GUI编程

组件 Component

  1. 窗口
  2. 弹窗
  3. 面板
  4. 文本框
  5. 列表框
  6. 按钮
  7. 图片
  8. 监听事件
  9. 鼠标
  10. 键盘事件

简介

  • GUI 的核心技术 :Swing AWT
    1. 界面不美观
    2. 需要jre环境
  • GUI是MVC基础,了解监听
  • 可以写自己的小工具

AWT

AWT介绍

  • 包含了很多的类和接口
  • GUI :图形用户编程
  • 元素: 窗口,按钮,文本框
  • 包: java.awt

组件和容器 Frame

  • 单个窗口
package com.gui.lesson01;
import java.awt.*;
public class TestFrame {
    //GUI第一个界面
    public static void main(String[] args) {
        //Frame 看源码
        Frame frame = new Frame("我的第一个Java图形界面窗口");
        //设置可见性
        frame.setVisible(true);
        //设置窗口大小
        frame.setSize(400,400);
        //设置背景颜色
        frame.setBackground(new Color(56, 88, 197));
        //弹出的初始位置
        frame.setLocation(200,200);
        //设置大小固定
        frame.setResizable(false);
    }
}
  • 多个窗口和封装
package com.gui.lesson01;
import java.awt.*;
public class TestFrame2 {
    public static void main(String[] args) {
        //展示多个窗口
        MyFrame myFrame1 = new MyFrame(100, 100, 200, 200, Color.cyan);
        MyFrame myFrame2=  new MyFrame(300, 100, 200, 200, Color.blue);
        MyFrame myFrame3 = new MyFrame(100, 300, 200, 200, Color.red);
        MyFrame myFrame4 = new MyFrame(300, 300, 200, 200, Color.pink);
        MyFrame myFrame5 = new MyFrame(500, 100, 200, 200, Color.yellow);
    }
}
class MyFrame extends Frame {
    static Integer id=0;//可能存在多个窗口,需要计数器
    public MyFrame(int x,int y,int w,int h,Color color){
        super("MyFrame "+ (++id));
        setBackground(color);
        setBounds(x,y,w,h);
        setVisible(true);
    }
}

面板 Panel

  • 窗口关闭
package com.gui.lesson01;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//Panel 可以看成是一个空间,但是不能单独存在
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(130, 187, 73));
        //Panel设置坐标 相对于frame
        panel.setBounds(50,50,400,400);
        panel.setBackground(new Color(255,0,0));
        //frame.add(panel)添加面板
        frame.add(panel);
        //设置可见性
        frame.setVisible(Boolean.TRUE);
        //监听事件,监听窗口关闭时间System.exit();
        frame.addWindowListener(new WindowAdapter() {
            //窗口点击关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //窗口结束
                System.exit(0);
            }
        });
    }
}

布局管理器

  • 流式布局
package com.gui.lesson01;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
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());   // 居中
        frame.setLayout(new FlowLayout(FlowLayout.LEFT)); //靠左
        frame.setSize(200,200);
        //添加按钮
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        //设置可见
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
  • 东西南北中
package com.gui.lesson01;
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");
        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.setBounds(200,200,400,400);
        frame.setBackground(new Color(56,25,126));
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
  • 表格布局 Grid
package com.gui.lesson01;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
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.setVisible(true);
        frame.pack();//java函数,自动设置最佳布局
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

课堂练习

