源代码如下,想让用户通过对话框进行输入,但是创建对话框后程序是不能正常退出了,请问应该怎么解决?package test;import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class main {
public static void main(String[] args) {
int a ;
AboutDialog dia = new AboutDialog();
System.out.println(dia.data);
dia.setVisible(true);
System.out.println(dia.data);
}
}
class AboutDialog extends JDialog
{
int data;
public AboutDialog()
{ super();
setModal(true);
data = 0;
JPanel p2 = new JPanel();
JButton one = new JButton("1");
p2.add(one);
JButton two = new JButton("2");
p2.add(two);
JButton three = new JButton("3");
p2.add(three);
getContentPane().add(p2, "South"); one.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
data = 1;
setVisible(false); }
} );
two.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
data = 2;
setVisible(false); }
} );
three.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
data = 3;
setVisible(false); }
} ); setSize(250, 150);
}
}
import java.awt.event.*;
import javax.swing.*;
class main {
public static void main(String[] args) {
int a ;
AboutDialog dia = new AboutDialog();
System.out.println(dia.data);
dia.setVisible(true);
System.out.println(dia.data);
}
}
class AboutDialog extends JDialog
{
int data;
public AboutDialog()
{ super();
setModal(true);
data = 0;
JPanel p2 = new JPanel();
JButton one = new JButton("1");
p2.add(one);
JButton two = new JButton("2");
p2.add(two);
JButton three = new JButton("3");
p2.add(three);
getContentPane().add(p2, "South"); one.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
data = 1;
setVisible(false); }
} );
two.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
data = 2;
setVisible(false); }
} );
three.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
data = 3;
setVisible(false); }
} ); setSize(250, 150);
}
}
public static void main(String[] args){
String name = JOptionPane.showInputDialog("请输入您的姓名:");
if(name != null){
System.out.println("姓名:" + name);
}
}
你在你的程序的3个地方改下
one.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
data = 1;
setVisible(false);
System.out.println(data);
System.exit(0);}
} );
再把main函数中的最后一条打印语句注释掉
我个人认为代码本身并没有什么问题,而是你的思路和用法出现了偏差。
如果,你想要反复使用一个对话框,那么,不会要求关闭这个对话框的时候,程序退出吧?
正常来说,一定会有窗口,比如一个JFrame实例,打开这个模式对话框,然后经过输入,点击比如确定按钮,这时模式窗口不可见(或销毁)。你也可以获得你想要的数据,但是请注意,程序并不退出,当你关闭这个对话框的父窗口的时候才去退出。
总而言之,你这里做的只是一个局部的工作。关闭的时候,模式对话框能够选择的只有
DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, or DISPOSE_ON_CLOSE
而关闭即退出的EXIT_ON_CLOSE是一个不合法参数。
你最好做一个父窗体来打开这个对话框。还有,你的public类在哪?main最好类名大些,而且既然主函数在这里,前面就用public修饰一下。
也可以用 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)