【问题标题】:Implementing GUI with Java application使用 Java 应用程序实现 GUI
【发布时间】:2017-06-26 23:03:25
【问题描述】:

一般来说,我是 Java 和编码方面的初学者,所以对于所提出的任何过于明显的问题,我深表歉意。我刚刚完成了从 SQL 数据库读取数据的应用程序的一部分,然后根据读取的信息将一些内容发送到套接字打印。我现在正在尝试学习摇摆并获得与应用程序一起使用的 GUI。目前我有两种形式,第一种用于选择打印机,然后第二种将(希望)用作日志/控制台,告诉用户发生了什么以及何时发生事情。我在一个项目中将代码和表格放在一起。

我想知道如何在 GUI 上按下 Jbutton 时让我的代码运行的类,以及当按下不同的 JButton 时如何阻止它运行。

来自 Swing Form (Form2.java) 的代码如下:

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");
}

}

我希望 JButton 运行的类中的代码如下:

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();
    }
}

}

任何关于我如何学习这一点的教程或指导将不胜感激。

谢谢!

【问题讨论】:

  • 您正在寻找一个 jbutton 动作监听器
  • @Javant 感谢您的回复,我确实认为它会通过动作监听器,但我不确定如何让它运行类

标签: java swing user-interface


【解决方案1】:

你想添加一个动作监听器。这是一个例子。下面是两个示例,说明如何使用 lambdas 而不是使用一个。

    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
    });

我还建议您阅读一下,http://www.tutorialspoint.com/design_pattern/mvc_pattern.htm

【讨论】:

    【解决方案2】:

    你的问题有点笼统,但让我提出一些建议:

    • 首先,您真的不想让 JButton 原封不动地运行数据库代码,因为这样做会将线性控制台程序硬塞到事件驱动的 GUI 中,这是灾难的根源。请注意,在编写时,所有数据库代码都保存在单个 static 主方法中,因此 GUI 无法控制该代码的运行。它要么运行,要么不运行,仅此而已,并且数据库代码没有简单的方法将其数据返回到 GUI。
    • 首先更改该数据库代码,使其更加模块化和 OOP 友好,包括创建具有状态(实例字段)和行为(实例方法)的适当类,并从静态 main 方法中获取几乎所有代码.
    • 我要您做的是为您的 GUI 创建一个合适的 模型,也就是您的 view。只有在这样做之后,您的 GUI 才会创建一个模型对象并在 ActionListener 中的按钮按下时调用其方法。您还需要在后台线程中调用任何长时间运行的代码,例如可以通过 SwingWorker 获得的代码。

    其他问题:

    • 您永远不会初始化您的 JPanel 或 JTextArea 变量,因此您既要添加一个空变量作为 JFrame 的 JPanel,又要在空 JTextArea 变量上调用方法,这两者都会抛出 NullPointerExceptions。

    【讨论】:

    • 非常感谢您的反馈 - 我会接受并开始工作。感觉有点像我在深渊,可能应该更多地利用我对基础知识的了解。非常感谢。
    • @braddarb:重新研究基础:是的,是的,是的!!我仍在这样做,它不断地给我带来红利。
    【解决方案3】:

    这是我为更好地理解 Java gui 而开发的部分代码。我也是一个初学者。 它是三个类:starter 类、正在进行的非 gui 进程、带有 swingworker 方法的 gui。简单,有效,可以安全地从 Swingworkers 进程方法更新许多 gui 组件(传递一个类实例作为参数)。整个代码,因此可以复制/粘贴:

    package structure;
    
    public class Starter {
    
    public static void main(String[] args) {
        Gui1 thegui = new Gui1();   
    
    }
    
    }
    

    逻辑

        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;
        }
    
    }
    }
    

    带有 Swingworker 的 GUI 类

    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();
    
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 1970-01-01
      • 2012-05-15
      • 2014-11-21
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多