2013-10-09 69 views
2

我創建了一個自定義類,它返回一個JFrame,然後我傳入一個JOptionPane,因爲我需要兩個TextFields而不是一個JOptionPane。按下確定後,有什麼方法可以獲得返回值?返回值自定義JOptionPane,Java

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(); } 

回答

4

你的代碼是有點不尋常。讓我提出建議:

  • 不要爲您的JOptionPane使用JFrame,這有點古怪。
  • 避免過度使用靜態方法。面向對象是要走的路。
  • 創建一個類,爲您創建您的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 
} 

...另一類別處......

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或字符串的密碼,除非安全性不是您的應用程序的關注。改用JPasswordField和char數組。

+0

+1很好的新建議..但我不知道如果我會使用joption窗格或許只是一個jdialog – nachokk

+1

@nachokk:哦,我一直以這種方式使用JOptionPanes。他們可以容納非常複雜的GUI,並以一種很好的緊湊模式顯示對話框。 –

+1

@nachokk一個'JOptionPane'提供了許多必須自己編寫的功能,例如按鈕,並提供了一個非常靈活的API來提供非常可定製的解決方案。有時候你可能別無選擇,只能使用'JDialog',但是'JOptionPane'更有用的地方還有很多 - 恕我直言 – MadProgrammer