快捷搜索:  汽车  科技

java图形界面编程教程(Java基础-25总结图形用户界面编程GUI)

java图形界面编程教程(Java基础-25总结图形用户界面编程GUI)GUI:方便直观(1)用户图形界面在Eclipse中创建项目,把Netbeans项目的src下的东西给拿过来即可。注意:修改项目编码为UTF-82:GUI(了解)

获取更多资源加微信公众号【java帮帮】 (是公众号,不是微信好友哦)

还有【Java帮帮】QQ空间,技术文章,视频,面试资料。欢迎关注!

学习交流请加【Java帮帮】自学交流QQ群553841695

java图形界面编程教程(Java基础-25总结图形用户界面编程GUI)(1)

1:如何让Netbeans的东西Eclipse能访问。

在Eclipse中创建项目,把Netbeans项目的src下的东西给拿过来即可。

注意:修改项目编码为UTF-8

2:GUI(了解)

(1)用户图形界面

GUI:方便直观

CLI:需要记忆一下命令,麻烦

(2)两个包:

java.awt:和系统关联较强

javax.swing:纯Java编写

(3)GUI的继承体系

组件:组件就是对象

容器组件:是可以存储基本组件和容器组件的组件。

基本组件:是可以使用的组件,但是必须依赖容器。

(4)事件监听机制(理解)

A:事件源事件发生的地方

B:事件就是要发生的事情

C:事件处理就是针对发生的事情做出的处理方案

D:事件监听就是把事件源和事件关联起来

举例:人受伤事件。

事件源:人(具体的对象)

Person p1 = new Person("张三");

Person p2 = new Person("李四");

事件:受伤

interface 受伤接口 {

一拳();

一脚();

一板砖();

}

事件处理:

受伤处理类 implements 受伤接口 {

一拳(){ System.out.println("鼻子流血了,送到卫生间洗洗"); }

一脚(){ System.out.println("晕倒了,送到通风处"); }

一板砖(){ System.out.println("头破血流,送到太平间"); }

}

事件监听:

p1.注册监听(受伤接口)

事件监听标准模板:

