import javax.swing.*l
public class JframeTest { public static void main(String[] args){
String input = JOptionPane.showInputDialog("plase input your pass");
int k = Integer.parseInt(input);
........}}
public class JframeTest { public static void main(String[] args){
String input = JOptionPane.showInputDialog("plase input your pass");
int k = Integer.parseInt(input);
........}}
而且如果parseInt的话要捕捉异常的
String input = JOptionPane.showInputDialog("plase input your pass");判断,如果密码不对:
if(!input.equals(youpass)){
return;
}程序A
因为这些都是模式的对话框,所以在响应前是不会执行你主程序中
的后续代码的,当然你也可以自己来写一个继承于Dialog的类,
里面放一个私有的属性和返回这个属性值的方法。以下是我匆匆写的一个例子,用isAdmit私有属性及返回其值的方法
来获取是否显示主窗体,整体的控制都在主类中,密码是123
如果输入123则显示主窗体,否则一直让你输入密码,当然可以关闭
密码输入的对话框来结束程序。//PFrame.java
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;class LoginFrame extends JDialog
{
JLabel jl;
JPasswordField jpf;
JButton jb;
JPanel jp_lp,jp_ok;
private boolean isAdmit=false;
LoginFrame()
{
this.setModal(true);
this.toFront();
this.setTitle("登陆");
this.setSize(300,120);
this.setLocation(350,200);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
jl=new JLabel("请输入密码:");
jpf=new JPasswordField(10);
jb=new JButton("Login");
jb.addActionListener(new ActionHandler());
jp_lp=new JPanel();
jp_lp.setLayout(new FlowLayout());
jp_lp.add(jl);
jp_lp.add(jpf);
jp_ok=new JPanel();
jp_ok.setLayout(new FlowLayout());
jp_ok.add(jb);
Container cp=this.getContentPane();
cp.setLayout(new BorderLayout());
cp.add(jp_lp,BorderLayout.NORTH);
cp.add(jp_ok,BorderLayout.SOUTH);
}//LoginFrame() over
class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent jb_click)
{
char inp[]=jpf.getPassword();
String sinp=new String(inp);
if(sinp.equals("123"))
{
//System.out.println("Password ok");
isAdmit=true;
LoginFrame.this.dispose();
}else
{
JOptionPane.showMessageDialog(null,"密码不正确,无法登陆!","错误",JOptionPane.WARNING_MESSAGE);
LoginFrame.this.jpf.setText("");
}
}
}//ActionHandler over
public boolean canLogin()
{
return isAdmit;
}
}
class MainForm extends JFrame
{
MainForm()
{
this.setTitle("主窗体");
this.setBounds(200,200,350,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class PFrame
{
public static void main(String[] args)
{
LoginFrame lf=new LoginFrame();
lf.show();
if(lf.canLogin())
{
new MainForm().setVisible(true);
}
}
}
public static void main(String[] args) {
String inputPass = JOptionPane.showInputDialog("plase input your pass");
String yourPass = "ab";
if (!inputPass.equals(yourPass)) {
System.exit(0);
}
else {
PassFrame frame = new PassFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
}class PassFrame extends JFrame {
public PassFrame() {
setSize(200,100);
setTitle("密码验证");
}
}