此问题已在此处找到答案:
如何使此方法更新循环中的gui((2个答案)
使用swingworker不断更新gui(2个答案)
昨天关门了。
为清晰起见更新我有两个类example.java(带有gui的主类)taskclassexample.java
如何使example.java调用方法taskclassexample.task,并且在该方法运行时,我需要progress变量中的字符串来更新gui中的textpane。
我希望此任务不会阻止我的主线程,但是该按钮将被禁用,直到任务方法结束,然后它将被重新启用。
谢谢
Example.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class example extends JFrame {
private JPanel contentPane;
private taskClassExample task = new taskClassExample();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
example frame = new example();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public example() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 648, 417);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(180, 196, 273, 66);
contentPane.add(btnNewButton);
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setBounds(198, 10, 238, 176);
contentPane.add(textPane);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// disable button after click
btnNewButton.setEnabled(false);
//THIS TASK TO RUN IN BACK GROUND
task.task();
// the text from progress variable in the above message to be appended to text box
textPane.setText(task.progress);
//re-enable button after task has completed
btnNewButton.setEnabled(true);
}
});
}
}
taskClassExample.java
public class taskClassExample {
private String progress;
public taskClassExample() {
}
public int task() {
//this method carrys out a background task an updates progress string throughout
progress = "Starting";
System.out.println(progress);
killTime(5000);
progress = "hitting the flux capacitor";
System.out.println(progress);
killTime(5000);
progress = "servicing Mr. Fusion";
System.out.println(progress);
killTime(5000);
progress = "tuning Time circuits";
System.out.println(progress);
killTime(5000);
progress = "cleaning Plutonium chamber";
System.out.println(progress);
killTime(5000);
progress = "configuring Roentgen meter";
System.out.println(progress);
killTime(5000);
progress = "finished";
System.out.println(progress);
return 1;
}
public void killTime(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
暂无答案!
目前还没有任何答案,快来回答吧!