我正在创建一个返回 JFrame 的自定义类,然后将其传递给 JOptionPane,因为我需要 JOptionPane 中的两个 TextField 而不是一个。有什么方法可以在按下 OK 时获得返回值?
public static JFrame TwoFieldPane(){
JPanel p = new JPanel(new GridBagLayout());
p.setBackground(background);
p.setBorder(new EmptyBorder(10, 10, 10, 10) );
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
p.add(new JLabel(field1), c);
c.gridx = 0;
c.gridy = 1;
p.add(new JLabel(field2), c);
//p.add(labels, BorderLayout.WEST);
c.gridx = 1;
c.gridy = 0;
c.ipadx = 100;
final JTextField username = new JTextField(pretext1);
username.setBackground(foreground);
username.setForeground(textcolor);
p.add(username, c);
c.gridx = 1;
c.gridy = 1;
JTextField password = new JTextField(pretext2);
password.setBackground(foreground);
password.setForeground(textcolor);
p.add(password, c);
c.gridx = 1;
c.gridy = 2;
c.ipadx = 0;
JButton okay = new JButton("OK");
okay.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
f.setVisible(false);
//RETURN VALUE HERE
}
});
p.add(okay, c);
f.add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
return f;
}
这就是我创建它的地方:
try{
JOptionPane.showInputDialog(Misc.TwoFieldPane("Server ip: ", "" , "Port: ", ""));
}catch(IllegalArgumentException e){e.printStackTrace(); }