package com.gui.lesson01;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ExDemo {
    public static void main(String[] args) {
        Frame frame = new Frame("ExTest");
        frame.setSize(400,400);
        frame.setLocation(300,400);
        frame.setBackground(Color.cyan);
        frame.setVisible(true);
        frame.setLayout(new GridLayout(2,1));
        Panel panel1 = new Panel(new BorderLayout());
        Panel panel2 = new Panel(new GridLayout(2,1));
        Panel panel3 = new Panel(new BorderLayout());
        Panel panel4 = new Panel(new GridLayout(2,2));
        //上面
        panel1.add(new Button("East-1"),BorderLayout.EAST);
        panel1.add(new Button("East-2"),BorderLayout.WEST);
        panel2.add(new Button("center-1"));
        panel2.add(new Button("center-2"));
        panel1.add(panel2,BorderLayout.CENTER);
        //下面
        panel3.add(new Button("East-2"),BorderLayout.EAST);
        panel3.add(new Button("West-2"),BorderLayout.WEST);
        for (int i = 0; i < 4; i++) {
            panel4.add(new Button("for-"+i));
        }
        panel3.add(panel4,BorderLayout.CENTER);
        frame.pack();
        frame.add(panel1);
        frame.add(panel3);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

事件监听

  • 事件监听:当某个事情发生的时候,干什么?
package com.gui.lesson02;
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 TestActionEvent {
    public static void main(String[] args) {
        //按下按钮,触发事件
        Frame frame=new Frame();
        Button button = new Button();
        //因为addActionLitsener
        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.gui.lesson02;
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 TestActionTwo {
    public static void main(String[] args) {
        //两个按钮,实现同一个监听
        //开始停止
        Frame frame = new Frame("开始-停止");
        Button button1 = new Button("start");
        Button button2 = new Button("stop");
        //可以显示的定义触发会返回的命令,如果不显示定义,就默认值
        //可以多个按钮只写一个监听类
        button2.setActionCommand("button2-stop");
        MyMonitor myMonitor = new MyMonitor();
        button1.addActionListener(myMonitor);
        button2.addActionListener(myMonitor);
        frame.add(button1,BorderLayout.NORTH);
        frame.add(button2,BorderLayout.SOUTH);
        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 MyMonitor implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("按钮被点击了"+e.getActionCommand());
    }
}
  • 输入框TextField监听
package com.gui.lesson02;
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 Test01 {
    public static void main(String[] args) {
        new MyFrame();
    }
}
class MyFrame extends Frame{
    public MyFrame(){
        TextField textField = new TextField();
        add(textField);
        //监听这个文本框输入的文字
        MyActionListener2 myActionListener2 = new MyActionListener2();
        //按下enter就会触发这个输入框的事件
        textField.addActionListener(myActionListener2);
        //设置替换编码
        textField.setEchoChar('*');
        setVisible(true);
        pack();
        windowListener(this);
    }
    private static void windowListener(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
class MyActionListener2 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField textField=(TextField)e.getSource();//获得一些资源
        System.out.println(textField.getText());//获得输入框的文本
        textField.setText("");
    }
}
  • 简易计算器
package com.gui.lesson02;
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();
    }
}
//计算器类
class Calculator extends Frame{
    public Calculator(){
        //三个文本框
        TextField num1 = new TextField(10);//字符数
        TextField num2 = new TextField(10);//字符数
        TextField num3 = new TextField(20);//字符数
        //一个按钮
        Button button = new Button("=");
        MyCalculatorListener myCalculatorListener = new MyCalculatorListener(num1,num2,num3);
        button.addActionListener(myCalculatorListener);
        //一个标签
        Label label = new Label("+");
        //布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
        windowListener(this);
    }
    private void windowListener(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
//监听器类
class MyCalculatorListener implements ActionListener {
    //获取三个变量
    private TextField num1,num2,num3;
    public MyCalculatorListener(TextField num1,TextField num2,TextField num3){
        this.num1=num1;
        this.num3=num3;
        this.num2=num2;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //1.获得加数和被加数
        int num11 = Integer.parseInt(num1.getText());
        int num22 = Integer.parseInt(num2.getText());
        //2.将这个数 + 法运算后,放到第三个框
        num3.setText(num11+num22+"");
        System.out.println(num3.getText());
        //3.清除前两个框
        num1.setText("");
        num2.setText("");
    }
}
  • 升级版
package com.gui.lesson02;
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().loadFrame();
    }
}
//计算器类
class Calculator extends Frame{
    TextField num1,num2,num3;
    public void loadFrame(){
        //三个文本框
         num1 = new TextField(10);//字符数
         num2 = new TextField(10);//字符数
         num3 = new TextField(20);//字符数
        //一个按钮
        Button button = new Button("=");
        MyCalculatorListener myCalculatorListener = new MyCalculatorListener(this);
        button.addActionListener(myCalculatorListener);
        //一个标签
        Label label = new Label("+");
        //布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
        windowListener(this);
    }
    private void windowListener(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
//监听器类
class MyCalculatorListener implements ActionListener {
    //获取计算器这个量,在一个类中组合另外一个类
    Calculator calculator=null;
    public MyCalculatorListener(Calculator calculator){
        this.calculator=calculator;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //1.获得加数和被加数
        int i = Integer.parseInt(calculator.num1.getText());
        int i1 = Integer.parseInt(calculator.num2.getText());
        //2.将这个数 + 法运算后,放到第三个框
        calculator.num3.setText(i+i1+"");
        System.out.println(calculator.num3.getText());
        //3.清除前两个框
        calculator.num1.setText("");
        calculator.num2.setText("");
    }
}
  • 内部类 更好的包装
package com.gui.lesson02;
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().loadFrame();
    }
}
//计算器类
class Calculator extends Frame{
    TextField num1,num2,num3;
    public void loadFrame(){
        //三个文本框
         num1 = new TextField(10);//字符数
         num2 = new TextField(10);//字符数
         num3 = new TextField(20);//字符数
        //一个按钮
        Button button = new Button("=");
        MyCalculatorListener myCalculatorListener = new MyCalculatorListener();
        button.addActionListener(myCalculatorListener);
        //一个标签
        Label label = new Label("+");
        //布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
        windowListener(this);
    }
    private void windowListener(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    //监听器类
    class MyCalculatorListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            //1.获得加数和被加数
            int i = Integer.parseInt(num1.getText());
            int i1 = Integer.parseInt(num2.getText());
            //2.将这个数 + 法运算后,放到第三个框
            num3.setText(i+i1+"");
            System.out.println(num3.getText());
            //3.清除前两个框
            num1.setText("");
            num2.setText("");
        }
    }
}

画笔 paint

package com.gui.lesson03;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}
class MyPaint extends Frame{
    protected void loadFrame(){
        setBounds(200,200,600,500);
        setVisible(true);
        windowListener(this);
    }
    private void windowListener(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    @Override
    public void paint(Graphics g) {
        //画笔,需要有颜色,画笔可以画画
        g.setColor(Color.red);
        g.fillOval(100,100,100,100);
        g.setColor(Color.GREEN);
        g.fillRect(150,200,200,200);
        //养成习惯,画笔画完,将之还原
        g.setColor(new Color(0,0,0));
    }
}

鼠标监听