事件源对象.addXXXListener(new XXXAdpater(){}

(5)适配器模式(理解)

A:接口

B:抽象适配器类

C:实现类

package cn.itcast_03;(1)

/*

* 针对用户操作的四种功能

*/

public interface UserDao {

public abstract void add();

public abstract void delete();

public abstract void update();

public abstract void find();

}

package cn.itcast_03;(2)

/*

* 问题:

* 接口(方法比较多) -- 实现类(仅仅使用一个,也得把其他的实现给提供了,哪怕是空实现)

* 太麻烦了。

* 解决方案:

* 接口(方法比较多) -- 适配器类(实现接口 仅仅空实现) -- 实现类(用哪个重写哪个)

*/

public class UserDaoDemo {

public static void main(String[] args) {

UserDao ud = new UserDaoImpl();

ud.add();

// 我没有说我们需要四种功能都实现啊。

UserDao ud2 = new UserDaoImpl2();

ud2.add();

}

}

package cn.itcast_03;(3)

public class UserDaoImpl implements UserDao {

@Override

public void add() {

System.out.println("添加功能");

}

@Override

public void delete() {

System.out.println("删除功能");

}

@Override

public void update() {

System.out.println("修改功能");

}

@Override

public void find() {

System.out.println("查找功能");

}

}

package cn.itcast_03;(4)

public abstract class UserAdapter implements UserDao {

@Override

public void add() {

}

@Override

public void delete() {

}

@Override

public void update() {

}

@Override

public void find() {

}

}

package cn.itcast_03;(5)

public class UserDaoImpl2 extends UserAdapter {

@Override

public void add() {

System.out.println("添加功能");

}

}

(6)案例:

A:创建窗体案例

package cn.itcast_01;(1)

import java.awt.Frame;

public class FrameDemo {

public static void main(String[] args) {

// 创建窗体对象

// Frame f = new Frame();

// Frame(String title)

Frame f = new Frame("林青霞");

// 设置窗体标题

f.setTitle("HelloWorld");

// 设置窗体大小

f.setSize(400 300); // 单位:像素

// 设置窗体位置

f.setLocation(400 200);

// 调用一个方法,设置让窗体可见

// f.show();

f.setVisible(true);

// System.out.println("helloworld");

}

}

package cn.itcast_01;(2)

import java.awt.Dimension;

import java.awt.Frame;

import java.awt.Point;

public class FrameDemo2 {

public static void main(String[] args) {

// 创建对象

Frame f = new Frame("方法调用的前后关系");

// f.setVisible(true);

// try {

// Thread.sleep(3000);

// } catch (InterruptedException e) {

// e.printStackTrace();

// }

// // f.setSize(400 300);

// // Dimension(int width int height)

// Dimension d = new Dimension(400 300);

// f.setSize(d);

// // f.setLocation(400 200);

// // Point(int x int y)

// Point p = new Point(400 200);

// f.setLocation(p);

// 一个方法搞定

f.setBounds(400 200 400 300);

f.setVisible(true);

}

}

B:窗体关闭案例

package cn.itcast_02;

import java.awt.Frame;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.event.WindowListener;

public class FrameDemo {

public static void main(String[] args) {

// 创建窗体对象

Frame f = new Frame("窗体关闭案例");

// 设置窗体属性

f.setBounds(400 200 400 300);

// 让窗体关闭

//事件源

//事件:对窗体的处理

//事件处理:关闭窗口(System.exit(0));

//事件监听

//f.addWindowListener(new WindowListener() {

//@Override

//public void windowOpened(WindowEvent e) {

//}

//

//@Override

//public void windowIconified(WindowEvent e) {

//}

//

//@Override

//public void windowDeiconified(WindowEvent e) {

//}

//

//@Override

//public void windowDeactivated(WindowEvent e) {

//}

//

//@Override

//public void windowClosing(WindowEvent e) {

//System.exit(0);

//}

//

//@Override

//public void windowClosed(WindowEvent e) {

//}

//

//@Override

//public void windowActivated(WindowEvent e) {

//}

//});

//用适配器类改进

f.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

// 设置窗体可见

f.setVisible(true);

}

}

C:窗体添加按钮并对按钮添加事件案例。

界面中的组件布局。

package cn.itcast_04;

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;

/*

* 需求:把按钮添加到窗体,并对按钮添加一个点击事件。

* A:创建窗体对象

* B:创建按钮对象

* C:把按钮添加到窗体

* D:窗体显示

*/

public class FrameDemo {

public static void main(String[] args) {

// 创建窗体对象

Frame f = new Frame("添加按钮");

// 设置属性

f.setBounds(400 200 400 300);

// 设置布局为流式布局

f.setLayout(new FlowLayout());

// 创建按钮对象

Button bu = new Button("点我啊");

// bu.setSize(20 10);

// 把按钮添加到窗体

f.add(bu);

// 设置窗体可以关闭

f.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

bu.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

System.out.println("你再点试试");

}

});

// 窗体显示

f.setVisible(true);

}

}

D:把文本框里面的数据转移到文本域

package cn.itcast_05;

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 FrameDemo {

public static void main(String[] args) {

// 创建窗体对象

Frame f = new Frame("数据转移");

// 设置窗体属性和布局

f.setBounds(400 200 400 300);

f.setLayout(new FlowLayout());

// 创建文本框

final TextField tf = new TextField(20);

// 创建按钮

Button bu = new Button("数据转移");

// 创建文本域

final TextArea ta = new TextArea(10 40);

// 把组件添加到窗体

f.add(tf);

f.add(bu);

f.add(ta);

// 设置窗体关闭

f.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

// 对按钮添加事件

bu.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// 获取文本框的值

String tf_str = tf.getText().trim();

// 清空数据

tf.setText("");

// 设置给文本域

// ta.setText(tf_str);

// 追加和换行

ta.append(tf_str "\r\n");

//获取光标

tf.requestFocus();

}

});

// 设置窗体显示

f.setVisible(true);

}

}

E:更改背景色

package cn.itcast_06;

import java.awt.Button;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.Frame;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

