滴水穿石-10GUI

时间:2021-08-28 16:43:24

GUI 图形用户界面

1 Frame 窗体

package d10;
//第一导入包
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener; public class Frame1 { public static void main(String[] args) {
// 创建窗体并命名
Frame f = new Frame("HelloWorld");
// 设置窗体大小
//f.setSize(400, 300);
// 设置窗体位置
//f.setLocation(500, 300); //方法二 setBounds(x, y, width, height);
f.setBounds(,, , ); f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
System.exit();
}
}); //显示窗体
f.setVisible(true);
} }

version 1.0

package d10;
import java.awt.Button;
import java.awt.FlowLayout;
//第一导入包
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; public class Frame1 { public static void main(String[] args) {
//01 创建窗体并命名
Frame f = new Frame("HelloWorld"); f.setBounds(,, , );
//02-01创建 按钮 对象
Button bu = new Button("点我");
//02-02 按钮点击事件的监听
bu.addActionListener(new ActionListener() { @Override
public void actionPerformed(ActionEvent e) {
System.out.println("再点一个试试!");
}
});
//01-02 设置窗体布局方式
f.setLayout(new FlowLayout());
//01-03 将按钮添加到Frame中
f.add(bu);
//01-04 窗体关闭事件的监听
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
System.exit();
}
}); //显示窗体
f.setVisible(true);
} }

version 2.0

滴水穿石-10GUI

package d10;

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; public class Frame2 {
public static void main(String[] args) {
//01-01 创建窗体对象那个
Frame f = new Frame();
//01-02 设置窗体位置
f.setBounds(, , , );
//01-03 设置窗体布局方式
f.setLayout(new FlowLayout()); //02-01 创建元素
TextField tf = new TextField();//02-01-01 创建文本框
Button bu = new Button("数据转移");//02-01-02 创建按钮
TextArea ta = new TextArea(,);//02-01-03 创建文本域
//02-02 将元素添加到Frame中
f.add(tf);
f.add(bu);
f.add(ta);
//02-03 为按钮添加监听事件
bu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//02-03-01 获取文本框的值
String tf_str = tf.getText().trim();
//02-03-02 清空文本框的值
tf.setText("");
//02-03-03 追加到文本域中
ta.append(tf_str+"\r\n");
//02-03-04 文本框获取焦点
tf.requestFocus(); }
});
//01-04 添加窗体关闭 监听事件
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit();
}
}); //01-05 设置窗体显示
f.setVisible(true);
}
}

将文本框的值转移到文本域

滴水穿石-10GUI

package d10;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
//第一导入包
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; public class Frame3 { public static void main(String[] args) {
//01 创建窗体并命名
Frame f = new Frame("HelloWorld"); f.setBounds(,, , );
//02-01创建 按钮 对象
Button bured = new Button("红");
bured.setBackground(Color.red);
Button bugreen = new Button("绿");
bugreen.setBackground(Color.green);
Button bublue = new Button("蓝");
bublue.setBackground(Color.blue); //02-02 鼠标事件的监听
bured.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
f.setBackground(Color.red);
}
@Override
public void mouseExited(MouseEvent e) {
f.setBackground(Color.white);
}
});
bugreen.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
f.setBackground(Color.green);
}
@Override
public void mouseExited(MouseEvent e) {
f.setBackground(Color.white);
}
});
bublue.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
f.setBackground(Color.blue);
}
@Override
public void mouseExited(MouseEvent e) {
f.setBackground(Color.white);
}
});
//01-02 设置窗体布局方式
f.setLayout(new FlowLayout());
//01-03 将按钮添加到Frame中
f.add(bured);f.add(bugreen);f.add(bublue);
//01-04 窗体关闭事件的监听
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
System.exit();
}
}); //显示窗体
f.setVisible(true);
} }

变换背景色

滴水穿石-10GUI

package d10;

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; public class Frame4 {
public static void main(String[] args) {
//01-01 创建窗体对象那个
Frame f = new Frame();
//01-02 设置窗体位置
f.setBounds(, , , );
//01-03 设置窗体布局方式
f.setLayout(new FlowLayout()); //02-01 创建元素
Label lb = new Label("只能输入数字");
TextField tf = new TextField();//02-01-01 创建文本框 //02-02 将元素添加到Frame中
f.add(lb);
f.add(tf); //02-03 为文本框添加键盘监听事件
tf.addKeyListener(new KeyAdapter() {
//键盘释放的时候做判断
public void keyPressed(KeyEvent e) {
char ch = e.getKeyChar(); if (!(ch>=''&&ch<='')) {
e.consume();
}
}
}); //01-04 添加窗体关闭 监听事件
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit();
}
}); //01-05 设置窗体显示
f.setVisible(true);
}
}