  • 目的:想要实现鼠标画画
package com.gui.lesson03;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
//鼠标监听事件
public class TestMouseListener {
    public static void main(String[] args) {
        new MyFrame("画图");
    }
}
class MyFrame extends Frame {
    //画画需要画笔,需要监听鼠标当前的设置,需要集合来存储这个点
    ArrayList points;
    public MyFrame(String title){
        super(title);
        setBounds(200,200,400,300);
        //存鼠标点击的点
        points=new ArrayList<>();
        //鼠标监听器,正对这个窗口
        setVisible(true);
        this.addMouseListener(new MyMouseListener());
        windowListener(this);
    }
    private void windowListener(Frame frame){
     frame.addWindowListener(new WindowAdapter() {
         @Override
         public void windowClosing(WindowEvent e) {
             System.exit(0);
         }
     });
    }
    @Override
    public void paint(Graphics g) {
        //画画,监听鼠标的事件
        Iterator iterator = points.iterator();
        while(iterator.hasNext()){
            Point point=(Point)iterator.next();
            g.setColor(Color.blue);
            g.fillOval(point.x,point.y,10,10);
        }
    }
    //添加一个点到界面上
    private void addPaint(Point point){
        points.add(point);
    }
    //适配器模式
    private class MyMouseListener extends MouseAdapter {
        //鼠标 按下,弹起,按住不放
        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame myFrame =(MyFrame) e.getSource();
            //这里点击的时候,就会在界面上产生一个点
            //这个点就是鼠标的点
            myFrame.addPaint(new Point(e.getX(),e.getY()));
            //每次点击鼠标都需要重新画一遍
            myFrame.repaint();
        }
    }
}

窗口监听

package com.gui.lesson03;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
    public static void main(String[] args) {
        new WindowFrame();
    }
}
class WindowFrame extends Frame {
    public WindowFrame(){
        setBackground(Color.blue);
        setBounds(100,100,200,200);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            //匿名内部类
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("windowClosing");
                System.exit(0);
            }
            @Override
            public void windowActivated(WindowEvent e) {
                WindowFrame source = (WindowFrame) e.getSource();
                source.setTitle("被激活了");
                System.out.println("windowActivated");
            }
        });
    }
}