public class FrameDemo {

public static void main(String[] args) {

// 创建窗体对象

final Frame f = new Frame("更改背景色");

// 设置窗体属性和布局

f.setBounds(400 200 400 300);

f.setLayout(new FlowLayout());

// 创建四个按钮

Button redButton = new Button("红色");

Button greenButton = new Button("绿色");

Button buleButton = new Button("蓝色");

// 添加按钮

f.add(redButton);

f.add(greenButton);

f.add(buleButton);

// 设置窗体关闭

f.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

// 对按钮添加动作事件

// redButton.addActionListener(new ActionListener() {

// @Override

// public void actionPerformed(ActionEvent e) {

// f.setBackground(Color.RED);

// }

// });

// 对按钮添加鼠标点击事件

// redButton.addMouseListener(new MouseAdapter() {

// @Override

// public void mouseClicked(MouseEvent e) {

// f.setBackground(Color.RED);

// }

// });

// 对按钮添加鼠标的进入事件

redButton.addMouseListener(new MouseAdapter() {

@Override

public void mouseEntered(MouseEvent e) {

f.setBackground(Color.RED);

}

});

redButton.addMouseListener(new MouseAdapter() {

@Override

public void mouseExited(MouseEvent e) {

f.setBackground(Color.WHITE);

}

});

greenButton.addMouseListener(new MouseAdapter() {

@Override

public void mouseEntered(MouseEvent e) {

f.setBackground(Color.GREEN);

}

});

greenButton.addMouseListener(new MouseAdapter() {

@Override

public void mouseExited(MouseEvent e) {

f.setBackground(Color.WHITE);

}

});

buleButton.addMouseListener(new MouseAdapter() {

@Override

public void mouseEntered(MouseEvent e) {

f.setBackground(Color.BLUE);

}

});

buleButton.addMouseListener(new MouseAdapter() {

@Override

public void mouseExited(MouseEvent e) {

f.setBackground(Color.WHITE);

}

});

// 设置窗体显示

f.setVisible(true);

}

}

F:设置文本框里面不能输入非数字字符

package cn.itcast_07;

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 FrameDemo {

public static void main(String[] args) {

// 创建窗体对象并设置属性

Frame f = new Frame("不能输入非数字字符");

f.setBounds(400 200 400 300);

f.setLayout(new FlowLayout());

// 创建Label标签对象

Label label = new Label("请输入你的QQ号码,不能是非数字,不信你试试");

TextField tf = new TextField(40);

// 添加到窗体上

f.add(label);

f.add(tf);

// 设置窗体关闭

f.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

// 给文本框添加事件

tf.addKeyListener(new KeyAdapter() {

@Override

public void keyPressed(KeyEvent e) {

// 如果你取得的字符不是数字字符就取消事件

// 思路:先获取字符,判断字符,取消事件

// char getKeyChar()

char ch = e.getKeyChar();

//System.out.println(ch);

if(!(ch>='0' && ch<='9')){

e.consume();

}

}

});

// 设置窗体可见

f.setVisible(true);

}

}

G:一级菜单

package cn.itcast_08;

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 FrameDemo {

public static void main(String[] args) {

// 创建窗体对象并设置属性

Frame f = new Frame("一级菜单");

f.setBounds(400 200 400 300);

f.setLayout(new FlowLayout());

// 创建菜单栏

MenuBar mb = new MenuBar();

// 创建菜单

Menu m = new Menu("文件");

// 创建菜单项

MenuItem mi = new MenuItem("退出系统");

// 谁添加谁呢

m.add(mi);

mb.add(m);

// 设置菜单栏

f.setMenuBar(mb);

// 设置窗体关闭

f.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

mi.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

System.exit(0);

}

});

// 设置窗体可见

f.setVisible(true);

}

}

H:多级菜单

package cn.itcast_09;

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 FrameDemo {

public static void main(String[] args) {

// 创建窗体对象并设置属性

final Frame f = new Frame("多级菜单");

f.setBounds(400 200 400 300);

f.setLayout(new FlowLayout());

final String name = f.getTitle();

// 创建菜单栏

MenuBar mb = new MenuBar();

// 创建菜单

Menu m1 = new Menu("文件");

Menu m2 = new Menu("更改名称");

// 创建菜单项

final MenuItem mi1 = new MenuItem("好好学习");

final MenuItem mi2 = new MenuItem("天天向上");

MenuItem mi3 = new MenuItem("恢复标题");

MenuItem mi4 = new MenuItem("打开记事本");

MenuItem mi5 = new MenuItem("退出系统");

// 谁添加谁呢

m2.add(mi1);

m2.add(mi2);

m2.add(mi3);

m1.add(m2);

m1.add(mi4);

m1.add(mi5);

mb.add(m1);

// 设置菜单栏

f.setMenuBar(mb);

// 设置窗体关闭

f.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

mi1.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

f.setTitle(mi1.getLabel());

}

});

mi2.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

f.setTitle(mi2.getLabel());

}

});

mi3.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

f.setTitle(name);

}

});

mi4.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

Runtime r = Runtime.getRuntime();

try {

r.exec("notepad");

} catch (IOException e1) {

e1.printStackTrace();

}

}

});

mi5.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

System.exit(0);

}

});

