2010-04-12 85 views
5

我伸出的JDialog創建一個自定義對話框中輸入輸入了用戶必須填寫一些字段: dialog http://www.freeimagehosting.net/uploads/3d4c15ed9a.jpg檢索一個JDialog

我應該如何檢索輸入的數據?

我想出了一個可行的解決方案。它模仿的JOptionPane,但我做的方式,它看起來醜陋的我,因爲所涉及的靜態字段...這裏是我的粗略代碼:

public class FObjectDialog extends JDialog implements ActionListener { 
    private static String name; 
    private static String text; 
    private JTextField fName; 
    private JTextArea fText; 
    private JButton bAdd; 
    private JButton bCancel; 

    private FObjectDialog(Frame parentFrame) { 
     super(parentFrame,"Add an object",true); 
     // build the whole dialog 
     buildNewObjectDialog(); 
     setVisible(true); 
    } 

    @Override 
    public void actionPerformed(ActionEvent ae) { 
     if(ae.getSource()==bAdd){ 
      name=fName.getText(); 
      text=fText.getText(); 
     } 
     else { 
      name=null; 
      text=null; 
     } 
     setVisible(false); 
     dispose(); 
    } 

    public static String[] showCreateDialog(Frame parentFrame){ 
     new FObjectDialog(parentFrame); 
     String[] res={name,text}; 
     if((name==null)||(text==null)) 
      res=null; 
     return res; 
    } 
} 

正如我所說的,可以正常工作,但我想這可能會引起嚴重併發問題...

有沒有更簡單的方法來做到這一點?它如何在JOptionPane中完成?

+0

你使用什麼外觀和感覺? – 2010-04-12 07:32:16

+1

@Martijn Courteaux:Nimbus(http://stackoverflow.com/questions/2616448/im-tired-of-jbuttons-how-can-i-make-a-nicer-gui-in-java);-) – 2010-04-12 07:39:43

回答

10

如果我這樣做,我一直是這樣的:

FObjectDialog fod = new FObjectDialog(this); 
fod.setLocationRelativeTo(this); // A model doesn't set its location automatically relative to its parent 
fod.setVisible(true); 
// Now this code doesn't continue until the dialog is closed again. 
// So the next code will be executed when it is closed and the data is filled in. 
String name = fod.getName(); 
String text = fod.getText(); 
// getName() and getText() are just two simple getters (you still have to make) for the two fields their content 
// So return textField.getText(); 

希望這有助於! PS:你的程序看起來不錯!

+0

Ooooooooh當然 !我不知道爲什麼我會陷入那些靜態的領域......在我看來,物體在處理完窗戶之後被毀壞了,但實際上並非如此。謝謝 ! – 2010-04-12 07:38:07

1

如果你打算同時顯示多個對話框,那麼你就會遇到併發問題,而不是其他問題。然而,擺脫所有靜態的東西將使設計更清潔,更安全,更容易測試。只需從調用代碼中控制創建和顯示對話框,並且不需要任何靜態內容。