我想创建一个简单的swing表单,它将接收来自用户的输入。棘手的部分是我希望表单的构造函数停止程序的流程,直到用户点击按钮。例如:
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello, please enter your name");
String name = new Input().getText();
JOptionPane.showMessageDialog(null, "Hello " + name);
}
我想在调用getText()方法之前在Input的构造函数内停止流,直到用户点击构造函数生成的Swing窗体上调用ActionListener的按钮。
以下是输入代码:
import java.awt.BorderLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class Input extends JFrame{
private static final long serialVersionUID = 1L;
private String text;
private JPanel panel;
private JTextArea textArea;
private JButton button;
public Input(){
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new BorderLayout(3,3));
textArea = new JTextArea(5,10);
button = new JButton("submit");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setText(textArea.getText());
}
});
panel.add(textArea, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
textArea.setSize(1500, 1500);
add(panel);
pack();
setVisible(true);
}
public synchronized String getText() {
while(text==null)
try {
this.wait();
} catch (InterruptedException e) {}
try {
return text;
} finally {
dispose();
}
}
public synchronized void setText(String text) {
this.text = text;
notifyAll();
}
}
我的感觉是,需要做的是构造函数以某种方式获取主要运行的线程的锁定,并且仅在从ActionListener调用setText()方法时释放它,但是我不知道该怎么做。
非常感谢!!!
答案 0 :(得分:1)
您可以尝试在ActionListener
中进一步处理:
@Override
public void actionPerformed(ActionEvent arg0) {
String name = textArea.getText();
// ans so on, and then:
JOptionPane.showMessageDialog(null, "Hello " + name);
}