我正在创建一个返回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(); }
答案 0 :(得分:4)
您的代码有点不寻常。让我提出建议:
,即一个过于简单的例子......
public class MyPanel extends JPanel {
private JTextField field1 = new JTextField(10);
// .... other fields ? ...
public MyPanel() {
add(new JLabel("Field 1:");
add(field1);
}
public String getField1Text() {
return field1.getText();
}
// .... other getters for other fields
}
......在另一个班级的其他地方......
MyPanel myPanel = new MyPanel();
int result = JOptionPane.showConfirmDialog(someComponent, myPanel);
if (result == JOptionPane.OK_OPTION) {
String text1 = myPanel.getField1Text();
// ..... String text2 = ...... etc .....
// .... .use the results here
}
除此之外,不要使用JTextField或Strings作为密码,除非安全性不是您的应用程序的关注点。改为使用JPasswordField和char数组。