只能输入数字--键盘监听事件

滴水穿石-10GUI

package d10;
import java.awt.Button;
import java.awt.FlowLayout;
//第一导入包
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; public class Frame5 { public static void main(String[] args) {
//01 创建窗体并命名
Frame f = new Frame("HelloWorld");
f.setBounds(,, , );
//02-01创建 菜单 对象
MenuBar mb = new MenuBar();//02-01创建菜单条
Menu mu = new Menu("文件");//02-02 创建菜单
MenuItem mi = new MenuItem("退出系统");//02-03 创建菜单项 //02-02放置 菜单 对象
mu.add(mi);
mb.add(mu); //02-03 菜单项点击事件的监听 mi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit();
}
});
//01-02 设置窗体布局方式
f.setLayout(new FlowLayout());
//01-03 将菜单条添加到Frame中
f.setMenuBar(mb);
//01-04 窗体关闭事件的监听
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
System.exit();
}
}); //显示窗体
f.setVisible(true);
} }

一级菜单

滴水穿石-10GUI

package d10;

import java.awt.FlowLayout;
//第一导入包
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException; public class Frame6 { public static void main(String[] args) {
//01 创建窗体并命名
Frame f = new Frame("多级菜单");
final String fTitle = f.getTitle();
f.setBounds(,, , );
//02-01创建 菜单 对象
MenuBar mb = new MenuBar();//02-01-01创建菜单条
Menu mu = new Menu("文件");//02-01-02 创建一级菜单 Menu mu2 = new Menu("设置标题");//02-01-03 创建二级菜单
MenuItem mi2_01 = new MenuItem("好好学习");//02-01-03-01 创建菜单项
MenuItem mi2_02 = new MenuItem("天天向上");//02-01-03-02 创建菜单项
MenuItem mi2_03 = new MenuItem("恢复标题");//02-01-03-03 创建菜单项 MenuItem mi_02 = new MenuItem("打开记事本");//02-01-02-02 创建菜单项
MenuItem mi_03 = new MenuItem("退出系统");//02-01-02-03 创建菜单项 //02-02放置 菜单 对象
mu.add(mu2);
mu2.add(mi2_01);
mu2.add(mi2_02);
mu2.add(mi2_03);
mu.add(mi_02);
mu.add(mi_03);
mb.add(mu); //02-03 菜单项点击事件的监听
mi2_01.addActionListener(new ActionListener() {
//好好学习
public void actionPerformed(ActionEvent e) {
f.setTitle(mi2_01.getLabel());
}
});
mi2_02.addActionListener(new ActionListener() {
//天天向上
public void actionPerformed(ActionEvent e) {
f.setTitle(mi2_02.getLabel());
}
});
mi2_03.addActionListener(new ActionListener() {
//恢复标题
public void actionPerformed(ActionEvent e) {
f.setTitle(fTitle);
}
});
mi_02.addActionListener(new ActionListener() {
//打开记事本
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
try {
rt.exec("notepad");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}); mi_03.addActionListener(new ActionListener() {
//退出系统
public void actionPerformed(ActionEvent e) {
System.exit();
}
});
//01-02 设置窗体布局方式
f.setLayout(new FlowLayout());
//01-03 将菜单条添加到Frame中
f.setMenuBar(mb);
//01-04 窗体关闭事件的监听
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
System.exit();
}
}); //显示窗体
f.setVisible(true);
} }

多级菜单

滴水穿石-10GUI

2:NetBeans 的使用

2.1 小型计算器

  public CalculateFrame() {
initComponents();
init();
} private void init() {
//设置标题
this.setTitle("小型计算器");
}

2.1.1 设置标题

  private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {                                             

        //获取第一个操作数的值
String sFirst = this.txtFirst.getText().trim();
//获取第二个操作数的值
String sSecond = this.txtSecond.getText().trim();
//获取运算符的值
String sOperator = this.cbOperator.getSelectedItem().toString().trim(); //通过正则表达式 判断输入的内容是否合法
String regex = "\\d+";
if (!sFirst.matches(regex)) {
//弹框提示
JOptionPane.showMessageDialog(this, this.lblFirst.getText() + "格式不正确");
this.txtFirst.setText("");
this.txtFirst.requestFocus();
return;
}
if (!sSecond.matches(regex)) {
//弹框提示
JOptionPane.showMessageDialog(this, this.lblSecond.getText() + "格式不正确");
this.txtSecond.setText("");
this.txtSecond.requestFocus();
return;
}
int iResult = ; int iFirst = Integer.parseInt(sFirst);
int iSecond = Integer.parseInt(sSecond);
switch (sOperator) {
case "+":
iResult = iFirst + iSecond;
break;
case "-":
iResult = iFirst - iSecond;
break;
case "*":
iResult = iFirst * iSecond;
break;
case "/":
iResult = iFirst / iSecond;
break;
}
this.txtResult.setText(String.valueOf(iResult));
}

