0

I'm quite the beginner when it comes to java & coding in general, so I apologise for any overly obvious questions asked. I've just completed part of an application which reads data from an SQL database, then sends some stuff to print to socket depending on what information is read. I'm now trying to learn swing and get a GUI working with the application. Currently I have 2 forms, the first is used to select a printer, then the second will (hopefully) work as a log/ console which tells the user what and when stuff is happening. I've got the code and the forms together in a project.

I was wanting to find out how I can make the class which has my code in run when a Jbutton is pressed on a GUI, as well as how I can stop it from running when a different JButton is pressed.

The code from the Swing Form (Form2.java) is as follows:

package com.company;
import javax.swing.*;
public class Form2
{
private JTextArea jtaConsole;
private JPanel Jframer;
private JButton stopButton;
private JButton startButton;

public Form2(String message)
{
    JFrame frame = new JFrame("Print Application");
    frame.setContentPane(this.Jframer);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setResizable(true);
    frame.setVisible(true);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    jtaConsole.append("  Printer selected: " + message + "\n");
}

}

And the code from the class I want the JButton to run is as follows:

package com.company;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ZebraCode
{
public static void main(String[] args)
{
    {
        while (true)
        {
            //SQL login.
            String connectionString = "jdbc:sqlserver://:;database=;user=;password=!!;";

            //Select Data.
            String SQL = "SELECT TOP 2 [PK_PrintQueueID],[FK_PrinterID],[FK_BarcodeTypeID],[Barcode],[Quantity],[QueueDate],[ProcessedDate] FROM [Brad].[dbo].[PrintQueue] -- WHERE ProcessedDate IS NULL";

            //Connection Variable & Time Settings.
            Connection connection = null;
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();

            try
            {
                connection = DriverManager.getConnection(connectionString);
                Statement stmt = connection.createStatement();
                Statement stmt2 = null;
                ResultSet rs = stmt.executeQuery(SQL);
                while (rs.next())
                {
                    // Get barcode value to split & Set date.
                    String FK_BarcodeTypeID = rs.getString("FK_BarcodeTypeID");
                    String barcode = rs.getString("Barcode");
                    String[] parts = barcode.split("-");
                    String part1 = parts[0];
                    String SQL2 = "UPDATE PrintQueue SET ProcessedDate = '" + dateFormat.format(date) + "' WHERE PK_PrintQueueID = '" + rs.getString("PK_PrintQueueID")+"'";
                    stmt2 = connection.createStatement();
                    stmt2.executeUpdate(SQL2);

                    // Action based on type of barcode.
                    if (FK_BarcodeTypeID.equals("1"))
                    {
                        // Type 128 barcode.
                        String zpl = "^XA^BY2,3,140^FT80,200^BCN,Y,N,N^FD>:" + rs.getString("Barcode") + "^FS^FT200,250^A0N,42,40^FH^FD" + part1 + "^FS^XZ";
                        printlabel(zpl);
                        System.out.println("New serialized barcode added.\nPrinting: " + (rs.getString("Barcode")));
                        System.out.println("Process date: " + dateFormat.format(date) + ".\n");
                    }
                    else
                    {
                        // Type 39 barcode.
                        String zpl = "CT~~CD,~CC^~CT~ ^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR4,4~SD15^JUS^LRN^CI0^XZ^XA^MMT^PW674^LL0376 ^LS0 ^BY2,3,151^FT84,249^BCN,,Y,N^FD>:" + rs.getString("Barcode") + "^FS ^PQ1,0,1,Y^XZ";
                        printlabel(zpl);

                        System.out.println("New un-serialized barcode added.\nPrinting: " + (rs.getString("Barcode")));
                        System.out.println("Process date: " + dateFormat.format(date) + ".\n");
                    }
                }
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
            try
            {
                //Makes execution sleep for 5 seconds.
                Thread.sleep(5000);
            }
            catch (InterruptedException ez)
            {
            }
        }
    }
}

//Printer Info.
public static void printlabel(String zpl)
{
    try
    {
        Socket clientSocket;
        clientSocket = new Socket("", );
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        outToServer.writeBytes(zpl);
        clientSocket.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

}

Any tutorials or direction as to how I can learn this would be appreciated.

Thanks!

2
  • You are looking for a jbutton action listener Commented Jul 21, 2016 at 13:16
  • @Javant Thanks for the reply, I did think it would be via the action listener but i'm unsure what exactly how to get it to run the class Commented Jul 21, 2016 at 13:18

3 Answers 3

3

You want to add an action listener.. here is an example. Below are two examples on how to do so using lambdas and not using one.

    JButton button = new JButton("Click Me!");

     // Without lambda
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            // Code to execture when clicked
        }
    });


     //With lambda
      button.addActionListener(e -> {
        //code to execute when clicked
    });

