0
我想創建一個簡單的揮杆形式,它將接收來自用戶的輸入。棘手的部分是,我希望窗體的構造函數在用戶點擊按鈕之前停止程序流。例如:防止流程繼續進行,直到在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()方法,直到用戶點擊調用一個ActionListener Swing的形式,構造函數產生的按鈕前。
這裏是輸入代碼:
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()方法時釋放它,但我不知道如何做到這一點。
非常感謝!
哪裏是主題? –
我相信你正在尋找的是一個模態對話框;然而,你知道[JOptionPane可以做到這一點](http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#input)? – Radiodef