2.1.2 计算按钮监听事件

滴水穿石-10GUI

2.1.3 修改窗体的图标

添加两个包,用于放置图片和设置UI操作

滴水穿石-10GUI

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/ package D10.Util; import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame; /**
*专门做界面效果的类
* @author Administrator
*/
public class UiUtil {
private UiUtil(){} public static void setFrameImage(JFrame jf){
//01 获取工具类对象
Toolkit tk = Toolkit.getDefaultToolkit(); //根据路径获取图片
Image i = tk.getImage("src\\D10\\Resource\\jjcc.jpg");
jf.setIconImage(i);
}
}

2.1.3 修改图标

private void init() {
//设置标题
this.setTitle("小型计算器");
//设置窗体图标
UiUtil.setFrameImage(this);
}

修改初始化方法

滴水穿石-10GUI

 public static void setFrameCenter(JFrame jf) {
//01 获取工具类对象
Toolkit tk = Toolkit.getDefaultToolkit(); //02 获取屏幕的宽和高
Dimension d = tk.getScreenSize();
double srceenWidth = d.getWidth();
double srceenHeight = d.getHeight();
//03 获取窗体的宽和高
int frameWidth = jf.getWidth();
int frameHeight = jf.getHeight();
//04 计算新的位置
int width = (int) (srceenWidth - frameWidth) / ;
int height = (int) (srceenHeight - frameHeight) / ; //05 设置窗体坐标
jf.setLocation(width, height);
}

2.1.4 窗体居中

 private void init() {
//设置标题
this.setTitle("小型计算器");
//设置窗体图标
UiUtil.setFrameImage(this);
//设置窗体居中
UiUtil.setFrameCenter(this);
}

修改初始化方法

2.1.5 修改皮肤

2.1.5.1 引用jar包

滴水穿石-10GUI

2.1.5.2 修改main方法

    public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CalculateFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CalculateFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CalculateFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CalculateFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
