用Java应用程序实现GUI
一般来说,我是java和编码的初学者,因此,对于任何过于明显的问题,我深表歉意。我刚刚完成了一个应用程序的一部分,该应用程序从SQL数据库读取数据,然后根据读取的信息将一些内容发送到socket进行打印。我现在正在尝试学习swing,并获得一个GUI来使用该应用程序。目前我有两个表单,第一个用于选择打印机,第二个(希望)将作为日志/控制台,告诉用户发生了什么以及什么时候发生了事情。我在一个项目中把代码和表单放在一起 我想知道,当在GUI上按下一个Jbutton时,如何使代码处于运行状态的类,以及当按下另一个Jbutton时,如何使其停止运行 Swing表单(Form2.java)中的代码如下:用Java应用程序实现GUI,java,swing,user-interface,Java,Swing,User Interface,一般来说,我是java和编码的初学者,因此,对于任何过于明显的问题,我深表歉意。我刚刚完成了一个应用程序的一部分,该应用程序从SQL数据库读取数据,然后根据读取的信息将一些内容发送到socket进行打印。我现在正在尝试学习swing,并获得一个GUI来使用该应用程序。目前我有两个表单,第一个用于选择打印机,第二个(希望)将作为日志/控制台,告诉用户发生了什么以及什么时候发生了事情。我在一个项目中把代码和表单放在一起 我想知道,当在GUI上按下一个Jbutton时,如何使代码处于运行状态的类,以及
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");
}
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运行的类中的代码如下:
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");
}
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();
}
}
}
任何关于如何学习的教程或指导都将不胜感激
谢谢 您想添加一个操作侦听器。。这里有一个例子。下面是关于如何使用lambdas和不使用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
});
我还建议你读一读,你想添加一个动作监听器。。这里有一个例子。下面是关于如何使用lambdas和不使用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
});
我还建议你读一读,你的问题有点宽泛,但让我提供一些建议:
- 首先,您确实不希望JButton不加更改地运行数据库代码,因为这样做会将线性控制台程序塞进事件驱动的GUI中,这会导致灾难。请注意,在编写时,所有数据库代码都保存在一个静态main方法中,因此GUI无法控制该代码的运行。它要么运行,要么不运行,就是这样,数据库代码没有简单的方法将数据返回到GUI
- 相反,首先更改数据库代码,使其更加模块化和面向对象友好,包括使用状态(实例字段)和行为(实例方法)创建适当的类,并从静态main方法中获取几乎所有的代码李>
- 我要你做的是为你的GUI,也就是你的视图,创建一个合适的模型。只有这样做之后,您的GUI才会创建一个模型对象,并在ActionListener中的按钮按钮上调用其方法。您还需要调用后台线程中的任何长时间运行的代码,例如可以通过SwingWorker获得的代码
- 您从不初始化JPanel或JTextArea变量,因此您都在添加一个null变量作为JFrame的JPanel,并对null JTextArea变量调用方法,这两个变量都会引发NullPointerException
- 首先,您确实不希望JButton不加更改地运行数据库代码,因为这样做会将线性控制台程序塞进事件驱动的GUI中,这会导致灾难。请注意,在编写时,所有数据库代码都保存在一个静态main方法中,因此GUI无法控制该代码的运行。它要么运行,要么不运行,就是这样,数据库代码没有简单的方法将数据返回到GUI
- 相反,首先更改数据库代码,使其更加模块化和面向对象友好,包括使用状态(实例字段)和行为(实例方法)创建适当的类,并从静态main方法中获取几乎所有的代码李>
- 我要你做的是为你的GUI,也就是你的视图,创建一个合适的模型。只有这样做之后,您的GUI才会创建一个模型对象,并在ActionListener中的按钮按钮上调用其方法。您还需要调用后台线程中的任何长时间运行的代码,例如可以通过SwingWorker获得的代码
- 您从不初始化JPanel或JTextArea变量,因此您都在添加一个null变量作为JFrame的JPanel,并对null JTextArea变量调用方法,这两个变量都会引发NullPointerException
- 你的问题有点宽泛,但让我提出一些建议:
- 以下是我为更好地理解Java gui而开发的部分代码。我也是个乞丐。
它有三个类:初学者类、正在进行的非gui进程、带有swingworker方法的gui。简单有效,可以安全地从Swingworkers进程方法(将类实例作为参数传递)更新许多gui组件。完整的代码,以便可以复制/粘贴:
package structure;
public class Starter {
public static void main(String[] args) {
Gui1 thegui = new Gui1();
}
}
逻辑
带有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();
}
}
包结构;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入java.awt.BorderLayout;
导入java.awt.EventQueue;
导入javax.swing.JLabel;
导入java.util.List;
导入javax.swing.*;
公共类Gui1{
最终类数据类{
弦向弦;
公共数据类(字符串jedan){
//超级();
this.stringtosend=jedan;
}
}
//EDT构造函数
JFrame框架;
公共GUI 1(){
invokeLater(新的Runnable(){
公开募捐{
试试{
初始化();
}捕获(例外e){
e、 printStackTrace();
}
}
});
}
公共无效初始化(){
//只是一个有面板和标签的框架,我想更新
frame=新的JFrame();
机架立根(10010020090);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel面板=新的JPanel();
frame.getContentPane().add(面板,BorderLayout.NORTH);
JLabel lblNovaOznaka=新JLabel();
补充小组(Lblnovoznaka);
frame.setVisible(true);
SwingWorker worker=新SwingWorker(){
@凌驾
受保护的