如何将文本字段从主类pri传递给CounterTask1类。
以下程序就是一个例子。真正的程序包含类似的结构。
在CounterTask1类中,textfield添加另一个字符串。如果单击打印按钮,它应该在终端中打印文本字段。
预先谢谢。
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.SwingWorker;
import java.util.List;
public class pri
{
JFrame Frame1 = new JFrame();
JLabel SourceLabel1 = new JLabel("Source Name");
JTextField SourceField1 = new JTextField(20);
public void MainFrame()
{
final CounterTask1 task1 = new CounterTask1();
Frame1.setLayout(null);
JButton Print = new JButton("Print");
Print.setBounds(10,10,100,30);
Print.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent ae)
{ String sourcename=SourceField1.getText();
System.out.println("Printing in Terminal "+sourcename);
task1.execute(); } });
JButton Exit = new JButton("Exit");
Exit.setBounds(10,50,100,30);
Exit.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent ae)
{ System.exit(0); } });
SourceField1.setBounds(130,10,100,30);
Frame1.add(SourceField1);
Frame1.add(Print);
Frame1.add(Exit);
Frame1.pack();
Frame1.setSize(250,150);
Frame1.setLocation(100,100);
Frame1.setVisible(true);
Frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} //MainFrame
public static void main(String[] args)
{ SwingUtilities.invokeLater(new Runnable()
{ public void run()
{
pri frame = new pri();
frame.MainFrame(); } });
}
}
class CounterTask1 extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
String one = SourceField1.getText();
String two = "Thanks !";
String Addst = one +two ;
System.out.println("printing in Task" + Addst);
return 0;
}// protected main class
protected void process(List<Integer> chunks)
{
System.out.println(chunks);
}
} // counter task
答案 0 :(得分:3)
我会以不同的方式做事 - 将文本传递给构造函数中的SwingWorker:
Print.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String sourcename = SourceField1.getText();
System.out.println("Printing in Terminal " + sourcename);
// note change in constructor
// this way getText() is called on the EDT.
CounterTask1 task1 = new CounterTask1(SourceField1.getText());
task1.execute();
}
});
在另一个班级:
class CounterTask1 extends SwingWorker<Integer, Integer> {
private String text;
public CounterTask1(String text) {
this.text = text;
}
protected Integer doInBackground() throws Exception {
String one = text;
String two = "Thanks !";
String Addst = one + two;
System.out.println("printing in Task" + Addst);
return 0;
}
注意:
doInBackground()
方法进行Swing调用。