try {
//</editor-fold>
UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
} catch (ClassNotFoundException ex) {
Logger.getLogger(CalculateFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(CalculateFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(CalculateFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(CalculateFrame.class.getName()).log(Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CalculateFrame().setVisible(true);
}
});
}

main

滴水穿石-10GUI

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/ package D10.Util; //这里面定义了常见的要使用的皮肤的字符串路径。
public abstract class MyLookAndFeel {
// 系统自带皮肤,5种都能用
public static String SYS_METAL = "javax.swing.plaf.metal.MetalLookAndFeel";
public static String SYS_NIMBUS = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
// 有个性
public static String SYS_CDE_MOTIF = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
public static String SYS_WINDOWS = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
public static String SYS_WINDOWS_CLASSIC = "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel";
// JIattoo jar包资源
public static String JTATTOO_ACRYL = "com.jtattoo.plaf.acryl.AcrylLookAndFeel";
public static String JTATTOO_AERO = "com.jtattoo.plaf.aero.AeroLookAndFeel";
// 还可以
public static String JTATTOO_ALUMINUM = "com.jtattoo.plaf.aluminium.AluminiumLookAndFeel";
// 很喜欢
public static String JTATTOO_BERNSTEIN = "com.jtattoo.plaf.bernstein.BernsteinLookAndFeel";
public static String JTATTOO_FAST = "com.jtattoo.plaf.fast.FastLookAndFeel";
// 有个性
public static String JTATTOO_HIFI = "com.jtattoo.plaf.hifi.HiFiLookAndFeel";
public static String JTATTOO_LUNA = "com.jtattoo.plaf.luna.LunaLookAndFeel";
// 很喜欢
public static String JTATTOO_MCWIN = "com.jtattoo.plaf.mcwin.McWinLookAndFeel";
public static String JTATTOO_MINT = "com.jtattoo.plaf.mint.MintLookAndFeel";
// 有个性
public static String JTATTOO_NOIRE = "com.jtattoo.plaf.noire.NoireLookAndFeel";
public static String JTATTOO_SMART = "com.jtattoo.plaf.smart.SmartLookAndFeel";
// liquidlnf.jar包资源
// 很喜欢
public static String LIQUIDINF = "com.birosoft.liquid.LiquidLookAndFeel";
}

MyLookAndFeel

2.2 用户登录页面

滴水穿石-10GUI

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/ package D10.Dao; import D10.Pojo.User; public interface UserDao {
//用户登录
public abstract boolean login(String username ,String password);
//用户注册
public abstract void regist(User user);
}

UserDao

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package D10.Dao.Impl; import D10.Dao.UserDao;
import D10.Pojo.User;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger; /**
*
* @author Administrator
*/
public class UserDaoImpl implements UserDao { private static File file = new File("user.txt"); static {
try {
file.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
} } public boolean login(String username, String password) {
boolean flag = false;
BufferedReader br = null;
try{
//一次读取一行数据
br = new BufferedReader(new FileReader(file));
String line = null;
while((line = br.readLine())!=null){
String [] datas = line.split("=");
if (datas[].equals(username)&&datas[].equals(password)) {
flag = true;
break;
}
}
}
catch( IOException e){
try {
br.close();
} catch (IOException ex) {
Logger.getLogger(UserDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
return flag;
} public void regist(User user) {
BufferedWriter bw = null;
try{
bw = new BufferedWriter(new FileWriter(file,true));
bw.write(user.getUserName()+"="+user.getPassword());
bw.newLine();
bw.flush();
}
catch(IOException e){
e.printStackTrace();
}finally{
try {
bw.close();
} catch (IOException ex) {
Logger.getLogger(UserDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
} }

UserDaoImpl

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package D10.Pojo; /**
*
* @author Administrator
*/
public class User { private String userName;
private String password; public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}

User

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package D10.Util; import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame; /**
* 专门做界面效果的类
*
* @author Administrator
*/
public class UiUtil { private UiUtil() {
} //修改窗体图标
public static void setFrameImage(JFrame jf) {
//01 获取工具类对象
Toolkit tk = Toolkit.getDefaultToolkit(); //根据路径获取图片
Image i = tk.getImage("src\\D10\\Resource\\user.jpg");
jf.setIconImage(i);
} //窗体居中
public static void setFrameCenter(JFrame jf) {
//01 获取工具类对象
Toolkit tk = Toolkit.getDefaultToolkit(); //02 获取屏幕的宽和高
Dimension d = tk.getScreenSize();
double srceenWidth = d.getWidth();
double srceenHeight = d.getHeight();
//03 获取窗体的宽和高
int frameWidth = jf.getWidth();
int frameHeight = jf.getHeight();
//04 计算新的位置
int width = (int) (srceenWidth - frameWidth) / ;
int height = (int) (srceenHeight - frameHeight) / ; //05 设置窗体坐标
jf.setLocation(width, height);
}
}

UiUtil

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package D10.view; import D10.Dao.Impl.UserDaoImpl;
import D10.Dao.UserDao;
import D10.Pojo.User;
import D10.Util.UiUtil;
import javax.swing.JOptionPane; /**
*
* @author Administrator
*/
public class LoginFrame extends javax.swing.JFrame { /**
* Creates new form LoginFrame
*/
public LoginFrame() {
initComponents();
init();
} private void init() {
this.setTitle("登录界面");
this.setResizable(false);
UiUtil.setFrameCenter(this);
UiUtil.setFrameImage(this);
} /**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() { lblUserName = new javax.swing.JLabel();
btnLogin = new javax.swing.JButton();
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
lblPassword = new javax.swing.JLabel();
btnRegister = new javax.swing.JButton();
btnReset = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); lblUserName.setText("用户名:"); btnLogin.setText("登录");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
}); lblPassword.setText("密码:"); btnRegister.setText("注册");
btnRegister.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRegisterActionPerformed(evt);
}
}); btnReset.setText("重置");
btnReset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnResetActionPerformed(evt);
}
}); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(, , )
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblUserName)
.addComponent(lblPassword))
.addGroup(layout.createSequentialGroup()
.addComponent(btnLogin)
.addGap(, , )))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(, , )
.addComponent(btnReset)
.addGap(, , )
.addComponent(btnRegister)
.addContainerGap(, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, , Short.MAX_VALUE)
.addComponent(txtUserName))
.addGap(, , Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(, , )
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblUserName)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(, , )
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblPassword)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(, , )
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnLogin)
.addComponent(btnRegister)
.addComponent(btnReset))
.addContainerGap(, Short.MAX_VALUE))
); pack();
}// </editor-fold> private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {
// "登录界面"的"注册"按钮
RegisterFrame rf = new RegisterFrame();
//this.setVisible(false);
this.dispose();
rf.setVisible(true);
} private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
// "登录界面"的"重置"按钮
this.txtPassword.setText("");
this.txtUserName.setText("");
} private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// "登录界面"的"登录"按钮
String userName = this.txtUserName.getText().trim();
String password = this.txtPassword.getText().trim(); String userNameRegex = "[a-zA-Z]{5}";
String passwordRegex = "\\w{5,12}"; if (!userName.matches(userNameRegex) || !password.matches(passwordRegex)) {
String msg = "";
if (!userName.matches(userNameRegex)) {
msg += "用户名格式不正确!(5位英文字符)";
}
if (!password.matches(userNameRegex)) {
msg += "密码格式不正确!(6-12位字符)";
}
JOptionPane.showMessageDialog(this, msg);
this.txtPassword.setText("");
this.txtUserName.setText("");
this.txtUserName.requestFocus();
return;
} //调用用户操作的功能进行注册
UserDao ud = new UserDaoImpl();
boolean flae = ud.login(userName, password);
if (flae) {
//给出提示
JOptionPane.showMessageDialog(this, "登录成功!");
} else {
//给出提示
JOptionPane.showMessageDialog(this, "用戶名或密碼有誤!");
this.txtPassword.setText("");
this.txtUserName.setText("");
this.txtUserName.requestFocus();
} } /**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold> /* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LoginFrame().setVisible(true);
}
});
} // Variables declaration - do not modify
private javax.swing.JButton btnLogin;
private javax.swing.JButton btnRegister;
private javax.swing.JButton btnReset;
private javax.swing.JLabel lblPassword;
private javax.swing.JLabel lblUserName;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
// End of variables declaration }

LoginFrame

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package D10.view; import D10.Dao.Impl.UserDaoImpl;
import D10.Dao.UserDao;
import D10.Pojo.User;
import D10.Util.UiUtil;
import javax.swing.JOptionPane; /**
*
* @author Administrator
*/
public class RegisterFrame extends javax.swing.JFrame { /**
* Creates new form LoginFrame
*/
public RegisterFrame() {
initComponents();
init();
} private void init() {
this.setTitle("登录界面");
this.setResizable(false);
UiUtil.setFrameCenter(this);
UiUtil.setFrameImage(this);
} /**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() { lblUserName = new javax.swing.JLabel();
btnCancel = new javax.swing.JButton();
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
lblPassword = new javax.swing.JLabel();
btnRegister = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); lblUserName.setText("用户名:"); btnCancel.setText("取消");
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
}); lblPassword.setText("密码:"); btnRegister.setText("注册");
btnRegister.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRegisterActionPerformed(evt);
}
}); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(, , )
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblUserName)
.addComponent(lblPassword)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnRegister)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, , Short.MAX_VALUE)
.addComponent(txtUserName))
.addGap(, , Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(, , )
.addComponent(btnCancel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(, , )
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblUserName)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(, , )
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblPassword)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(, , )
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnRegister)
.addComponent(btnCancel))
.addContainerGap(, Short.MAX_VALUE))
); pack();
}// </editor-fold> private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {
goLogin();
} private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {
// "注册界面"的"注册"按钮:
String userName = this.txtUserName.getText().trim();
String password = this.txtPassword.getText().trim(); String userNameRegex = "[a-zA-Z]{5}";
String passwordRegex = "\\w{5,12}"; if (!userName.matches(userNameRegex) || !password.matches(passwordRegex)) {
String msg = "";
if (!userName.matches(userNameRegex)) {
msg += "用户名格式不正确!(5位英文字符)";
}
if (!password.matches(userNameRegex)) {
msg += "密码格式不正确!(6-12位字符)";
}
JOptionPane.showMessageDialog(this, msg);
this.txtPassword.setText("");
this.txtUserName.setText("");
this.txtUserName.requestFocus();
return;
}
//封装对象
User user = new User();
user.setUserName(userName);
user.setPassword(password);
//调用用户操作的功能进行注册
UserDao ud = new UserDaoImpl();
ud.regist(user);
//给出提示
JOptionPane.showMessageDialog(this, "注册成功!");
goLogin();
} /**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RegisterFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RegisterFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RegisterFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RegisterFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold> /* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RegisterFrame().setVisible(true);
}
});
} // Variables declaration - do not modify
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnRegister;
private javax.swing.JLabel lblPassword;
private javax.swing.JLabel lblUserName;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
// End of variables declaration private void goLogin() {
this.dispose();
LoginFrame lf = new LoginFrame();
lf.setVisible(true);
} }

RegisterFrame

滴水穿石-10GUI