I'd also advise you to do a little reading, http://www.tutorialspoint.com/design_pattern/mvc_pattern.htm

Sign up to request clarification or add additional context in comments.

Comments

2

Your question is a bit broad but let me offer some suggestions:

  • First off, you really don't want to have a JButton run the database code unchanged as doing this would be shoehorning a linear console program into an event-driven GUI, a recipe for disaster. Note that as written all your database code is held within a single static main method, and so there would be no way for the GUI to be able to control the running of that code. Either it runs or it doesn't, that's it, and no easy way for the database code to return its data to the GUI.
  • Instead first change that database code so that it is much more modular and OOP-friendly, including creating proper classes with state (instance fields) and behavior (instance methods), and getting almost all that code out of the static main method.
  • What I'm asking you to do is to create a proper model for your GUI, aka your view. Only after doing this would you have your GUI create a model object and call its methods on button push within your ActionListener. You will also want to call any long-running code within a background thread such as can be obtained with a SwingWorker.

Other issues:

  • You never initialize your JPanel or JTextArea variables, and so you're both adding a null variable as your JFrame's JPanel and calling methods on a null JTextArea variable, both of which will throw NullPointerExceptions.

2 Comments

Really appreciate the feedback - i'll take it on board and get to work. Feeling a bit like I'm in the deep-end and should probably work on my knowledge of the fundamentals more. Many thanks.
@braddarb: Re working on the fundamentals: yes, yes, YES!! I'm still doing this and it continually pays me dividends.
0

Here's a part of code I developed to better understand Java gui. I'm also a begginer. It's three classes: starter class, ongoing non gui processes, gui with the swingworker method. Simple, works, can safely update a lot of gui components from Swingworkers process method (passes a class instance as argument). Whole code so it can be copy/pasted:

package structure;

public class Starter {

public static void main(String[] args) {
    Gui1 thegui = new Gui1();   

}

}

LOGIC

    package structure;

public class Logical {
String realtimestuff;

public String getRealtimestuff() {
    return realtimestuff;
}

public void setRealtimestuff(String realtimestuff) {
    this.realtimestuff = realtimestuff;
}
//MAIN LOGICAL PROCESS..
public void process(){
    // do important realtime stuff
    if (getRealtimestuff()=="one thing"){
        setRealtimestuff("another thing");
    }else{setRealtimestuff("one thing");
}
    // sleep a while for readibility of label in GUI
    //System.out.println(getRealtimestuff());
    try {
        Thread.sleep(250);
    } catch (InterruptedException e) {
         System.out.println("sleep interrupted");
        return;
    }

}
}

GUI CLASS with Swingworker

package structure;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JLabel;
import java.util.List;
import javax.swing.*;

public class Gui1  {    

final class Dataclass{
    String stringtosend;    
    public Dataclass(String jedan){
        //super();
        this.stringtosend = jedan;
    }
    }

// EDT constructor
JFrame frame;
public Gui1(){
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {                   
                initialize();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });     
}

public void initialize() {
    // JUST A FRAME WITH A PANEL AND A LABEL I WISH TO UPDATE

    frame = new JFrame();
    frame.setBounds(100, 100, 200, 90);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    frame.getContentPane().add(panel, BorderLayout.NORTH);

    JLabel lblNovaOznaka = new JLabel();                
    panel.add(lblNovaOznaka);
    frame.setVisible(true);


    SwingWorker <Void, Dataclass> worker = new SwingWorker <Void, Dataclass>(){

        @Override
        protected Void doInBackground() throws Exception {                  
            Logical logic = new Logical();
            boolean looper = true;
            String localstring;
            while (looper == true){
                logic.process();
                localstring = logic.getRealtimestuff();                 
                publish(new Dataclass(localstring));

            }
            return null;
        }

        @Override
        protected void process(List<Dataclass> klasa) {
            // do a lot of things in background and then pass a loto of arguments for gui updates
            Dataclass xxx = klasa.get(getProgress());               
            lblNovaOznaka.setText(xxx.stringtosend);    

        }

    };
    worker.execute();

}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.