我有一个带有JTextField和JButton的JFrame。我希望它的行为像JOptionPane.showInputDialog()。基本上,我想构造它,然后调用.start()或使其可见的东西,然后等待按钮按下,然后返回JTextField的内容。我听说过wait()/ notify()可能会这样做,但是我不知道这是否正确,如果正确,我能否看一下使用它的简短示例?
最佳答案
在这里尝试使用JDialog
这个代码示例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogExample extends JFrame
{
private JLabel nameLabel;
public DialogExample()
{
super("Dialog Example");
}
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
nameLabel = new JLabel();
contentPane.add(nameLabel);
setContentPane(contentPane);
setSize(200, 100);
setLocationByPlatform(true);
setVisible(true);
MyDialog dialog = new MyDialog(this, "Credentials : ", true);
dialog.createAndDisplayGUI();
}
public void setName(String name)
{
if (name.length() > 0)
nameLabel.setText(name);
else
nameLabel.setText("Empty string received.");
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new DialogExample().createAndDisplayGUI();
}
});
}
}
class MyDialog extends JDialog
{
private JTextField nameField;
private JFrame frame;
public MyDialog(JFrame f
, String title, boolean isModal)
{
super(f, title, isModal);
frame = f;
}
public void createAndDisplayGUI()
{
JPanel contentPane = new JPanel();
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel nameLabel = new JLabel("Please Enter your Name : ");
nameField = new JTextField(10);
JButton submitButton = new JButton("SUBMIT");
submitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (nameField.getDocument().getLength() > 0)
frame.setName(nameField.getText());
else
frame.setName("");
MyDialog.this.dispose();
}
});
contentPane.add(nameLabel);
contentPane.add(nameField);
contentPane.add(submitButton);
add(contentPane);
pack();
setVisible(true);
}
}