我正在尝试使用JDialog
作为String
的输入。但我得到的文本是在单击按钮之前。
这是我的对话框:
public class AddMemberDialog extends JDialog {
private JTextField name;
public AddMemberDialog() {
super(new JFrame("Add Member"), "Add Member");
this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
this.setMinimumSize(new Dimension(500, 500));
this.name = new JTextField();
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
close();
}
});
this.setLayout(new GridLayout(2, 1, 5, 5));
this.add(name);
this.add(add);
this.pack();
}
private void close(){ this.dispose(); }
public String getName(){ return this.name.getText(); }
}
这是我用来获取String
的内容:
AddMemberDialog input = new AddMemberDialog();
input.setLocationRelativeTo(this);
input.setVisible(true);
String txt = input.getName();
最佳答案
import javax.swing.JDialog;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
public class AddMemberDialog extends JDialog
{
private JTextField name;
public static void main(String[] args)
{
AddMemberDialog input = new AddMemberDialog();
input.setLocationRelativeTo(null);
input.setVisible(true);
}
public AddMemberDialog()
{
super(new JFrame("Add Member"), "Add Member");
this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
this.setMinimumSize(new Dimension(500, 500));
this.name = new JTextField();
JButton add = new JButton("Add");
add.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
close();
}
});
JButton takeInput = new JButton("takeInput");
takeInput.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String txt = getName();
System.out.println(txt);
}
}
);
this.setLayout(new GridLayout(3, 1, 5, 5));
this.add(name);
this.add(add);
this.add(takeInput);
this.pack();
}
private void close()
{
this.dispose();
}
public String getName()
{
return this.name.getText();
}
}
好吧,基本上,你的问题是,如果你只是留下代码
AddMemberDialog input = new AddMemberDialog();
input.setLocationRelativeTo(this);
input.setVisible(true);
String txt = input.getName();
当 IDE 到达该行代码时,它会自动接收您的输入。也就是说,除非您在 IDE 到达那里之前将某些内容放入其中(并且 IDE 在几毫秒内到达那里),否则之后它将不再需要输入。因此,为了补偿,我们不会让程序接受输入,直到我们准备好为止,因此需要一个按钮。在上面的代码中,我创建了一个新的 JButton
并将其命名为 takeInput
。还给了它一个 ActionListener 并在该 ActionListener 中让它执行您所要求的操作。现在,我可以控制输入何时发生。
关于java - 使用 JDialog 作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26594046/