说到java&编码,所以我为任何过于明显的问题道歉。我刚刚完成了一个应用程序的一部分,该应用程序从SQL数据库读取数据,然后根据读取的信息将一些内容发送到套接字进行打印。我现在正在尝试学习swing,并获得一个与应用程序一起工作的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();
}
}
}
任何关于我如何学习的教程或指导都将不胜感激。
谢谢!
您想要添加一个动作侦听器。。这里有一个例子。下面是关于如何使用Lambda和不使用Lambda的两个例子。
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
你的问题有点宽泛,但让我提出一些建议:
- 首先,你真的不想让JButton运行数据库代码,因为这样做会把一个线性控制台程序硬塞进事件驱动的GUI中,这会带来灾难。请注意,在编写时,所有数据库代码都保存在一个静态主方法中,因此GUI无法控制该代码的运行。它要么运行,要么不运行,仅此而已,而且数据库代码将数据返回到GUI的方法并不简单
- 相反,首先更改数据库代码,使其更加模块化和面向对象,包括使用状态(实例字段)和行为(实例方法)创建适当的类,并从静态主方法中获取几乎所有的代码
- 我要求您为GUI创建一个合适的模型,也就是您的view。只有在这样做之后,您才能让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();
}
}
逻辑
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();
}
}