// 设置窗体可见

f.setVisible(true);

}

}

(7)Netbeans的概述和使用

A:是可以做Java开发的另一个IDE工具。

B:使用

A:四则运算

a:修改图标

b:设置居中

package cn.itcast.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) {

//获取工具类对象

//public static Toolkit getDefaultToolkit():获取默认工具包。

Toolkit tk = Toolkit.getDefaultToolkit();

//根据路径获取图片

Image i = tk.getImage("src\\cn\\itcast\\resource\\jjcc.jpg");

//给窗体设置图片

jf.setIconImage(i);

}

//设置窗体居中

public static void setFrameCenter(JFrame jf) {

/*

思路:

A:获取屏幕的宽和高

B:获取窗体的宽和高

C:(用屏幕的宽-窗体的宽)/2,(用屏幕的高-窗体的高)/2作为窗体的新坐标。

*/

//获取工具对象

Toolkit tk = Toolkit.getDefaultToolkit();

//获取屏幕的宽和高

Dimension d = tk.getScreenSize();

double srceenWidth = d.getWidth();

double srceenHeigth = d.getHeight();

//获取窗体的宽和高

int frameWidth = jf.getWidth();

int frameHeight = jf.getHeight();

//获取新的宽和高

int width = (int) (srceenWidth - frameWidth) / 2;

int height = (int) (srceenHeigth - frameHeight) / 2;

//设置窗体坐标

jf.setLocation(width height);

}

}

c:设置皮肤

package cn.itcast.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";

}

d:数据校验

package cn.itcast.view;(7)

import cn.itcast.util.UiUtil;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JOptionPane;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

public class NewJFrame extends javax.swing.JFrame {

/**

* Creates new form NewJFrame

*/

public NewJFrame() {

initComponents();

init();

}

public NewJFrame(String name) {

initComponents();

init(name);

}

private void init() {

this.setTitle("模拟四则运算");

UiUtil.setFrameImage(this "jjcc.jpg");

UiUtil.setFrameCenter(this);

}

private void init(String name) {

this.setTitle("欢迎" name "光临");

UiUtil.setFrameImage(this "jjcc.jpg");

UiUtil.setFrameCenter(this);

}

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

jLabel2 = new javax.swing.JLabel();

jLabel3 = new javax.swing.JLabel();

firstNumber = new javax.swing.JTextField();

secondNumber = new javax.swing.JTextField();

resultNumber = new javax.swing.JTextField();

jLabel4 = new javax.swing.JLabel();

selectOperator = new javax.swing.JComboBox();

jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("第一个操作数");

jLabel2.setText("第二个操作数");

jLabel3.setText("结果");

jLabel4.setText("=");

selectOperator.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " " "-" "*" "/" }));

jButton1.setText("计算");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(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(26 26 26)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING false)

.addComponent(firstNumber)

.addComponent(jLabel1 javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.DEFAULT_SIZE Short.MAX_VALUE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(selectOperator javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING false)

.addComponent(jLabel2 javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.DEFAULT_SIZE Short.MAX_VALUE)

.addComponent(secondNumber))

.addGap(14 14 14)

.addComponent(jLabel4)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jButton1)

.addComponent(jLabel3)

.addComponent(resultNumber javax.swing.GroupLayout.PREFERRED_SIZE 72 javax.swing.GroupLayout.PREFERRED_SIZE))

.addContainerGap(23 Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel1)

.addComponent(jLabel2)

.addComponent(jLabel3))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(firstNumber javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(secondNumber javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(resultNumber javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel4)

.addComponent(selectOperator javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18 18 18)

.addComponent(jButton1)

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE Short.MAX_VALUE))

);

pack();

}// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

//获取第一个操作数

String firstNumberString = this.firstNumber.getText().trim();

//获取运算符

String selectOperator = this.selectOperator.getSelectedItem().toString();

//获取第二个操作数

String secondNumberString = this.secondNumber.getText().trim();

// System.out.println(firstNumberString);

// System.out.println(selectOperator);

// System.out.println(secondNumberString);

//数据校验 必须是数字字符串

String regex = "\\d ";

//校验第一个数

if (!firstNumberString.matches(regex)) {

// System.out.println("数据不匹配");

//public static void showMessageDialog(Component parentComponent Object message)

JOptionPane.showMessageDialog(this "第一个操作数不满足要求必须是数字");

this.firstNumber.setText("");

this.firstNumber.requestFocus();

return;//回去吧

}

