我有一个简单的应用程序和一些线程,我需要从某个线程更新SWING GUI(我使用Netbeans)。
这是我需要更新的主要表格:
public class mainForm extends javax.swing.JFrame {
private gameControll obj;
public mainForm() {
initComponents();
}
public void runAuto(){
ThreadTest th1 = new ThreadTest(1, 1, obj);
ThreadTest th8 = new ThreadTest(8, 95000, obj);
ThreadTest th2 = new ThreadTest(2, 100000, obj);
ThreadTest th3 = new ThreadTest(3, 120000, obj);
ThreadTest th4 = new ThreadTest(4, 140000, obj);
ThreadTest th22 = new ThreadTest(22, 1000, obj);
Thread thread1 = new Thread(th1);
Thread thread2 = new Thread(th2);
Thread thread3 = new Thread(th3);
Thread thread4 = new Thread(th4);
Thread thread22 = new Thread(th22);
Thread thread8 = new Thread(th8);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread22.start();
thread8.start();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
mainForm app = new mainForm();
app.setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField pathtbox;
}
现在我有一些线索:
public class ThreadTest implements Runnable {
public static mainForm main = new mainForm();
private final int functionNumber;
private final int time2start;
public ThreadTest(int functionNumber, int time2start, gameControll obj){
this.functionNumber = functionNumber;
this.time2start = time2start;
}
@Override
public void run(){
try{Thread.sleep(time2start);}catch(Exception ex){}//Time Delay before executing methods
switch(functionNumber){
case 1:
//System.out.println("case 1");
obj.runFirst();
break;
case 2:
// System.out.println("case 2");
obj.runSecond();
break;
case 3:
{
try {
obj.runThird();
} catch (IOException ex) {
Logger.getLogger(ThreadTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
break;
...
在其他一些课程中我有:
public void runFirst(){
System.out.println("I need to show this text on jlabel5");
}
代码的每个部分都在不同的文件(类)中。 我如何在这里实现Swing worker才能在我的主GUI表单上显示文本?
答案 0 :(得分:1)
我如何在这里实现Swing worker才能在我的主GUI表单上显示文本?
根据您的代码中观察到的功能列表:
在这种情况下,IMO Swing Timer比Swing工作者更适合。您可以定义多个具有Runnable
类实例访问权限的计时器,而不是使用实现MainForm
接口的类,以便执行所需的操作并更新相同的表单(现在您创建一个新表单作为ThreadTest
类的类成员。例如:
Timer timer1 = new Timer(1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainFrame.runFirst();
}
});
timer1.setRepeats(false);
Timer timer2 = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainFrame.runSecond();
}
});
timer2.setRepeats(false);
...
timer1.start();
timer2.start();
...
MainFrame#runFirst()
应该是这样的:
public void runFirst() {
jlabel5.setText("Label#5 updated from Timer!");
}