我有一个带有JTextField和JButton的JFrame。我希望它的行为类似于JOptionPane.showInputDialog()。基本上,我想构造它,然后调用.start()或使其可见的东西然后等待按下按钮然后返回JTextField的内容。我听说wait()/ notify()可能会这样做,但我不知道这是否正确,如果是,我能看到一个如何使用它的简短示例吗?
答案 0 :(得分:3)
JDialog也是您自定义输入对话框的解决方案,有一个库可以帮助您加快开发速度。它被称为TaskDailog。
http://code.google.com/p/oxbow/wiki/TaskDialogIntroduction?tm=6
的更多信息答案 1 :(得分:3)
以下使用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);
}
}