import javax.swing.*;
import java.awt.event.*;
public class Test {
private String textFieldValue;
public Test() {
JFrame frame = new JFrame ();
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("OK");
panel.add(label);
panel.add(textField);
frame.getContentPane().add(panel);
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );
frame.setVisible(true);
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
textFieldValue = textField.getText();
frame.dispose();
System.out.println("inside= " + textFieldValue);
}
});
panel.add(button);
}
public String getValue() {
return textFieldValue;
}
public static void main(String[] args) {
Test test = new Test();
System.out.println("outside= " + test.getValue());
}
}
请问有人可以帮忙吗? 通过运行上述代码,变量“textFieldValue”尚未分配在 JTextField 对象中输入的值:textField。
任何帮助将不胜感激!
如果您想阻止其他组件直到收到用户输入,您可以使用 JDialog 而不是 jFrame。
JDialog dialog = new JDialog();
...
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
textFieldValue = textField.getText();
System.out.println("inside = " + textFieldValue);
dialog.dispose(); // Close dialog
}
});
...
panel.add(button);
dialog.getContentPane().add(panel);
dialog.setSize(500, 300);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setModal(true); // Make it modal to block the main thread
dialog.setVisible(true);
或一次输入一个
textFieldValue = JOptionPane.showInputDialog("Enter your name: ");