//校验第二个数

if (!secondNumberString.matches(regex)) {

// System.out.println("数据不匹配");

//public static void showMessageDialog(Component parentComponent Object message)

JOptionPane.showMessageDialog(this "第二个操作数不满足要求必须是数字");

this.secondNumber.setText("");

this.secondNumber.requestFocus();

return;//回去吧

}

//把字符串数据转换为整数

int firstNumber = Integer.parseInt(firstNumberString);

int secondNumber = Integer.parseInt(secondNumberString);

//定义变量接收结果

int resultNumber = 0;

switch (selectOperator) {

case " ":

resultNumber = firstNumber secondNumber;

break;

case "-":

resultNumber = firstNumber - secondNumber;

break;

case "*":

resultNumber = firstNumber * secondNumber;

break;

case "/":

if(secondNumber==0){

JOptionPane.showMessageDialog(this "除数不能为0");

this.secondNumber.setText("");

this.secondNumber.requestFocus();

return;

}else {

resultNumber = firstNumber / secondNumber;

}

break;

}

//把结果赋值给结果框

this.resultNumber.setText(String.valueOf(resultNumber));

}//GEN-LAST:event_jButton1ActionPerformed

/**

* @param args the command line arguments

*/

// public static void main(String args[]) {

// /* Create and display the form */

// java.awt.EventQueue.invokeLater(new Runnable() {

// public void run() {

// new NewJFrame().setVisible(true);

// }

// });

// }

// Variables declaration - do not modify//GEN-BEGIN:variables

private javax.swing.JTextField firstNumber;

private javax.swing.JButton jButton1;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JTextField resultNumber;

private javax.swing.JTextField secondNumber;

private javax.swing.JComboBox selectOperator;

// End of variables declaration//GEN-END:variables

}

B:登录注册

package cn.itcast.util;(1)

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) {

//获取工具类对象

//public static Toolkit getDefaultToolkit():获取默认工具包。

Toolkit tk = Toolkit.getDefaultToolkit();

//根据路径获取图片

Image i = tk.getImage("src\\cn\\itcast\\resource\\user.jpg");

//给窗体设置图片

jf.setIconImage(i);

}

public static void setFrameImage(JFrame jf String imageName) {

//获取工具类对象

//public static Toolkit getDefaultToolkit():获取默认工具包。

Toolkit tk = Toolkit.getDefaultToolkit();

//根据路径获取图片

Image i = tk.getImage("src\\cn\\itcast\\resource\\" imageName);

//给窗体设置图片

jf.setIconImage(i);

}

//设置窗体居中

public static void setFrameCenter(JFrame jf) {

/*

思路:

A:获取屏幕的宽和高

B:获取窗体的宽和高

C:(用屏幕的宽-窗体的宽)/2,(用屏幕的高-窗体的高)/2作为窗体的新坐标。

*/

//获取工具对象

Toolkit tk = Toolkit.getDefaultToolkit();

//获取屏幕的宽和高

Dimension d = tk.getScreenSize();

double srceenWidth = d.getWidth();

double srceenHeigth = d.getHeight();

//获取窗体的宽和高

int frameWidth = jf.getWidth();

int frameHeight = jf.getHeight();

//获取新的宽和高

int width = (int) (srceenWidth - frameWidth) / 2;

int height = (int) (srceenHeigth - frameHeight) / 2;

//设置窗体坐标

jf.setLocation(width height);

}

}

package cn.itcast.pojo;(2)

public class User {

private String username;

private String password;

public User(){}

/**

* @return the username

*/

public String getUsername() {

return username;

}

/**

* @param username the username to set

*/

public void setUsername(String username) {

this.username = username;

}

/**

* @return the password

*/

public String getPassword() {

return password;

}

/**

* @param password the password to set

*/

public void setPassword(String password) {

this.password = password;

}

}

package cn.itcast.dao;(3)

import cn.itcast.pojo.User;

/**

*

* @author Administrator

*/

public interface UserDao {

/**

* 这是用户登录功能

*

* @param username 用户名

* @param password 密码

* @return 登录是否成功

*/

public abstract boolean login(String username String password);

/**

* 这是用户注册功能

*

* @param user 被注册的用户信息

*/

public abstract void regist(User user);

}

package cn.itcast.dao.impl;(4)

import cn.itcast.dao.UserDao;

import cn.itcast.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;

/**

*

* @author Administrator

*/

