GUI编程
主要学习一些组件的使用
包括:
- 窗口
- 弹窗
- 面板
- 文本框
- 列表框
- 按钮
- 图片
- 监听事件
- 鼠标
- 键盘事件
1. 简介
GUI的核心技术:Swing,AWT
没流行的原因:不美观,需要jre环境
作用:
- 写自己的小工具
- 维护swing界面
- 了解MVC架构,了解监听
2. AWT
2.1 概述
Abstract window toolkit
-
包含了很多类和接口,GUI(graphical user interface),图形用户界面
-
元素:窗口,按钮,文本框
-
java.awt
2.2 组件和容器
1. Frame框架
package com.chao.lesson01;
import java.awt.*;
//GUI的第一个界面
public class TestFrame {
public static void main(String[] args) {
//只有这个是看不见的,不可见
Frame frame = new Frame("我的第一个Java图像界面窗口");
//设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(400,400);
//设置颜色
frame.setBackground(new Color(58, 16,89));
//初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);
}
}
进行了一些封装的
package com.chao.lesson01;
import java.awt.*;
public class TestFrame2 {
public static void main(String[] args) {
new MyFrame(100,100,200,200,Color.red);
new MyFrame(300,100,200,200,Color.green);
new MyFrame(100,300,200,200,Color.yellow);
new MyFrame(300,300,200,200,Color.blue);
}
}
class MyFrame extends Frame {
static int id = 0;
public MyFrame(int x, int y, int w, int h, Color color) {
super("Myframe"+(++id));
setVisible(true);
setSize(w,h);
setLocation(x,y);
setBackground(color);
}
}
2. Panel面板
可以看成一个空间,但是不能单独存在
package com.chao.lesson01;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame();
Panel panel = new Panel();
//设置布局
frame.setLayout(null);
//坐标和背景色
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(40,161,5));
//面板的,相对于frame
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(80, 26, 11));
frame.add(panel);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
2.3 布局管理器
1. 流式布局
package com.chao.lesson02;
import java.awt.*;
public class TestFlowLayout {
public static void main(String[] args) {
Frame frame = new Frame();
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
// frame.setLayout(new FlowLayout(FlowLayout.CENTER));//默认值
// frame.setLayout(new FlowLayout(FlowLayout.LEFT));//左对齐
frame.setLayout(new FlowLayout(FlowLayout.RIGHT));//右对齐
frame.setSize(200,200);
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.setVisible(true);
}
}
2. 边界布局(东西南北中)
package com.chao.lesson02;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestBorderLayout {
public static void main(String[] args) {
Frame frame = new Frame("TestBorderLayout");
frame.setSize(200,200);
frame.setLayout(new BorderLayout());
Button east = new Button("East");
Button west = new Button("West");
Button south = new Button("South");
Button north = new Button("North");
Button center = new Button("Center");
frame.add(east,BorderLayout.EAST);
frame.add(west,BorderLayout.WEST);
frame.add(south,BorderLayout.SOUTH);
frame.add(north,BorderLayout.NORTH);
frame.add(center,BorderLayout.CENTER);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
3. 表格布局
package com.chao.lesson02;
import java.awt.*;
public class TestGridLayout {
public static void main(String[] args) {
Frame frame = new Frame("TestGridLayout");
Button btn1 = new Button("btn1");
Button btn2 = new Button("btn2");
Button btn3 = new Button("btn3");
Button btn4 = new Button("btn4");
Button btn5 = new Button("btn5");
Button btn6 = new Button("btn6");
frame.setLayout(new GridLayout(3,2));
frame.add(btn1);
frame.add(btn2);
frame.add(btn3);
frame.add(btn4);
frame.add(btn5);
frame.add(btn6);
frame.pack();//Java函数,自动选择最优秀的布局
frame.setVisible(true);
}
}
嵌套布局,绘制特定的图形
package com.chao.lesson02;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestNew {
public static void main(String[] args) {
Frame frame = new Frame();
Panel p1 = new Panel(new BorderLayout());
Panel p2 = new Panel(new GridLayout(2,1));
Panel p3 = new Panel(new BorderLayout());
Panel p4 = new Panel(new GridLayout(2,2));
p1.add(new Button("btn1"),BorderLayout.WEST);
p1.add(new Button("btn2"),BorderLayout.EAST);
p2.add(new Button("1"));
p2.add(new Button("2"));
p1.add(p2,BorderLayout.CENTER);
p3.add(new Button("btn3"),BorderLayout.WEST);
p3.add(new Button("btn4"),BorderLayout.EAST);
for(int i = 0; i<4;i++){
p4.add(new Button("new"+(++i)));
}
p3.add(p4,BorderLayout.CENTER);
frame.add(p1,BorderLayout.NORTH);
frame.add(p3,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
2.4 事件监听
某个事件发生,进行一些处理
- 基础的按键监听
package com.chao.lesson03;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestAction {
public static void main(String[] args) {
Frame frame = new Frame();
Button button = new Button();
MyActionListener myActionListener = new MyActionListener();
button.addActionListener(myActionListener);
frame.add(button,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
windowClose(frame);
}
private static void windowClose(Frame frame){
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("aaa");
}
}
两个按钮同时的监听,多个按钮共享一个事件
package com.chao.lesson03;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestActionTwo {
public static void main(String[] args) {
//两个按钮,实现同一个监听
Frame frame = new Frame("stat-stop test");
Button button1 = new Button("start");
Button button2 = new Button("stop");
//如果不设置,默认就是标签名
button2.setActionCommand("设置过了的stop");
MyListener myListener = new MyListener();
button1.addActionListener(myListener);
button2.addActionListener(myListener);
frame.add(button1,BorderLayout.NORTH);
frame.add(button2,BorderLayout.SOUTH);
frame.setVisible(true);
frame.pack();
}
}
class MyListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("msg=>" + e.getActionCommand());
}
}
2.5 输入框监听
package com.chao.lesson03;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestText {
//main函数是入口,只有启动功能
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
}
}
class MyFrame extends Frame{
MyFrame(){
TextField textField = new TextField();
add(textField);
//监听这个文本框的文字
TextListener textListener = new TextListener();
//按下enter就会触发这个输入框的事件
textField.addActionListener(textListener);
//设置显示格式
textField.setEchoChar('$');
setVisible(true);
pack();
}
}
class TextListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField t = (TextField) e.getSource();//获得资源,返回值类型为Object
System.out.println(t.getText());//获得输入框的文本
t.setText("");//回车后变空
}
}
2.6 简易计算器
面向对象编程的原则:组合,大于继承
class A{
public B b;
}
1. 普通版
package com.chao.lesson03;
import javax.swing.text.html.InlineView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestCalc {
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
//计算器类
class Calculator extends Frame {
public Calculator() {
setLayout(new FlowLayout());
//3个文本框
TextField sum1 = new TextField(10);
TextField sum2 = new TextField(10);
TextField ret = new TextField(20);
//1个按钮
Button sign = new Button("=");
sign.addActionListener(new MyCalcListener(sum1,sum2,ret));
//1个标签
Label label = new Label("+");
add(sum1);
add(label);
add(sum2);
add(sign);
add(ret);
setVisible(true);
pack();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//监听器类
class MyCalcListener implements ActionListener{
private TextField sum1,sum2,ret;
public MyCalcListener(TextField sum1,TextField sum2,TextField ret) {
this.sum1 =sum1;
this.sum2 =sum2;
this.ret =ret;
}
@Override
public void actionPerformed(ActionEvent e) {
//1.获得两个数
int n1 = Integer.parseInt(sum1.getText());
int n2 = Integer.parseInt(sum2.getText());
//2.执行加法操作
ret.setText(""+(n1+n2));
//3.清除前两个数
sum1.setText("");
sum2.setText("");
}
}
2. 组合
package com.chao.lesson03;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestCalc01 {
public static void main(String[] args) {
//启动
new Calculator01().load();
}
}
//计算器类
class Calculator01 extends Frame {
//属性
TextField sum1,sum2,ret;
//方法
public void load(){
setLayout(new FlowLayout());
//3个文本框
sum1 = new TextField(10);
sum2 = new TextField(10);
ret = new TextField(20);
//1个按钮
Button sign = new Button("=");
sign.addActionListener(new MyCalcListener01(this));
//1个标签
Label label = new Label("+");
add(sum1);
add(label);
add(sum2);
add(sign);
add(ret);
setVisible(true);
pack();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//监听器类
class MyCalcListener01 implements ActionListener{
//获取计算器这个对象,在一个类中组合另一个类
Calculator01 calculator01 = null;
public MyCalcListener01(Calculator01 calculator01) {
this.calculator01 = calculator01;
}
@Override
public void actionPerformed(ActionEvent e) {
//1.获得两个数
int n1 = Integer.parseInt(calculator01.sum1.getText());
int n2 = Integer.parseInt(calculator01.sum2.getText());
//2.执行加法操作
calculator01.ret.setText(""+(n1+n2));
//3.清除前两个数
calculator01.sum1.setText("");
calculator01.sum2.setText("");
}
}
3. 内部类(还要练习)
面向对象,内部类的最大好处,就是可以畅通无阻的访问外部类的属性和方法。
package com.chao.GUI;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestCalc {
public static void main(String[] args) {
new Calculator().loadCalc();
}
}
class Calculator extends Frame{
//属性
TextField num1,num2,num3;
//方法
public void loadCalc(){
//3个文本框
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(20);
//1个标签
Label label = new Label("+");
//1个按钮
Button button = new Button("=");
button.addActionListener(new MyCalListener());
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
setVisible(true);
pack();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
class MyCalListener implements ActionListener{
//此时就可以直接使用外部类的内容,代码更简洁
@Override
public void actionPerformed(ActionEvent e) {
//1.获取两个数
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
//2.求和输出
num3.setText(""+(n1+n2));
//3.清除前两个
num1.setText("");
num2.setText("");
}
}
}
2.7 画笔
package com.chao.GUI;
import java.awt.*;
public class TestPaint {
public static void main(String[] args) {
new MyPaint();
}
}
class MyPaint extends Frame {
MyPaint(){
setBounds(100,100,500,600);
setVisible(true);
}
//画笔
@Override
public void paint(Graphics g) {
// super.paint(g);
//设置画笔颜色
g.setColor(Color.red);
//画空心圆
g.drawOval(100,100,100,100);
//换颜色
g.setColor(Color.green);
//填充圆
g.fillOval(150,200,100,100);
//画矩形
g.fillRect(200,300,100,100);
//画笔默认颜色是黑色,所以每次用完将它还原
}
}
2.8 鼠标监听
目的:实现鼠标画画
package com.chao.GUI;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
//鼠标监听事件
public class TestMouse {
public static void main(String[] args) {
MyMouse myMouse = new MyMouse("MyMouse-画图");
}
}
//鼠标类
class MyMouse extends Frame{
//画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这些点
ArrayList points;//存位置的
public MyMouse(String title) {
super(title);
setBounds(100,100,400,300);
//存鼠标的位置的点
points = new ArrayList<>();
//鼠标监听器,针对这个窗口
this.addMouseListener(new MyMouseListener());
setVisible(true);
this.addWindowListener(new MyWindowListener());
}
@Override
public void paint(Graphics g) {
//画画,需要监听鼠标的事件(因为鼠标在哪画在哪
Iterator iterator = points.iterator();
while (iterator.hasNext()){
Point point =(Point)iterator.next();
g.setColor(Color.green);
g.fillOval(point.x,point.y,10,10);
}
}
//添加一个点到界面上
public void addPaint(Point point){
points.add(point);
}
//适配器模式
private class MyMouseListener extends MouseAdapter {
//鼠标的操作包括:按下,弹起,按住不动
@Override
public void mousePressed(MouseEvent e) {
MyMouse myMouse = (MyMouse) e.getSource();
//点击的时候,产生一个点,画出来
//这个点就是鼠标的点
myMouse.addPaint(new Point(e.getX(),e.getY()));
//每次点击鼠标都要重画一遍
myMouse.repaint();//刷新
}
}
private class MyWindowListener extends WindowAdapter{
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
//测试鼠标监听
public class TestMouseListenter {
public static void main(String[] args) {
new Paint("画图").loadMyPaint();
}
}
class Paint extends Frame {
private List<Point> pointList;
private Paint cuttorPaint;
public Paint(String title){
super(title);
cuttorPaint = this;
pointList = new ArrayList<>();
}
public void loadMyPaint(){
setVisible(true);
setBounds(100,100,800,600);
addMouseListener(new MyMouseListenter());
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
@Override
public void paint(Graphics g) {
Iterator<Point> iterator = pointList.iterator();
while (iterator.hasNext()){
Point point = iterator.next();
//循环画列表的点坐标
g.fillOval(point.x,point.y,10,10);
}
}
private class MyMouseListenter extends MouseAdapter{
// 按下鼠标时触发
@Override
public void mousePressed(MouseEvent e) {
pointList.add(new Point(e.getX(),e.getY()));
//画笔重新画点
cuttorPaint.repaint();
}
}
}
[https://blog.csdn.net/u011412779/article/details/106629686/?biz_id=102&utm_term=GUI%E7%8B%82%E7%A5%9E&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-0-106629686&spm=1018.2118.3001.4449]摘自以上
2.9 窗口监听
内部类
package com.chao.GUI;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
public static void main(String[] args) {
new MyWindow();
}
}
class MyWindow extends Frame{
public MyWindow(){
setBounds(100,100,400,300);
setVisible(true);
addWindowListener(new MyWindowListener());
}
class MyWindowListener extends WindowAdapter{
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);//隐藏窗口,使不可见
System.exit(0);
}
}
}
使用匿名内部类
package com.chao.GUI;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
public static void main(String[] args) {
new MyWindow();
}
}
class MyWindow extends Frame{
public MyWindow(){
setBounds(100,100,400,300);
setVisible(true);
// addWindowListener(new MyWindowListener());
this.addWindowListener(
//匿名内部类
new WindowAdapter() {
//关闭
@Override
public void windowClosing(WindowEvent e) {
System.out.println("你点了x");
System.exit(0);
}
//激活
@Override
public void windowActivated(WindowEvent e) {
MyWindow myWindow = (MyWindow)e.getSource();
myWindow.setTitle("被激活了");
}
}
);
}
}
2.10 键盘监听
package com.chao.GUI;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class TestKey {
public static void main(String[] args) {
new MyKey();
}
}
class MyKey extends Frame {
public MyKey(){
setBounds(100,200,400,300);
setVisible(true);
this.addKeyListener(
new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
//获得键盘的键是哪一个,是当前的码
int keyCode = e.getKeyCode();
System.out.println(keyCode);
if(keyCode== KeyEvent.VK_W){
System.out.println("你按了w");
}
}
}
);
}
}
3. Swing
3.1 JFrame 窗口
package com.chao.GUI.lesson02;
import sun.security.krb5.internal.tools.Kinit;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo {
//init初始化
public void init(){
//顶级窗口
JFrame jf= new JFrame("第一个JFrame窗口");
jf.setVisible(true);
jf.setBounds(100,100,400,300);
jf.setBackground(Color.green);//没有用,因为要使用容器,需要实例化
//获得一个容器,不用容器设置不了颜色
Container container = jf.getContentPane();//返回值是container
container.setBackground(Color.green);
//设置文字
JLabel jLabel = new JLabel("欢迎来到新世界");
jf.add(jLabel);
//居中显示
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JFrameDemo().init();
}
}
3.2 JDialog 弹窗
package com.chao.GUI.lesson02;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JDialogDemo extends JFrame {
public JDialogDemo(){
this.setVisible(true);
this.setBounds(100,100,400,300);
//自动关闭
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//容器,放东西
Container container =this.getContentPane();
//绝对布局,使用x,y坐标
container.setLayout(null);
JButton jButton = new JButton("点击就弹窗");
jButton.setBounds(30,30,100,100);
container.add(jButton);
jButton.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new MyDialog();
}
}
);
}
public static void main(String[] args) {
new JDialogDemo();
}
}
class MyDialog extends JDialog{
public MyDialog(){
this.setTitle("第一个弹窗");
this.setVisible(true);
this.setBounds(100,100,300,300);
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Container container =this.getContentPane();
container.setLayout(null);
JLabel jLabel = new JLabel("欢迎来到王颖超的世界");
jLabel.setBounds(20,20,200,100);
container.add(jLabel);
}
}
3.3 标签
JLabel
图标Icon
package com.chao.GUI.lesson02;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageIconTest extends JFrame {
public ImageIconTest(){
JLabel jLabel = new JLabel("ImageIcon");
//获取图片地址
URL url = ImageIconTest.class.getResource("tp.jpg");
//借助标签
ImageIcon imageIcon = new ImageIcon(url);
jLabel.setIcon(imageIcon);
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(jLabel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(100,100,700,700);
}
public static void main(String[] args) {
new ImageIconTest();
}
}
3.4 面板
JPanel
package com.chao.GUI.lesson02;
import javax.swing.*;
import java.awt.*;
public class JPanelDemo extends JFrame {
public static void main(String[] args) {
new JPanelDemo();
}
public JPanelDemo(){
this.setVisible(true);
this.setBounds(100,100,500,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel(new GridLayout(3,1));
JPanel panel2 = new JPanel(new GridLayout(1,2));
JPanel panel3 = new JPanel(new GridLayout(2,2));
JPanel panel4 = new JPanel(new GridLayout(3,2));
panel1.add(new JButton("1"));
panel1.add(new JButton("1"));
panel1.add(new JButton("1"));
panel2.add(new JButton("2"));
panel3.add(new JButton("3"));
panel3.add(new JButton("3"));
panel3.add(new JButton("3"));
panel3.add(new JButton("3"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
panel4.add(new JButton("4"));
Container container = getContentPane();
//行数与列数必须设置,不然会出现格式错误
//另外,当设置的行数与列数乘积大于面板数,会空出一些区域
//当设置的行数与列数乘积小于面板数,会自动扩大区域
//后两个参数是间距
container.setLayout(new GridLayout(3,2,15,15));
container.add(panel1);
container.add(panel2);
container.add(panel3);
container.add(panel4);
}
}
滑动JScroll
package com.chao.lesson03;
import com.sun.deploy.panel.ControlPanel;
import javax.swing.*;
import java.awt.*;
public class JScrollTest extends JFrame {
public static void main(String[] args) {
new JScrollTest();
}
public JScrollTest() {
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,500,400);
Container container =this.getContentPane();
JTextArea jtextArea = new JTextArea("你好呀",30,20);
jtextArea.setText("我好了");
JScrollPane jScrollPane = new JScrollPane(jtextArea);
container.add(jScrollPane);
}
}
3.5 按钮
图片按钮
package com.chao.lesson03;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo01 extends JFrame {
public JButtonDemo01(){
this.setVisible(true);
this.setBounds(100,100,500,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container container = getContentPane();
//将图片变成图标
URL url=JButtonDemo01.class.getResource("test.jpg");
ImageIcon imageIcon = new ImageIcon(url);
//把图标加到按钮上
JButton jbutton = new JButton(imageIcon);
container.add(jbutton);
pack();
}
public static void main(String[] args) {
new JButtonDemo01();
}
}
- 单选按钮
package com.chao.lesson03;
import javafx.scene.control.RadioButton;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo02 extends JFrame {
public JButtonDemo02(){
this.setVisible(true);
this.setBounds(100,100,500,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//单选框JRadioButton
Container container = getContentPane();
JRadioButton jRadioButton1 = new JRadioButton("JRadioButton1");
JRadioButton jRadioButton2 = new JRadioButton("JRadioButton2");
JRadioButton jRadioButton3 = new JRadioButton("JRadioButton3");
//通过分组的形式实现单选框只能选择一个的操作
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(jRadioButton1);
buttonGroup.add(jRadioButton2);
buttonGroup.add(jRadioButton3);
//设置位置
container.add(jRadioButton1,BorderLayout.CENTER);
container.add(jRadioButton2,BorderLayout.SOUTH);
container.add(jRadioButton3,BorderLayout.NORTH);
pack();
}
public static void main(String[] args) {
new JButtonDemo02();
}
}
- 复选按钮
package com.chao.lesson03;
import javafx.scene.control.RadioButton;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo03 extends JFrame {
public JButtonDemo03(){
this.setVisible(true);
this.setBounds(100,100,500,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//多选框
Checkbox checkBox1 = new Checkbox("CheckBox1");
Checkbox checkBox2 = new Checkbox("CheckBox2");
Container container = getContentPane();
container.add(checkBox1,BorderLayout.NORTH);
container.add(checkBox2,BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
new JButtonDemo03();
}
}
3.6 列表
下拉框
package com.chao.lesson03;
import javax.swing.*;
import java.awt.*;
public class JComboBoxDemo extends JFrame {
public static void main(String[] args) {
new JComboBoxDemo();
}
public JComboBoxDemo(){
this.setVisible(true);
this.setBounds(100,100,500,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComboBox option = new JComboBox();
option.addItem("正在热映");
option.addItem("已下线");
option.addItem("即将上映");
Container container = getContentPane();
container.add(option);
}
}
列表框
package com.chao.lesson03;
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
public class JBoxDemo extends JFrame {
public static void main(String[] args) {
new JBoxDemo();
}
public JBoxDemo(){
this.setVisible(true);
this.setSize(500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//这一行要往前放,不然容易第一次加载不出来内容
Container container = getContentPane();
// //生成列表的内容
// String[] arr = {"1","2","3"};
//
// //将内容放入列表
// JList jList = new JList(arr);
//也可以放Vector
Vector content = new Vector();
content.add("zhangsan");
content.add("lisi");
content.add("wangwu");
content.remove("wangwu");
JList jList = new JList(content);
container.add(jList);
}
}
应用场景
-
一些单个选项。少于两个用单选框,多于两个用下拉框
-
列表框用于展示一些信息,一般可以动态扩容(add,remove)
3.7 文本框
普通文本框
package com.chao.lesson03;
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
public class JBoxDemo extends JFrame {
public static void main(String[] args) {
new JBoxDemo();
}
public JBoxDemo(){
this.setVisible(true);
this.setSize(500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//这一行要往前放,不然容易第一次加载不出来内容
Container container = getContentPane();
// //生成列表的内容
// String[] arr = {"1","2","3"};
//
// //将内容放入列表
// JList jList = new JList(arr);
//也可以放Vector
Vector content = new Vector();
content.add("zhangsan");
content.add("lisi");
content.add("wangwu");
content.remove("wangwu");
JList jList = new JList(content);
container.add(jList);
}
}
密码框
package com.chao.lesson03;
import javax.swing.*;
import java.awt.*;
public class JTextDemo2 extends JFrame {
public static void main(String[] args) {
new JTextDemo2();
}
public JTextDemo2(){
Container container = getContentPane();
JPasswordField jPasswordField = new JPasswordField();//默认使用·进行隐藏
jPasswordField.setEchoChar('¥');//被钱迷惑了双眼
container.add(jPasswordField);
this.setVisible(true);
this.setSize(500,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
文本域 JTextArea,讲JScroll时
ps:
HTML,Servlet,MVC
C/S:Client/Server,客户端和服务器
B/S:Browser/Server,浏览器和服务器
贪吃蛇
GamePage
package com.chao.GUI.snakegame;
import javax.swing.*;
public class GamePage extends JFrame {
public void init(){
//开始了解为什么要把设置可见性的这些代码放在最后,不然容易出现监听失败等问题,初始加载不全
this.add(new GamePanel());
this.setVisible(true);
this.setBounds(15,10,920,740);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setResizable(false);
}
public static void main(String[] args) {
new GamePage().init();
}
}
GamePanel
package com.chao.GUI.snakegame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
public class GamePanel extends JPanel implements KeyListener, ActionListener {
//定义蛇的数据结构
int length;//蛇的长度
int[] snakeX = new int[600];//x坐标
int[] snakeY = new int[600];//y坐标
String direction;//初始方向向右
Boolean isStart;//记录游戏的状态
Boolean isFail;//记录失败的状态
int foodx;
int foody;
int score;
Random random = new Random();
//定时器,以ms为单位,表示没多少毫秒执行一次
Timer timer = new Timer(100,this);
//初始化蛇
public void init(){
length = 3;
snakeX[0] = 100;snakeY[0]=100;//头部初始位置
snakeX[1] = 75;snakeY[1]=100;//第一节身体初始位置
snakeX[2] = 50;snakeY[2]=100;//第二节身体初始位置
direction = "R";//默认向右
isStart = false;//默认不开始
isFail = false;//默认不失败
score = 0;
timer.start();//定时器开启
//食物随机分布在界面
foodx = 25 + 25 *random.nextInt(34);
foody = 75 + 25 *random.nextInt(24);
}
public GamePanel(){
init();
//获得焦点和键盘事件
this.setFocusable(true);//获得焦点事件
this.addKeyListener(this);//获得键盘监听事件
}
@Override
public void paint(Graphics g) {
super.paintComponent(g);//清屏
this.setBackground(Color.WHITE);
//绘制静态面板
Data.header.paintIcon(this,g,25,11);//头部
g.fillRect(25,75,850,600);//默认的游戏界面
g.setColor(Color.white);
//设置字体
g.setFont(new Font("微软雅黑",Font.BOLD,16));
g.drawString("长度" + length, 750, 35);
g.drawString("分数" + score, 750, 50);
//静态画法
// //把小蛇画上去
// Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头
// Data.body.paintIcon(this,g,snakeX[1],snakeY[1]);//第一个身体
// Data.body.paintIcon(this,g,snakeX[2],snakeY[2]);//第二个身体
if(direction.equals("R")){
Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头,需要判断方向
}else if(direction.equals("L")){
Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头,需要判断方向
}else if(direction.equals("U")){
Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头,需要判断方向
}else if(direction.equals("D")){
Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头,需要判断方向
}
for(int i = 1; i <length;i++){
Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);//每一个身体
}
//画食物
Data.food.paintIcon(this,g,foodx,foody);
//游戏状态
if(isStart == false){
//设置白色
g.setColor(Color.white);
//设置字体
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("按下空格开始游戏!",300,300);
}
if(isFail){
g.setColor(Color.red);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
g.drawString("失败,重新开始!",300,300);
}
}
//按下键盘的操作
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_SPACE){
if(isFail){//重新开始
isFail = false;
init();
}
else{
isStart = !isStart;
}
repaint();
}
//小蛇移动
if(keyCode == KeyEvent.VK_UP) {
direction = "U";
}else if(keyCode == KeyEvent.VK_DOWN){
direction = "D";
}else if(keyCode == KeyEvent.VK_LEFT){
direction = "L";
}else if(keyCode == KeyEvent.VK_RIGHT){
direction = "R";
}
}
//事件监听,通过固定时间来判断
@Override
public void actionPerformed(ActionEvent e) {
if(isStart && isFail ==false){//开始游戏则让小蛇动起来
//吃食物
if(foodx == snakeX[0] && foody == snakeY[0]){
length++;//长度加一
//分数加10
score = score +10;
//生成新的食物
foodx = 25 + 25 *random.nextInt(34);
foody = 75 + 25 *random.nextInt(24);
}
//移动,身体的变化恒定
for(int i = length-1; i>0;i--){
snakeX[i]=snakeX[i-1];//身体的下一位置为其右边的上一位置
snakeY[i]=snakeY[i-1];
}
//方向
if(direction.equals("R")){
snakeX[0]=snakeX[0]+25;//蛇头
//如果超出范围
if(snakeX[0]>850){
snakeX[0]=25;
}
}else if(direction.equals("L")){
snakeX[0]=snakeX[0]-25;//蛇头
//如果超出范围
if(snakeX[0]<25){
snakeX[0]=850;
}
}else if(direction.equals("U")){
snakeY[0]=snakeY[0]-25;//蛇头
//如果超出范围
if(snakeY[0]<75){
snakeY[0]=650;
}
}else if(direction.equals("D")){
snakeY[0]=snakeY[0]+25;//蛇头
//如果超出范围
if(snakeY[0]>650){
snakeY[0]=75;
}
}
//失败判断,撞到自己
for(int i = 1; i<length;i++){
if(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
isFail = true;
}
}
repaint();//重画
}
timer.start();//定时器开启
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
Data
package com.chao.GUI.snakegame;
import javax.swing.*;
import java.net.URL;
//数据中心
public class Data {
public static URL headerURL = Data.class.getResource("statics/header.png");
public static ImageIcon header = new ImageIcon(headerURL);
public static URL upURL = Data.class.getResource("statics/up.png");
public static ImageIcon up = new ImageIcon(upURL);
public static URL downURL = Data.class.getResource("statics/down.png");
public static ImageIcon down = new ImageIcon(downURL);
public static URL leftURL = Data.class.getResource("statics/left.png");
public static ImageIcon left = new ImageIcon(leftURL);
public static URL rightURL = Data.class.getResource("statics/right.png");
public static ImageIcon right = new ImageIcon(rightURL);
public static URL bodyURL = Data.class.getResource("statics/body.png");
public static ImageIcon body = new ImageIcon(bodyURL);
public static URL foodURL = Data.class.getResource("statics/food.png");
public static ImageIcon food = new ImageIcon(foodURL);
}
优化方向:
-
根据积分增加等级,改变速度
-
撞墙游戏失败
-
不能回头
-
食物功能不同(有毒食物,高级食物)
-
联机
-
存档(数据库,io操作)
ps:打jar包
Project Structure->Artifacts->点+->ok
Build->Build Artifacts->Build
F:\IdeaJavaFile\GUI\out\artifacts\javaGUI_jar打开cmd
命令
java -jar javaGUI.jar