制作一个单纯的登陆窗口,加入简单的登录验证,退出提示,弹窗提示
package com.koow.swing.test;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JPasswordField;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Popup extends JFrame implements ActionListener {
JButton login = new JButton("登录"); //登陆按钮
JButton exit =new JButton("退出"); //退出按钮
JLabel name =new JLabel("用户名:"); //用户名标签
JLabel password= new JLabel("密码:"); //密码标签
JLabel code=new JLabel("验证码:"); //验证码标签
JTextField JName=new JTextField(10); //明文账号输入
JPasswordField JPassword=new JPasswordField(10);//非明文密码输入
JTextField Code=new JTextField(10); //明文验证码输入
public Popup(){
JPanel jp=new JPanel(); //面板容器类,包含在javax.swing 包中,可以进行嵌套,功能是对窗体中具有相同逻辑功能的组件进行组合。
jp.setLayout(new GridLayout(4,2)); //4行2列的面板jp(网格布局)
this.name.setHorizontalAlignment(SwingConstants.RIGHT); //设置该组件的对齐方式为向右对其
this.password.setHorizontalAlignment(SwingConstants.RIGHT);
this.code.setHorizontalAlignment(SwingConstants.RIGHT);
jp.add(this.name); //将内容加在面板jp上
jp.add(this.JName);
jp.add(this.password);
jp.add(this.JPassword);
jp.add(this.code);
jp.add(this.Code);
jp.add(this.login);
jp.add(this.exit);
this.login.addActionListener(this); //登录增加事件监听
this.exit.addActionListener(this); //退出增加事件监听
this.add(jp,BorderLayout.CENTER); //将整块面板定义在中间
this.setTitle("登录"); //设置窗口名称
this.setLocation(500,300); //设置初始位置
this.pack(); //表示随着面板自动调整大小
this.setVisible(true); //设置窗体可见,没有该语句,窗体将不可见
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置点击界面关闭按钮时,执行的操作是退出,否则程序还驻留在内存中没有结束
}
public void actionPerformed(ActionEvent e){ //对事件进行处理
if(e.getSource()==this.exit){
int i=JOptionPane.showConfirmDialog(null, "确定要退出吗?","提示",JOptionPane.YES_NO_OPTION);
//显示选择对话框
if(i==JOptionPane.YES_OPTION){
System.exit(0); //程序退出
}
}else{
if(this.JName.getText().equals("koow") && String.valueOf(JPassword.getPassword()).equals("123123")){
JOptionPane.showMessageDialog(null, "登陆成功,"+(this.Code.getText()==null||this.Code.getText().equals("")?"没有输入验证码":"验证码为:"+this.Code.getText())+",程序退出");
//显示信息提示框
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "用户或密码错误!请重新登录!");
//显示信息提示框
this.JName.setText(""); //重置文本框为空
this.JPassword.setText(""); //重置文本框为空
}
}
}
public static void main(String[] args){
JFrame.setDefaultLookAndFeelDecorated(true);
new Popup();
}
}