public class UserDaoImpl implements UserDao {

//定义文件

private static File file = new File("user.txt");

//类加载的时候就把文件创建

static {

try {

file.createNewFile();

} catch (IOException ex) {

ex.printStackTrace();

}

}

@Override

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[0].equals(username) && datas[1].equals(password)) {

flag = true;

break;

}

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

br.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

return flag;

}

@Override

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) {

ex.printStackTrace();

}

}

}

}

package cn.itcast.view;(5)

import cn.itcast.dao.UserDao;

import cn.itcast.dao.impl.UserDaoImpl;

import cn.itcast.util.UiUtil;

import javax.swing.JOptionPane;

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 "user.jpg");

}

/**

* 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">//GEN-BEGIN:initComponents

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

jLabel2 = new javax.swing.JLabel();

jtfUsername = new javax.swing.JTextField();

jpfPassword = new javax.swing.JPasswordField();

jButton1 = new javax.swing.JButton();

jButton2 = new javax.swing.JButton();

jButton3 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("用户名:");

jLabel2.setText("密码:");

jButton1.setText("登录");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

jButton2.setText("重置");

jButton2.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton2ActionPerformed(evt);

}

});

jButton3.setText("注册");

jButton3.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton3ActionPerformed(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(42 42 42)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jLabel1)

.addComponent(jLabel2))

.addGap(18 18 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING false)

.addComponent(jtfUsername javax.swing.GroupLayout.DEFAULT_SIZE 174 Short.MAX_VALUE)

.addComponent(jpfPassword)))

.addGroup(layout.createSequentialGroup()

.addGap(64 64 64)

.addComponent(jButton1)

.addGap(18 18 18)

.addComponent(jButton2)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jButton3)))

.addContainerGap(61 Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(47 47 47)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel1)

.addComponent(jtfUsername javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(31 31 31)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel2)

.addComponent(jpfPassword javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(54 54 54)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jButton1)

.addComponent(jButton2)

.addComponent(jButton3))

.addContainerGap(48 Short.MAX_VALUE))

);

pack();

}// </editor-fold>//GEN-END:initComponents

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

RegistFrame rf = new RegistFrame();

rf.setVisible(true);

// this.setVisible(false);

this.dispose();

}//GEN-LAST:event_jButton3ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

this.jtfUsername.setText("");

this.jpfPassword.setText("");

}//GEN-LAST:event_jButton2ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

/*

思路:

A:获取用户名和密码

B:正则表达式校验用户名和密码

C:创建对象调用功能,返回一个boolean值

D:根据boolean值给出提示

*/

//获取用户名和密码

String username = this.jtfUsername.getText().trim();

String password = this.jpfPassword.getText().trim();

//用正则表达式做数据校验

//定义规则

//用户名规则

String usernameRegex = "[a-zA-z]{5}";

//密码规则

String passwordRegex = "\\w{6 12}";

//校验

if(!username.matches(usernameRegex)) {

JOptionPane.showMessageDialog(this "用户名不满足条件(5个英文字母组成)");

this.jtfUsername.setText("");

this.jtfUsername.requestFocus();

return;

}

if(!password.matches(passwordRegex)) {

JOptionPane.showMessageDialog(this "密码不满足条件(6-12个任意单词字符)");

this.jpfPassword.setText("");

this.jpfPassword.requestFocus();

return;

}

//创建对象调用功能,返回一个boolean值

UserDao ud = new UserDaoImpl();

boolean flag = ud.login(username password);

if(flag){

JOptionPane.showMessageDialog(this "恭喜你登录成功");

// NewJFrame njf = new NewJFrame();

NewJFrame njf = new NewJFrame(username);

njf.setVisible(true);

this.dispose();

}else {

JOptionPane.showMessageDialog(this "用户名或者密码有误");

this.jtfUsername.setText("");

this.jpfPassword.setText("");

this.jtfUsername.requestFocus();

}

}//GEN-LAST:event_jButton1ActionPerformed

/**

* @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//GEN-BEGIN:variables

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton2;

private javax.swing.JButton jButton3;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JPasswordField jpfPassword;

private javax.swing.JTextField jtfUsername;

// End of variables declaration//GEN-END:variables

}

package cn.itcast.view;(6)

import cn.itcast.dao.UserDao;

import cn.itcast.dao.impl.UserDaoImpl;

import cn.itcast.pojo.User;

import cn.itcast.util.UiUtil;

import javax.swing.JOptionPane;

public class RegistFrame extends javax.swing.JFrame {

/**

* Creates new form LoginFrame

*/

