java 浅谈JOptionPane


//也可利用JOptionPane的构造方法自定义对话框,

//如:自己做一个输入密码的对话框

 final JPasswordField field=new JPasswordField();
 field.setEchoChar('*');
 field.requestFocusInWindow();
 Object[] message = { "请输入当前用户密码:", field};
 JOptionPane pane = new JOptionPane(message, JOptionPane.INFORMATION_MESSAGE){ 
		private static final long serialVersionUID = 4268134471531397292L;
		public void paint(Graphics g) {
                    super.paint(g);
                    //设置光标位置,不能直接在实例化文本框对象后就直接调用requestFocus(),需要组件类重载paint方法,passwordinput是一个文本框对象,因为swing的图像显示的原理是执行了setVisible方法之后默认隐士执行paint方法,只有在paint方法之后设置光标位置才可以起作用,在paint或者setVisible之前设置之前还没有画出图形所以requestFocus()方法,在setVisible方法之前使用时不起作用的,需要重载paint方法就可以了
                    field.requestFocusInWindow();                     
                }
};
JDialog dialog = pane.createDialog(null, "输入");
dialog.setVisible(true);
String  inputValue=field.getText();

//下面是判断输入的密码是否正确…….

 

上面程序的错误:其对话框按钮不能自定义

改进:利用JOptionPane的showOptionDialog方法来自定义窗口

public class RegisterDialog{
    private final JPasswordField  field=new JPasswordField ();
    private int  option=-1;
    public RegisterDialog(Component parentComponent){
       //弹出注册对话框
        field.setEchoChar('*');
        field.requestFocusInWindow();
        Object[] options = { "注册", "取消"};
        Object[] message = { "请输入注册码:", field};
        option=JOptionPane.showOptionDialog(parentComponent,message,"注册码输入窗口",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null, options, options[0]);
    public int GetOption(){
       return option;
    }
    public String getInputCode(){
       String  inputValue=field.getText().trim();
       return  inputValue;
    }
}



posted on 2012-07-20 15:13  java课程设计例子  阅读(332)  评论(0编辑  收藏  举报