键盘监听

package com.gui.lesson03;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
//键盘事件
public class TestKeyListener {

    public static void main(String[] args) {
        new KeyFrame();
    }
}
class KeyFrame extends Frame{
    public KeyFrame(){
        setBounds(1,2,300,400);
        setVisible(true);

        addKeyListener(new KeyAdapter() {
            //键盘按下
            @Override
            public void keyPressed(KeyEvent e) {
                //获得键盘按下的键是哪一个,当前的码

                int keyCode = e.getKeyCode();
                System.out.println(keyCode);
                if(keyCode==KeyEvent.VK_UP){
                    System.out.println("你按下了上键");
                }
                //根据按下不同操作,产生不同结果
            }
        });
    }
}

总结

  1. Frame 是一个顶级窗口
  2. Panel 无法单独显示,必须添加到某个容器中
  3. 布局管理器

​ 1.流式布局

​ 2.东西南北中

​ 3.表格

  1. 大小,定位背景颜色,可见性,监听
  2. oop原则:组合,大于继承

Swing

窗口和面板

package com.gui.lesson04;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo02 {
    public static void main(String[] args) {
        new MyJFrame().init();
    }
}
class MyJFrame extends JFrame {
    public void init(){
        setBounds(10,10,200,300);
        setVisible(true);
        JLabel jLabel = new JLabel("我爱学Java");
        add(jLabel);
        //让文本标签居中
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        //获得一个容器
        Container contentPane = this.getContentPane();
        contentPane.setBackground(Color.blue);
    }
}

弹窗

  • JDiaLog 用来被弹出,默认就有关闭事件
package com.gui.lesson04;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//主窗口
public class DialogDemo extends JFrame {
    public DialogDemo() {
        setVisible(true);
        setSize(700,500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //JFrame 放东西,容器
        Container container =getContentPane();
        container.setLayout(null);
        //按钮
        JButton jButton = new JButton("点击弹出一个对话框");//创建
        jButton.setBounds(30,30,200,50);
        //点击这个按钮的时候,弹出一个弹窗
        jButton.addActionListener(new ActionListener() {//监听器
            @Override
            public void actionPerformed(ActionEvent e) {
                //弹窗
                new MyDiaLogDemo();
            }
        });
        container.add(jButton);
    }
    public static void main(String[] args) {
        new DialogDemo();
    }
}
//弹窗的窗口
class MyDiaLogDemo extends JDialog{
    public MyDiaLogDemo(){
        setVisible(true);
        setBounds(100,100,500,500);
        //setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container contentPane = getContentPane();
        contentPane.setLayout(null);
        contentPane.add(new Label("秦老师带你学Java"));
    }
}

标签

  • JLabel
new JLabel("xxx");
  • 图标 ICON
package com.gui.lesson04;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageIconDemo extends JFrame {
    public ImageIconDemo(){
        //获取图片地址
        JLabel jLabel = new JLabel("ImageIcon");
        URL resource = ImageIconDemo.class.getResource("1.jpg");//图片自备
        ImageIcon imageIcon = new ImageIcon(resource);
        jLabel.setIcon(imageIcon);
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        Container contentPane = getContentPane();
        contentPane.add(jLabel);
        setVisible(true);
        setBounds(100,100,200,200);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new ImageIconDemo();
    }
}

面板