public RegistFrame() {

initComponents();

init();

}

private void init() {

this.setTitle("注册界面");

this.setResizable(false);

UiUtil.setFrameCenter(this);

UiUtil.setFrameImage(this "user.jpg");

}

/**

* 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">//GEN-BEGIN:initComponents

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

jLabel2 = new javax.swing.JLabel();

jtfUsername = new javax.swing.JTextField();

jpfPassword = new javax.swing.JPasswordField();

jButton1 = new javax.swing.JButton();

jButton3 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("用户名:");

jLabel2.setText("密码:");

jButton1.setText("取消");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

jButton3.setText("注册");

jButton3.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton3ActionPerformed(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(42 42 42)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(jButton3)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED javax.swing.GroupLayout.DEFAULT_SIZE Short.MAX_VALUE)

.addComponent(jButton1)

.addGap(72 72 72))

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jLabel1)

.addComponent(jLabel2))

.addGap(18 18 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING false)

.addComponent(jtfUsername javax.swing.GroupLayout.DEFAULT_SIZE 174 Short.MAX_VALUE)

.addComponent(jpfPassword))

.addContainerGap(61 Short.MAX_VALUE))))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(47 47 47)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel1)

.addComponent(jtfUsername javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(31 31 31)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel2)

.addComponent(jpfPassword javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED 52 Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jButton3)

.addComponent(jButton1))

.addGap(50 50 50))

);

pack();

}// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

goLogin();

}//GEN-LAST:event_jButton1ActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

/*

分析:

A:获取用户名和密码

B:用正则表达式做数据校验

C:封装成用户对象

D:调用用户操作的功能进行注册

E:回到登录界面

*/

//获取用户名和密码

String username = this.jtfUsername.getText().trim();

String password = this.jpfPassword.getText().trim();

//用正则表达式做数据校验

//定义规则

//用户名规则

String usernameRegex = "[a-zA-z]{5}";

//密码规则

String passwordRegex = "\\w{6 12}";

//校验

if(!username.matches(usernameRegex)) {

JOptionPane.showMessageDialog(this "用户名不满足条件(5个英文字母组成)");

this.jtfUsername.setText("");

this.jtfUsername.requestFocus();

return;

}

if(!password.matches(passwordRegex)) {

JOptionPane.showMessageDialog(this "密码不满足条件(6-12个任意单词字符)");

this.jpfPassword.setText("");

this.jpfPassword.requestFocus();

return;

}

//封装成用户对象

User user = new User();

user.setUsername(username);

user.setPassword(password);

//调用用户操作的功能进行注册

UserDao ud = new UserDaoImpl();

ud.regist(user);

//给出提示

JOptionPane.showMessageDialog(this "用户注册成功,回到登录界面");

goLogin();

}//GEN-LAST:event_jButton3ActionPerformed

private void goLogin() {

LoginFrame lf = new LoginFrame();

lf.setVisible(true);

this.dispose();

}

/**

* @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(RegistFrame.class.getName()).log(java.util.logging.Level.SEVERE null ex);

// } catch (InstantiationException ex) {

// java.util.logging.Logger.getLogger(RegistFrame.class.getName()).log(java.util.logging.Level.SEVERE null ex);

// } catch (IllegalAccessException ex) {

// java.util.logging.Logger.getLogger(RegistFrame.class.getName()).log(java.util.logging.Level.SEVERE null ex);

// } catch (javax.swing.UnsupportedLookAndFeelException ex) {

// java.util.logging.Logger.getLogger(RegistFrame.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 RegistFrame().setVisible(true);

// }

// });

// }

// Variables declaration - do not modify//GEN-BEGIN:variables

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton3;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JPasswordField jpfPassword;

private javax.swing.JTextField jtfUsername;

// End of variables declaration//GEN-END:variables

}

package cn.itcast.view;(7)

import cn.itcast.util.UiUtil;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JOptionPane;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

public class NewJFrame extends javax.swing.JFrame {

/**

* Creates new form NewJFrame

*/

public NewJFrame() {

initComponents();

init();

}

public NewJFrame(String name) {

initComponents();

init(name);

}

private void init() {

this.setTitle("模拟四则运算");

UiUtil.setFrameImage(this "jjcc.jpg");

UiUtil.setFrameCenter(this);

}

