如何将文本字段从主类 pri 传递到 CounterTask1 类。
下面的程序是一个例子。实际程序包含类似的结构。
在 CounterTask1 类中,文本字段添加了另一个字符串。如果单击打印按钮,它应该在终端中打印文本字段。
提前谢谢。
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