检索 JDialog 中输入的输入
我扩展了 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 中是如何完成的?
I extended JDialog to create a custom dialog where the user must fill some fields :
How should I retrieve the data entered ?
I came up with a solution that works. It mimics JOptionPane but the way I do it looks ugly to me because of the static fields involved... Here is roughly my code :
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;
}
}
As I said, that works properly, but I guess that might raise serious concurrency issues...
Is there a cleaner way to do that ? How is it done in JOptionPane ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我这样做,我总是这样工作:
希望这有帮助!
PS:你的程序看起来很棒!
If I do this, I always works like this:
Hope this helps!
PS: Your program looks great!
如果您打算同时显示多个对话框,那么您就会遇到并发问题,否则不会。然而,摆脱所有静态的东西会让设计更干净、更安全、更容易测试。只需通过调用代码控制对话框的创建和显示,您不需要任何静态内容。
If you intend to display multiple dialogs at the same time, then you have concurrency issues, not otherwise. However, getting rid of all the static stuff would make the design cleaner, safer and easier to test. Just control the creation and showing of the dialog from the calling code and you don't need any static stuff.