2010-04-12 86 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

如果你打算同时显示多个对话框,那么你就会遇到并发问题,而不是其他问题。然而,摆脱所有静态的东西将使设计更清洁,更安全,更容易测试。只需从调用代码中控制创建和显示对话框,并且不需要任何静态内容。