如下,请问该如何在程序中UserFrame构造方法中第一行弹出一个类似的对话框?

//要求如下
/*
*如何在程序中UserFrame构造方法中第一行弹出一个类似的对话框,
*其中有两个输入框,分别输入用户名和密码,可以返回两个String
*而不采用如下split方法来分别验证用户名和密码?
*我曾试图自己写一个对话框,但是程序在弹出对话框后没有暂停执行等待输入,
*而是,即使不输入正确的用户名和密码,也会弹出UserFrame,代码如下:
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class UserFrame extends JFrame {
public UserFrame() {
// 即以下此行中是否有现成写好的类可以显示一个对话框,有两个输入框
String str = JOptionPane.showInputDialog(this, new String[] {
"Please input username", "password" }, "login",
DO_NOTHING_ON_CLOSE);
String username = null;
String password = null;
try {
if (str == null || "".equals(str.trim())) {
System.out.println("no input");
System.exit(0);
}
String[] info = str.split(",");
username = info[0];
password = info[1];
} catch (Exception e) {
System.exit(0);
}
if (username.equals("scott") && password.equals("tiger")) {
this.setContentPane(getContent());
this.setBounds(250, 100, 600, 480);
this.setTitle("UI");
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} else {
System.exit(0);
}
}

public JPanel getContent() {
JPanel panel = new JPanel();
JButton button = new JButton("doSomething");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("doSomething");
}
});
panel.add(button);
return panel;
}

public final static void main(String[] args) {
UserFrame uf = new UserFrame();
uf.setVisible(true);
}

}
如何写?

人到中年有点甜
浏览 146回答 2
2回答

绝地无双

可以使用JoptionPane:有几种提示框:第一种:JOptionPane.showMessageDialog(jPanel, "提示消息", "标题",JOptionPane.WARNING_MESSAGE);  第二种:int n = JOptionPane.showConfirmDialog(null, "你高兴吗?", "标题",JOptionPane.YES_NO_OPTION);//返回的是按钮的index  i=0或者1  第三种:Object[] obj2 ={ "足球", "篮球", "乒乓球" };  String s = (String) JOptionPane.showInputDialog(null,"请选择你的爱好:\n", "爱好", JOptionPane.PLAIN_MESSAGE, new ImageIcon("icon.png"), obj2, "足球");   

胡说叔叔

简单啊,你先不要让UserFrame的visible值设为true,就先弹出对话框,等对话框执行完再验证,如果验证通过就setVisible(true),否则直接exit就行了..具体自己实现吧...
打开App,查看更多内容
随时随地看视频慕课网APP