从自定义 JOptionPane 返回值,Java

Kyr*_*tar 2 java swing return joptionpane

我正在创建一个返回 JFrame 的自定义类,然后将其传递到 JOptionPane 中,因为我需要 JOptionPane 中的两个 TextField,而不是一个。当按下“确定”时,有什么方法可以获得返回值吗?

 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;
}
Run Code Online (Sandbox Code Playgroud)

这就是我创建它的地方:

try{
    JOptionPane.showInputDialog(Misc.TwoFieldPane("Server ip: ", "" , "Port: ", ""));
    }catch(IllegalArgumentException e){e.printStackTrace(); }
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

你的代码有点不寻常。我来提一下建议吧:

  • 不要将 JFrame 用于 JOptionPane,这有点古怪。
  • 避免过度使用静态方法。OOP 是必经之路。
  • 创建一个类,该类为您创建 JOptionPane 的 JPanel 并且具有实际的实例字段。
  • 为类提供 getter 方法,允许您在 JOptionPane 返回后查询其状态。
  • 创建 JOptionPane 并给它一个从上面的类创建的 JPanel。
  • JOptionPane 返回后,查询放置在其中的对象的字段状态。

即,一个过于简单的例子......

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
}
Run Code Online (Sandbox Code Playgroud)

...在另一个班级的其他地方...

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
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,不要使用 JTextField 或字符串作为密码,除非您的应用程序不关心安全性。请改用 JPasswordField 和 char 数组。