  • JPanel
package com.gui.lesson05;
import javax.swing.*;
import java.awt.*;
public class JPanelDemo extends JFrame {
    public JPanelDemo(){
        Container contentPane = this.getContentPane();
        contentPane.setLayout(new GridLayout(2,1,10,10)); //vgap 间距
        JPanel jPanel1 = new JPanel(new GridLayout(1,3));
        JPanel jPanel2 = new JPanel(new GridLayout(1,2));
        JPanel jPanel3 = new JPanel(new GridLayout(2,1));
        JPanel jPanel4 = new JPanel(new GridLayout(3,2));
        jPanel1.add(new JButton("1"));
        jPanel1.add(new JButton("1"));
        jPanel1.add(new JButton("1"));
        jPanel2.add(new JButton("2"));
        jPanel2.add(new JButton("2"));
        jPanel3.add(new JButton("3"));
        jPanel3.add(new JButton("3"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));
        this.setVisible(true);
        this.setBounds(10,10,600,600);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        contentPane.add(jPanel1);
        contentPane.add(jPanel2);
        contentPane.add(jPanel3);
        contentPane.add(jPanel4);
    }
    public static void main(String[] args) {
        new JPanelDemo();
    }
}
  • JScrollPanel
package com.gui.lesson05;
import javax.swing.*;
import java.awt.*;
public class JScrollDemo extends JFrame {
    public JScrollDemo(){
        Container contentPane = this.getContentPane();
        //文本域
        JTextArea jTextArea = new JTextArea(20,50);
        jTextArea.setText("我爱学Java");
        //SCROLL面板
        JScrollPane jScrollPane = new JScrollPane(jTextArea);
        contentPane.add(jScrollPane);
        this.setVisible(true);
        this.setBounds(10,10,600,600);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JScrollDemo();
    }
}

按钮

图片按钮

package com.gui.lesson05;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo01 extends JFrame {
    public JButtonDemo01(){
        Container contentPane = this.getContentPane();
        URL resource = this.getClass().getResource("1.jpg");
        //将图片变为图标
        ImageIcon imageIcon = new ImageIcon(resource);
        //把这个图标放在按钮上
        JButton jButton = new JButton();
        jButton.setIcon(imageIcon);
        jButton.setToolTipText("图片按钮");
        contentPane.add(jButton);
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo01();
    }
}

单选按钮

package com.gui.lesson05;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo02 extends JFrame{
    public JButtonDemo02(){
        Container contentPane = this.getContentPane();
        //将图片变为图标
        URL resource = this.getClass().getResource("1.jpg");
        ImageIcon imageIcon = new ImageIcon(resource);
        //单选框
        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);
        contentPane.add(jRadioButton1,BorderLayout.NORTH);
        contentPane.add(jRadioButton2,BorderLayout.CENTER);
        contentPane.add(jRadioButton3,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo02();
    }
}

复选按钮

package com.gui.lesson05;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class JButtonDemo03 extends JFrame{
    public JButtonDemo03(){
        Container contentPane = this.getContentPane();
        //将图片变为图标
        URL resource = this.getClass().getResource("1.jpg");
        ImageIcon imageIcon = new ImageIcon(resource);
        //多选框
        JCheckBox jCheckBox1 = new JCheckBox("jCheckBox1");
        JCheckBox jCheckBox2 = new JCheckBox("jCheckBox2");
        JCheckBox jCheckBox3 = new JCheckBox("jCheckBox3");
        contentPane.add(jCheckBox1,BorderLayout.NORTH);
        contentPane.add(jCheckBox2,BorderLayout.CENTER);
        contentPane.add(jCheckBox3,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo03();
    }
}

列表

下拉框

package com.gui.lesson06;
import javax.swing.*;
import java.awt.*;
public class TestComboboxDemo01 extends JFrame {
    public TestComboboxDemo01 (){
        Container contentPane = this.getContentPane();
        JComboBox jComboBox = new JComboBox();
        jComboBox.addItem(null);
        jComboBox.addItem("正在上映");
        jComboBox.addItem("已下架");
        jComboBox.addItem("即将上映");
        contentPane.add(jComboBox);
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestComboboxDemo01();
    }
}

列表框

package com.gui.lesson06;
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
public class TestComboboxDemo02 extends JFrame {
    public TestComboboxDemo02 (){
        Container contentPane = this.getContentPane();
        //生成列表的内容
        //String [] contents = {"1","2","3"};
        Vector contents = new Vector();
        contents.add("1");
        contents.add("2");
        contents.add("3");
        //列表中需要放入内容
        JList jList = new JList(contents);
        contentPane.add(jList);
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestComboboxDemo02();
    }
}
  • 应用场景
    • 选择地区,或者单个选项
    • 列表,展示信息,一般是动态扩容

文本框

文本框

package com.gui.lesson06;
import javax.swing.*;
import java.awt.*;
public class TestTextDemo01 extends JFrame {
    public TestTextDemo01(){
        Container contentPane = this.getContentPane();
        JTextField jTextField1 = new JTextField("hello");
        JTextField jTextField2 = new JTextField("world",20);
        contentPane.add(jTextField1,BorderLayout.NORTH);
        contentPane.add(jTextField2,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestTextDemo01();
    }
}

密码框

package com.gui.lesson06;
import javax.swing.*;
import java.awt.*;
public class TestTextDemo02 extends JFrame {
    public TestTextDemo02(){
        Container contentPane = this.getContentPane();
        JPasswordField jPasswordField = new JPasswordField();
        jPasswordField.setEchoChar('*');
        contentPane.add(jPasswordField);
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestTextDemo02();
    }
}

贪吃蛇

  • 帧: 时间片足够小,就是动画,一秒三十帧,六十帧,连起来是动画,拆开就是静态的图片,

    1. 键盘监听
    2. 定时器 Timer
  • 大体流程

    1. 定义数据
    2. 画上去
    3. 监听事件
      • 键盘
      • 事件
  • 游戏主线程

package com.gui.snake;
import javax.swing.*;
//游戏的主启动类
public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setResizable(false);
        frame.setBounds(10,10,900,720);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //正常游戏界面都应该在上面
        frame.add(new GamePanel());
        frame.setVisible(true);
    }
}
  • 游戏资源类
package com.gui.snake;
import javax.swing.*;
import java.net.URL;
//数据中心
public class Data {
    private static URL headerURL=Data.class.getResource("statics/header.png");
    private static ImageIcon header=new ImageIcon(headerURL);
    private static URL bodyURL=Data.class.getResource("statics/body.png");
    private static ImageIcon body=new ImageIcon(bodyURL);
    private static URL downURL=Data.class.getResource("statics/down.png");
    private static ImageIcon down=new ImageIcon(downURL);
    private static URL foodURL=Data.class.getResource("statics/food.png");
    private static ImageIcon food=new ImageIcon(foodURL);
    private static URL leftURL=Data.class.getResource("statics/left.png");
    private static ImageIcon left=new ImageIcon(leftURL);
    private static URL rightURL=Data.class.getResource("statics/right.png");
    private static ImageIcon right=new ImageIcon(rightURL);
    private static URL upURL=Data.class.getResource("statics/up.png");
    private static ImageIcon up=new ImageIcon(upURL);
    public static ImageIcon getHeader() {
        return header;
    }
    public static void setHeader(ImageIcon header) {
        Data.header = header;
    }
    public static ImageIcon getBody() {
        return body;
    }
    public static void setBody(ImageIcon body) {
        Data.body = body;
    }
    public static ImageIcon getDown() {
        return down;
    }
    public static void setDown(ImageIcon down) {
        Data.down = down;
    }
    public static ImageIcon getFood() {
        return food;
    }
    public static void setFood(ImageIcon food) {
        Data.food = food;
    }
    public static ImageIcon getLeft() {
        return left;
    }
    public static void setLeft(ImageIcon left) {
        Data.left = left;
    }
    public static ImageIcon getRight() {
        return right;
    }
    public static void setRight(ImageIcon right) {
        Data.right = right;
    }
    public static ImageIcon getUp() {
        return up;
    }
    public static void setUp(ImageIcon up) {
        Data.up = up;
    }
}
  • 游戏绘制
package com.gui.snake;
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.Objects;
import java.util.Random;
//游戏的面板
public class GamePanel extends JPanel implements KeyListener,ActionListener {
    //定义蛇的数据结构
    private Integer length; //蛇的长度
    private Integer [] snakex=new Integer [600]; // 蛇的x坐标
    private Integer [] snakey=new Integer [500]; // 蛇的y坐标
    private String fx; //蛇头方向
    private  Boolean isStart = false;    //游戏当前状态
    private Integer foodX;//食物坐标
    private Integer foodY;//食物坐标
    Random random=new Random();
    private Boolean isFail=false; //游戏失败
    private Integer score;
    //定时器
    Timer timer=new Timer(100,this); //100毫秒执行一次
    //构造器
    public GamePanel(){
        init();
        //获得焦点和键盘事件
        this.setFocusable(true); //获得焦点事情
        this.addKeyListener(this); //获得键盘的监听事件
    }
    //初始化方法
    public void init(){
        length=3;
        snakex[0]=100;snakey[0]=100; //头的坐标
        snakex[1]=75;snakey[1]=100; //第一节身体
        snakex[2]=50;snakey[2]=100; //第二节身体
        fx="R";//初始方向向右
        timer.start(); //游戏一开始就启动
        //随机投放食物
        foodX=25+25*random.nextInt(34);
        foodY=75+25*random.nextInt(24);
        score=0;
    }
    //绘制面板,游戏中的所有东西,用这个画笔来画
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); //清屏的作用
        //绘制静态的面板
        this.setBackground(Color.white);
        Data.getHeader().paintIcon(this,g,25,11); //头部广告栏
        g.fillRect(25,75,850,600); //默认的游戏界面
        //画积分
        g.setColor(Color.white);
        g.setFont(new Font("微软雅黑",Font.BOLD,20));//设置字体
        g.drawString("长度: "+length,750,30);
        g.drawString("分数: "+score,750,55);
        //画食物
        Data.getFood().paintIcon(this,g,foodX,foodY);
        //画小蛇
        if(fx.equals("R")){
            Data.getRight().paintIcon(this,g,snakex[0],snakey[0]); //蛇头
        } else if (fx.equals("L")) {
            Data.getLeft().paintIcon(this,g,snakex[0],snakey[0]); //蛇头
        } else if (fx.equals("U")) {
            Data.getUp().paintIcon(this,g,snakex[0],snakey[0]); //蛇头
        } else if (fx.equals("D")) {
            Data.getDown().paintIcon(this,g,snakex[0],snakey[0]); //蛇头
        }
        for (int i = 1; i < length; i++) {
            Data.getBody().paintIcon(this,g,snakex[i],snakey[i]);  //身体
        }
        //游戏状态
        if(!isStart){
            g.setColor(Color.WHITE);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//设置字体
            g.drawString("按下空格开始游戏!",300,400);
        }
        //游戏失败
        if(isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//设置字体
            g.drawString("失败,按下空格重新开始!",300,400);
        }
    }
    //键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        Integer keyCode = e.getKeyCode(); //获得键盘的按键是哪一个
        if(keyCode==KeyEvent.VK_SPACE){ //如果按下的是空格键
            if(isFail){
                isFail=false;
                init();
            }else{
                isStart=!isStart; //取反
            }
            repaint();
        }
        //小蛇移动
        if(keyCode==KeyEvent.VK_UP){
            fx="U";
        }else if(keyCode==KeyEvent.VK_DOWN){
            fx="D";
        }else if(keyCode==KeyEvent.VK_LEFT){
            fx="L";
        }else if(keyCode==KeyEvent.VK_RIGHT){
            fx="R";
        }
    }
    //事件监听  需要通过固定事件来刷新 1s=10次?
    @Override
    public void actionPerformed(ActionEvent e) {
        if(isStart && !isFail){//如果游戏是开始状态,让他动
            //吃食物
            if(Objects.equals(snakex[0], foodX) && Objects.equals(snakey[0], foodY)){
                length++;
                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(fx.equals("R")){
                snakex [0]+=25;
                //边界判断
                if(snakex[0]>850)snakex[0]=25;
            }else if(fx.equals("L")){
                snakex [0]-=25;
                if(snakex[0]<25)snakex[0]=850;
            }else if(fx.equals("U")){
                snakey [0]-=25;
                if(snakey[0]<75)snakey[0]=650;
            }else if(fx.equals("D")){
                snakey [0]+=25;
                if(snakey[0]>650)snakey[0]=75;
            }
            //失败判定,撞到自己
            for (Integer i = 1; i < length; i++) {
                if(Objects.equals(snakex[0], snakex[i]) && Objects.equals(snakey[0], snakey[i])){
                    isFail=true;
                }
            }
            repaint(); //重画
        }
        timer.start(); //定时器开启
    }
    @Override
    public void keyTyped(KeyEvent e) {

    }
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
  • 图片素材

图片素材

提取码:

qbm4
版权声明:本文为liguangyu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/liguangyu/p/16413377.html