private void init(String name) {

this.setTitle("欢迎" name "光临");

UiUtil.setFrameImage(this "jjcc.jpg");

UiUtil.setFrameCenter(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">//GEN-BEGIN:initComponents

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

jLabel2 = new javax.swing.JLabel();

jLabel3 = new javax.swing.JLabel();

firstNumber = new javax.swing.JTextField();

secondNumber = new javax.swing.JTextField();

resultNumber = new javax.swing.JTextField();

jLabel4 = new javax.swing.JLabel();

selectOperator = new javax.swing.JComboBox();

jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("第一个操作数");

jLabel2.setText("第二个操作数");

jLabel3.setText("结果");

jLabel4.setText("=");

selectOperator.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " " "-" "*" "/" }));

jButton1.setText("计算");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(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(26 26 26)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING false)

.addComponent(firstNumber)

.addComponent(jLabel1 javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.DEFAULT_SIZE Short.MAX_VALUE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(selectOperator javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING false)

.addComponent(jLabel2 javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.DEFAULT_SIZE Short.MAX_VALUE)

.addComponent(secondNumber))

.addGap(14 14 14)

.addComponent(jLabel4)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jButton1)

.addComponent(jLabel3)

.addComponent(resultNumber javax.swing.GroupLayout.PREFERRED_SIZE 72 javax.swing.GroupLayout.PREFERRED_SIZE))

.addContainerGap(23 Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel1)

.addComponent(jLabel2)

.addComponent(jLabel3))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(firstNumber javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(secondNumber javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(resultNumber javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel4)

.addComponent(selectOperator javax.swing.GroupLayout.PREFERRED_SIZE javax.swing.GroupLayout.DEFAULT_SIZE javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18 18 18)

.addComponent(jButton1)

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE Short.MAX_VALUE))

);

pack();

}// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

//获取第一个操作数

String firstNumberString = this.firstNumber.getText().trim();

//获取运算符

String selectOperator = this.selectOperator.getSelectedItem().toString();

//获取第二个操作数

String secondNumberString = this.secondNumber.getText().trim();

// System.out.println(firstNumberString);

// System.out.println(selectOperator);

// System.out.println(secondNumberString);

//数据校验 必须是数字字符串

String regex = "\\d ";

//校验第一个数

if (!firstNumberString.matches(regex)) {

// System.out.println("数据不匹配");

//public static void showMessageDialog(Component parentComponent Object message)

JOptionPane.showMessageDialog(this "第一个操作数不满足要求必须是数字");

this.firstNumber.setText("");

this.firstNumber.requestFocus();

return;//回去吧

}

//校验第二个数

if (!secondNumberString.matches(regex)) {

// System.out.println("数据不匹配");

//public static void showMessageDialog(Component parentComponent Object message)

JOptionPane.showMessageDialog(this "第二个操作数不满足要求必须是数字");

this.secondNumber.setText("");

this.secondNumber.requestFocus();

return;//回去吧

}

//把字符串数据转换为整数

int firstNumber = Integer.parseInt(firstNumberString);

int secondNumber = Integer.parseInt(secondNumberString);

//定义变量接收结果

int resultNumber = 0;

switch (selectOperator) {

case " ":

resultNumber = firstNumber secondNumber;

break;

case "-":

resultNumber = firstNumber - secondNumber;

break;

case "*":

resultNumber = firstNumber * secondNumber;

break;

case "/":

if(secondNumber==0){

JOptionPane.showMessageDialog(this "除数不能为0");

this.secondNumber.setText("");

this.secondNumber.requestFocus();

return;

}else {

resultNumber = firstNumber / secondNumber;

}

break;

}

//把结果赋值给结果框

this.resultNumber.setText(String.valueOf(resultNumber));

}//GEN-LAST:event_jButton1ActionPerformed

/**

* @param args the command line arguments

*/

// public static void main(String args[]) {

// /* Create and display the form */

// java.awt.EventQueue.invokeLater(new Runnable() {

// public void run() {

// new NewJFrame().setVisible(true);

// }

// });

// }

// Variables declaration - do not modify//GEN-BEGIN:variables

private javax.swing.JTextField firstNumber;

private javax.swing.JButton jButton1;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JTextField resultNumber;

private javax.swing.JTextField secondNumber;

private javax.swing.JComboBox selectOperator;

// End of variables declaration//GEN-END:variables

}


获取更多资源加微信公众号【Java帮帮】 (是公众号,不是微信好友哦)

还有【Java帮帮】QQ空间,技术文章,视频,面试资料。欢迎关注!

学习交流请加【Java帮帮】自学交流QQ群553841695

猜您喜欢: