当前位置:

15.GUI编程

故人归 |  2025-07-13
 4人浏览

01.GUI编程简介

怎么学

  • 这是什么?
  • 怎么玩?
  • 该如何在我们平时运用?

组件

  • 窗口
  • 弹窗
  • 面板
  • 文本框
  • 列表框
  • 按钮
  • 图片
  • 监听事件
    • 鼠标事件
    • 键盘事件

简介

GUI核心:Swing AWT

没有流行

  • 界面不美观
  • 需要jre环境

那为啥要学习?

  • 可以写出自己心中想要的一些小工具
  • 工作时候,也可能需要维护到swing界面,概率极小
  • 了解MVC架构,连接监听!

02.AWT介绍

  1. 包含了很多类和接口!
  2. 元素:窗口,按钮,文本框
  3. java.awt

image-20210323215956687

03.第一个Frame窗口

public class TestFrame {
    public static void main(String[] args) {
        //创建窗口
        Frame frame = new Frame("界面窗口");
        //设置窗口的可见性
        frame.setVisible(true);
        //设置窗口的大小
        frame.setSize(400,400);
        //设置背景颜色
        frame.setBackground(new Color(116, 217, 99));
        //弹出的初始位置
        frame.setLocation(200,200);
        //设置大小固定
        frame.setResizable(false);
    }
}

image-20210323221521217

问题:发现窗口关闭不掉--暂时可以停止java运行

尝试回顾封装

public class TestFrame2 {
    public static void main(String[] args) {
        MyFrame myFrame1 = new MyFrame(100,100,200,200,Color.BLACK);
        MyFrame myFrame2 = new MyFrame(300,100,200,200,Color.BLUE);
        MyFrame myFrame3 = new MyFrame(100,300,200,200,Color.DARK_GRAY);
        MyFrame myFrame4 = new MyFrame(300,300,200,200,Color.GREEN);
    }
}

class MyFrame extends Frame {
    private static int id = 0;

    MyFrame(int x, int y, int w, int h, Color color) {
        super("窗口" + (id++));
        setVisible(true);
        setBounds(x, y, w, h);
        setBackground(color);
    }
}

image-20210323222647712

04.Panel面板讲解

解决了关闭的问题!

public class TestPanel {
    public static void main(String[] args) {
        //窗口
        Frame frame = new Frame("窗口");
        frame.setBounds(300,300, 500,500);
        frame.setBackground(new Color(49, 248, 90));
        //设置布局
        frame.setLayout(null);
        //面板
        Panel panel = new Panel();
        panel.setBounds(100,100,300,300);
        panel.setBackground(new Color(200, 36, 4));

        //面板添加到窗口里
        frame.add(panel);
        frame.setVisible(true);
        //监听事件,监听窗口关闭事件
        frame.addWindowListener(new WindowAdapter() {
            //点击关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //关闭程序
                System.exit(0);
            }
        });
    }
}

image-20210324214807527

05.3种布局管理器

  • 流式布局
  • 东西南北中
  • 表格布局

流式布局

public class TestFlowLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("窗口");
        //流式布局 new FlowLayout()默认居中
        frame.setLayout(new FlowLayout());
        //frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        //frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
        frame.setBounds(200,200,300,300);
        //组件--按钮
        Button button01 = new Button("Button01");
        Button button02 = new Button("Button02");
        Button button03 = new Button("Button03");

        frame.add(button01);
        frame.add(button02);
        frame.add(button03);

        //关闭
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.setVisible(true);

    }
}

image-20210324220026504

东南西北中

public class TestBorderLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("窗口");
        frame.setBounds(200, 200, 300, 300);

        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.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        frame.setVisible(true);
    }
}

image-20210324220801958

表格

public class TestGradLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("窗口");
        frame.setBounds(200, 200, 300, 300);

        frame.setLayout(new GridLayout(3, 2));
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        Button button4 = new Button("button4");
        Button button5 = new Button("button5");
        Button button6 = new Button("button6");

        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.add(button6);
        //java函数
        frame.pack();
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        frame.setVisible(true);
    }
}

image-20210324221718268

06.课堂练习讲解及总结

public class PracticeDemo {
    public static void main(String[] args) {
        Frame frame = new Frame("窗口");
        frame.setBounds(200, 200, 400, 300);
        frame.setLayout(new GridLayout(2, 1));

        //四个面板
        Panel p1 = new Panel();
        p1.setLayout(new BorderLayout());
        p1.add(new Button("west1"), BorderLayout.WEST);
        Panel p2 = new Panel();
        p2.setLayout(new GridLayout(2, 1));
        p2.add(new Button("up"));
        p2.add(new Button("down"));
        p1.add(p2, BorderLayout.CENTER);
        p1.add(new Button("east1"), BorderLayout.EAST);


        Panel p3 = new Panel();
        p3.setLayout(new BorderLayout());
        p3.add(new Button("west2"), BorderLayout.WEST);
        Panel p4 = new Panel();
        p4.setLayout(new GridLayout(2, 2));
        for (int i = 1; i <= 4; i++) {
            p4.add(new Button("b" + i));
        }
        p3.add(p4, BorderLayout.CENTER);
        p3.add(new Button("east2"), BorderLayout.EAST);

        frame.add(p1);
        frame.add(p3);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

image-20210324224327004

总结:

  1. Frame是一个顶级窗口
  2. Panel无法单独显示,必须添加到某个容器中
  3. 布局管理器
    1. 流式
    2. 东西南北中
    3. 表格
  4. 大小,定位,背景颜色,可见性,监听!

07.事件监听

事件监听:当某个事件发生时,干什么?

public class TestActionEvent {
    public static void main(String[] args) {
        //按一下按钮,触发一些事件
        Frame frame = new Frame("窗口");
        frame.setBounds(200,200,300,300);
        Button button = new Button();
        button.addActionListener(new MyActionListener());
        frame.add(button);
        frame.pack();
        windowClose(frame);
        frame.setVisible(true);
    }

    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("action");
    }
}

多个按钮公用一个事件

public class TestActionEvent2 {
    public static void main(String[] args) {
        //按一下按钮,触发一些事件
        Frame frame = new Frame("窗口");
        Button b1 = new Button("start");
        Button b2 = new Button("stop");
        //可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值。
        //可以多个按钮只写一个监听类
        b2.setActionCommand("b2-command");

        MyMonitor myMonitor = new MyMonitor();

        b1.addActionListener(myMonitor);
        b2.addActionListener(myMonitor);

        frame.setLayout(new BorderLayout());
        frame.add(b1, BorderLayout.NORTH);
        frame.add(b2, BorderLayout.SOUTH);

        frame.pack();
        windowClose(frame);
        frame.setVisible(true);
    }

    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()+"按钮被点击了!");
    }
}

08.输入框事件监听

输入框TextField

public class TestText01 {
    public static void main(String[] args) {
        MyFrame myFrame = new MyFrame("窗口");
        //关闭窗口事件
        windowClose(myFrame);
        //设置窗口可见性
        myFrame.setVisible(true);
    }

    /**
     * 关闭窗口事件
     * @param frame
     */
    private static void windowClose(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class MyFrame extends Frame {
    public MyFrame(String title) {
        super(title);

        TextField textField = new TextField();
        //按一下enter就会触发这个输入框事件
        textField.addActionListener(new MyActionListener2());
        //页面数据录入的时候会展示*
        textField.setEchoChar('*');
        //输入框中添加文本域
        add(textField);
        //设置自适应
        pack();
    }
}

class MyActionListener2 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField textField = (TextField) e.getSource();
        System.out.println(textField.getText());
        textField.setText(null);
    }
}

09.简易计算器、回顾组合内部类

oop原则:组合,大于继承

目前代码

public class TestCalculator {
    public static void main(String[] args) {
        new MyCalculator("计算器");
    }
}

class MyCalculator extends Frame {
    MyCalculator(String title) {
        super(title);
        //3个文本框(字符数)
        TextField n1 = new TextField(10);
        TextField n2 = new TextField(10);
        TextField n3 = new TextField(20);
        //1一个标签
        Label l1 = new Label("+");
        //1个按钮
        Button b1 = new Button("=");

        b1.addActionListener(new MyCalculatorListener(n1, n2, n3));
        //流式布局
        setLayout(new FlowLayout());
        add(n1);
        add(l1);
        add(n2);
        add(b1);
        add(n3);
        pack();
        closeWindows(this);
        setVisible(true);
    }

    private void closeWindows(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class MyCalculatorListener implements ActionListener {
    private TextField n1, n2, n3;

    MyCalculatorListener(TextField n1, TextField n2, TextField n3) {
        this.n1 = n1;
        this.n2 = n2;
        this.n3 = n3;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int i1 = Integer.parseInt(n1.getText());
        int i2 = Integer.parseInt(n2.getText());

        n3.setText("" + (i1 + i2));
        n1.setText(null);
        n2.setText(null);
    }
}

改成面向对象

public class TestCalculator {
    public static void main(String[] args) {
        new MyCalculator("计算器").loadFrame();
    }
}

class MyCalculator extends Frame {

    protected TextField n1, n2, n3;

    public void loadFrame() {
        n1 = new TextField(10);
        n2 = new TextField(10);
        n3 = new TextField(20);
        Label l1 = new Label("+");
        Button b1 = new Button("=");

        b1.addActionListener(new MyCalculatorListener(this));

        setLayout(new FlowLayout());

        add(n1);
        add(l1);
        add(n2);
        add(b1);
        add(n3);

        pack();
        closeWindows(this);
        setVisible(true);
    }

    MyCalculator(String title) {
        super(title);
    }

    private void closeWindows(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class MyCalculatorListener implements ActionListener {
    private MyCalculator myCalculator;

    MyCalculatorListener(MyCalculator myCalculator) {
        this.myCalculator = myCalculator;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int i1 = Integer.parseInt(myCalculator.n1.getText());
        int i2 = Integer.parseInt(myCalculator.n2.getText());

        myCalculator.n3.setText("" + (i1 + i2));
        myCalculator.n1.setText(null);
        myCalculator.n2.setText(null);
    }
}

内部类

  • 更好的包装
public class TestCalculator {
    public static void main(String[] args) {
        new MyCalculator("计算器").loadFrame();
    }
}

class MyCalculator extends Frame {
    private TextField n1, n2, n3;

    MyCalculator(String title) {
        super(title);
    }

    public void loadFrame() {
        n1 = new TextField(10);
        n2 = new TextField(10);
        n3 = new TextField(20);
        Label l1 = new Label("+");
        Button b1 = new Button("=");

        b1.addActionListener(new MyCalculatorListener());

        setLayout(new FlowLayout());

        add(n1);
        add(l1);
        add(n2);
        add(b1);
        add(n3);

        pack();
        closeWindows(this);
        setVisible(true);
    }

    private void closeWindows(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    //内部类最大的好处,就是可以畅通无阻的访问外部的属性和方法
    private class MyCalculatorListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int i1 = Integer.parseInt(n1.getText());
            int i2 = Integer.parseInt(n2.getText());

            n3.setText("" + (i1 + i2));
            n1.setText(null);
            n2.setText(null);
        }
    }
}

10.画笔Paint

public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}

class MyPaint extends Frame {
    public void loadFrame() {
        setBounds(200,200, 500,400);
        windowClose(this);
        setVisible(true);
    }

    private void windowClose(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.drawOval(100,100,100,100);
        //实心圆
        g.fillOval(200,100,100,100);
        //长方形
        g.fillRect(300,100,100,100);
        //养成习惯,画笔用完,将它还原到最初的颜色
        g.setColor(Color.BLACK);
    }
}

11.鼠标监听事件、模拟画图工具

目的:想要实现鼠标画点

image-20210330144321123

public class TestMouseListener {
    public static void main(String[] args) {
        new MyDrawPointFrame("画点");
    }
}

class MyDrawPointFrame extends Frame {
    private ArrayList<Point> points;

    MyDrawPointFrame(String title) {
        super(title);
        setBounds(200, 200, 400, 500);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                //清空点
                points.clear();
                System.exit(0);
            }
        });
        setVisible(true);
        points = new ArrayList<>();
        addMouseListener(new MyMouseListener());
    }

    @Override
    public void paint(Graphics g) {
        Iterator<Point> iterator = points.iterator();
        while (iterator.hasNext()) {
            Point point = iterator.next();
            //设置点的颜色
            g.setColor(Color.BLUE);
            //画点
            g.fillOval(point.x, point.y, 5, 5);
        }
    }

    public void addPoint(Point point) {
        points.add(point);
    }

}

class MyMouseListener extends MouseAdapter {
    @Override
    public void mousePressed(MouseEvent e) {
        MyDrawPointFrame myDrawPointFrame = (MyDrawPointFrame) e.getSource();
        //添加点
        myDrawPointFrame.addPoint(new Point(e.getX(), e.getY()));
        //重要:每次点击鼠标都需要需要重新画一遍(因为第一次points中没有元素,之后点没有重画的话,是显示不了的)  刷新
        myDrawPointFrame.repaint();
    }
}

image-20210330144009359

12.窗口监听事件

public class TestWindow {
    public static void main(String[] args) {
        new MyWindowFrame();
    }
}

class MyWindowFrame extends Frame {
    public MyWindowFrame() {
        setBounds(200, 200, 300, 300);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            /**
             * 关闭
             * @param e
             */
            @Override
            public void windowClosing(WindowEvent e) {
                //正常退出
                System.exit(0);
            }

            /**
             * 激活
             * @param e
             */
            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("窗口被激活");
            }
        });
    }
}

13.键盘监听事件

public class TestKeyListener {
    public static void main(String[] args) {
        new MyKeyFrame();
    }
}

class MyKeyFrame extends Frame {
    public MyKeyFrame() {
        setBounds(100,100,300,300);
        setVisible(true);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_UP) {
                    System.out.println("点了一下方向上键");
                }
            }
        });
    }
}

14.Swing之JFrame窗体

public class JFrameDemo {
    public static void main(String[] args) {
        new MyJFrame().init("JFrame");
    }
}

class MyJFrame extends JFrame {
    public void init(String title) {
        setTitle(title);
        setBounds(200,200,500,500);
        setVisible(true);
        //关闭
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JLabel jLabel = new JLabel("jLabel");
        //设置水平对齐
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        add(jLabel);
        //获取一个容器
        Container contentPane = this.getContentPane();
        //设置背景颜色
        contentPane.setBackground(Color.YELLOW);
    }
}

image-20210330162131565

15.JDialog弹窗

public class JDialogDemo {
    public static void main(String[] args) {
        new DialogFrame();
    }
}

class DialogFrame extends JFrame {
    public DialogFrame() {
        setVisible(true);
        setBounds(100, 100, 500, 500);
        //获取容器
        Container contentPane = this.getContentPane();
        //绝对布局
        contentPane.setLayout(null);
        JButton jButton = new JButton("点一下弹出");
        jButton.setBounds(50, 50, 100, 100);
        jButton.addActionListener(e -> new MyDialog());
        contentPane.add(jButton);

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

class MyDialog extends JDialog {
    public MyDialog() {
        setVisible(true);
        setBounds(200, 200, 200, 200);
        Container contentPane = this.getContentPane();
        JLabel label = new JLabel("加油加油");
        contentPane.add(label);
        //不用关闭了,JDialog有自带的
//        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

16.Icon、ImageIcon标签

图标Icon

public class IconDemo extends JFrame implements Icon {
    private int width;
    private int height;

    public IconDemo(int width, int height) {
        this.width = width;
        this.height = height;
    }


    public static void main(String[] args) {
        new IconDemo(10, 10).init();
    }

    public void init() {
        setBounds(100, 100, 300, 300);
        Container container = this.getContentPane();
        JLabel jLabel = new JLabel("jLabel", this, SwingConstants.CENTER);
        container.add(jLabel);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.setColor(Color.YELLOW);
        g.fillOval(x, y, this.width, this.height);
    }

    @Override
    public int getIconWidth() {
        return this.width;
    }

    @Override
    public int getIconHeight() {
        return this.height;
    }
}

图片Icon

public class ImageIconDemo extends JFrame {
    public static void main(String[] args) {
        new ImageIconDemo();
    }

    public ImageIconDemo() {
        setVisible(true);
        setBounds(200, 200, 800, 800);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = getContentPane();
        URL url = ImageIconDemo.class.getResource("1569761996752.jpg");
        ImageIcon imageIcon = new ImageIcon(url);
        JLabel jLabel = new JLabel("jLabel");
        jLabel.setIcon(imageIcon);
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        container.add(jLabel);

    }
}

17.文本域JScroll面板

JPanel

public class JPanelDemo extends JFrame {

    public static void main(String[] args) {
        new JPanelDemo();
    }

    public JPanelDemo() {
        setVisible(true);
        setBounds(300, 300, 500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = getContentPane();
        container.setLayout(new GridLayout(2, 1, 10, 10));
        //创建2个面板
        JPanel jp1 = new JPanel(new GridLayout(1, 3));
        JPanel jp2 = new JPanel(new GridLayout(2, 2));
        jp1.add(new JButton("1-1"));
        jp1.add(new JButton("1-2"));
        jp1.add(new JButton("1-3"));
        jp2.add(new JButton("1-1"));
        jp2.add(new JButton("1-2"));
        jp2.add(new JButton("2-1"));
        jp2.add(new JButton("2-2"));
        container.add(jp1);
        container.add(jp2);
    }
}

image-20210330215250122

JScroll

public class JScrollDemo extends JFrame {

    public static void main(String[] args) {
        new JScrollDemo();
    }

    public JScrollDemo() {
        setVisible(true);
        setBounds(200, 200, 400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();

        TextArea textArea = new TextArea(20, 50);
        textArea.setText("学习中");
        JScrollPane scrollPane = new JScrollPane(textArea);

        container.add(scrollPane);
    }
}

image-20210330220827860

18.图片按钮、单选框、多选框

图片按钮

public class JButtonDemo extends JFrame {
    public static void main(String[] args) {
        new JButtonDemo();
    }

    public JButtonDemo() {
        setVisible(true);
        setBounds(200, 200, 500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        URL url = JButtonDemo.class.getResource("1569761996752.jpg");
        ImageIcon imageIcon = new ImageIcon(url);

        JButton jButton = new JButton();
        jButton.setIcon(imageIcon);
        jButton.setToolTipText("这是一个图片按钮");

        container.add(jButton);
    }
}

单选框

public class JRadioButtonDemo extends JFrame {
    public static void main(String[] args) {
        new JRadioButtonDemo();
    }

    public JRadioButtonDemo() {
        setVisible(true);
        setBounds(200, 200, 500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());

        JRadioButton b1 = new JRadioButton("b1");
        JRadioButton b2 = new JRadioButton("b2");
        JRadioButton b3 = new JRadioButton("b3");
        //单选框,放到一个组里,才能只选中其中一个
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(b1);
        buttonGroup.add(b2);
        buttonGroup.add(b3);

        container.add(b1, BorderLayout.NORTH);
        container.add(b2, BorderLayout.CENTER);
        container.add(b3, BorderLayout.SOUTH);
    }

}

image-20210330223731085

复选框

public class JCheckBoxDemo extends JFrame {
    public static void main(String[] args) {
        new JCheckBoxDemo();
    }
    public JCheckBoxDemo() {
        setVisible(true);
        setBounds(200,200,500,500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());

        JCheckBox c1 = new JCheckBox("JCheckBox-01");
        JCheckBox c2 = new JCheckBox("JCheckBox-02");
        JCheckBox c3 = new JCheckBox("JCheckBox-03");

        container.add(c1, BorderLayout.NORTH);
        container.add(c2, BorderLayout.CENTER);
        container.add(c3, BorderLayout.SOUTH);

    }
}

image-20210330223658192

如何实现全选和全不选呢?

public class JCheckBoxDemo extends JFrame {
    public static void main(String[] args) {
        new JCheckBoxDemo();
    }

    public JCheckBoxDemo() {
        setVisible(true);
        setBounds(200, 200, 500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());

        JCheckBox c1 = new JCheckBox("JCheckBox-ALL");
        JCheckBox c2 = new JCheckBox("JCheckBox-02");
        JCheckBox c3 = new JCheckBox("JCheckBox-03");

        c1.addActionListener((e) -> {
                    JCheckBox checkBox = (JCheckBox) e.getSource();
                    if (checkBox.isSelected()) {
                        c2.setSelected(true);
                        c3.setSelected(true);
                    } else {
                        c2.setSelected(false);
                        c3.setSelected(false);
                    }
                }
        );

        container.add(c1, BorderLayout.NORTH);
        container.add(c2, BorderLayout.CENTER);
        container.add(c3, BorderLayout.SOUTH);
    }
}

19.下拉框、列表框

下拉框

public class ComboboxDemo extends JFrame {
    public static void main(String[] args) {
        new ComboboxDemo();
    }

    public ComboboxDemo() {
        setVisible(true);
        setBounds(200, 200, 100, 100);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        JComboBox<String> comboBox = new JComboBox();
        comboBox.addItem("正在热映");
        comboBox.addItem("热映中");
        comboBox.addItem("即将上映");
        container.add(comboBox);

    }
}

image-20210330224538631

列表框

public class ListDemo extends JFrame {
    public static void main(String[] args) {
        new ListDemo();
    }

    public ListDemo() {
        setVisible(true);
        setBounds(200, 200, 300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();

        String[] strs = {"1","2","3","4"};
        JList<String> list = new JList<>(strs);
        container.add(list);

    }
}

image-20210330225217829

应用场景

  • 选择地区,或者一些单个选项
  • 列表,展示信息,一般是动态扩容!

20.文本框、密码框、文本域

文本框

public class TextDemo extends JFrame {
    public static void main(String[] args) {
        new TextDemo();
    }

    public TextDemo() {
        setVisible(true);
        setBounds(200, 200, 300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());
        JTextField textField1 = new JTextField("hello1",50);
        JTextField textField2 = new JTextField("hello2",50);

        container.add(textField1, BorderLayout.NORTH);
        container.add(textField2, BorderLayout.SOUTH);

    }
}

image-20210330225717676

密码框

public class TextDemo2 extends JFrame {
    public static void main(String[] args) {
        new TextDemo2();
    }

    public TextDemo2() {
        setVisible(true);
        setBounds(200, 200, 300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();

        JPasswordField passwordField = new JPasswordField();
        passwordField.setEchoChar('*');

        container.add(passwordField);
    }
}

image-20210330225958145

文本域

public class JScrollDemo extends JFrame {

    public static void main(String[] args) {
        new JScrollDemo();
    }

    public JScrollDemo() {
        setVisible(true);
        setBounds(200, 200, 400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();

        TextArea textArea = new TextArea(20, 50);
        textArea.setText("学习中");
        JScrollPane scrollPane = new JScrollPane(textArea);

        container.add(scrollPane);
    }
}

image-20210330220827860

21.贪吃蛇之界面绘制

帧,如果时间片足够小,就是动画,一秒30帧。连起来是动画,拆开就是静态的图片!

键盘监听

定时器Timer

22.绘制静态小蛇

23.让小蛇动起来

24.键盘控制小蛇移动

25.小蛇吃食物长大

26.失败判定、积分系统

总结:

  • 初始化数据
  • 画页面
  • 监听
    • 键盘事件监听
    • 事件监听

基础数据

public class Data {
    //相对路径 tx.jpg
    //绝对路径 /  相当于当前项目

    //头部
    public static URL headerUrl = Data.class.getResource("statics/header.png");
    public static ImageIcon header = new ImageIcon(headerUrl);
    //身体
    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);
    //上下左右
    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 class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame("贪吃蛇小游戏");
        frame.setBounds(10, 10, 900, 720);
        //窗口大小不可变
        frame.setResizable(false);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(new GamePanel());
        frame.setVisible(true);
    }
}

面板

public class GamePanel extends JPanel implements KeyListener, ActionListener {

    /**
     * 定义蛇的数据结构
     */
    //蛇的长度
    private int length;
    //蛇的x坐标 25*25
    private int[] snakeX = new int[600];
    //蛇的y坐标 25*25
    private int[] snakeY = new int[500];
    //方向
    private String direction;
    //食物x
    private int foodX;
    //食物y
    private int foodY;
    //食物随机生成用到
    private Random random = new Random();
    //分数
    private int score;
    //是否开始(开始/暂停)
    private boolean isStart = false;
    //是否失败
    private boolean isFail = false;
    //定时器
    private Timer timer = new Timer(100, this);


    /**
     * 构造器
     */
    public GamePanel() {
        init();
        //获得焦点
        setFocusable(true);
        //添加键盘监听事件
        addKeyListener(this);
        //启动定时器
        timer.start();
    }

    /**
     * 初始化
     */
    private void init() {
        //蛇的初始长度
        length = 3;
        //脑袋的坐标
        snakeX[0] = 100;
        snakeY[0] = 100;
        //第一个身体的坐标
        snakeX[1] = 75;
        snakeY[1] = 100;
        //第二个身体的坐标
        snakeX[2] = 50;
        snakeY[2] = 100;
        //初始方向:右
        direction = "R";
        //食物初始化(随机分布)
        foodX = 25 + 25 * random.nextInt(34);
        foodY = 75 + 25 * random.nextInt(24);
        //分数初始化
        score = 0;
    }


    /**
     * 绘制面板,游戏中的所有东西,都使用这个画笔来画
     */
    @Override
    public void paintComponent(Graphics g) {
        //清屏
        super.paintComponents(g);
        this.setBackground(Color.WHITE);
        //绘制静态的面板
        //头部广告栏画上去
        Data.header.paintIcon(this, g, 25, 15);
        //画一个矩形 -- 默认的游戏界面
        g.fillRect(25, 75, 850, 600);
        //画上长度和分数
        g.setColor(Color.WHITE);
        g.setFont(new Font("微软雅黑", Font.BOLD, 18));
        g.drawString("长度 "+length, 750, 38);
        g.drawString("分数 "+score, 750, 57);
        //把小蛇画上去
        //蛇头
        switch (direction) {
            case "L": {
                Data.left.paintIcon(this, g, snakeX[0], snakeY[0]);
                break;
            }
            case "R": {
                Data.right.paintIcon(this, g, snakeX[0], snakeY[0]);
                break;
            }
            case "U": {
                Data.up.paintIcon(this, g, snakeX[0], snakeY[0]);
                break;
            }
            case "D": {
                Data.down.paintIcon(this, g, snakeX[0], snakeY[0]);
                break;
            }
            default: {
                break;
            }
        }
        //蛇的身体
        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) {
            //画白色的提示文字
            g.setColor(Color.WHITE);
            g.setFont(new Font("微软雅黑", Font.BOLD, 40));
            g.drawString("按下空格开始游戏!", 300, 300);
        }
        //失败提示
        if (isFail) {
            //画白色的提示文字
            g.setColor(Color.WHITE);
            g.setFont(new Font("微软雅黑", Font.BOLD, 30));
            g.drawString("游戏失败,请按下空格重新开始游戏!", 200, 300);
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    /**
     * 键盘监听
     * @param e
     */
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_SPACE) {
            if (isFail) {
                //重新开始
                isFail = false;
                init();
            } else {
                isStart = !isStart;
            }
            repaint();
        }
        //小蛇移动
        switch (keyCode) {
            case KeyEvent.VK_UP: {
                direction = "U";
                break;
            }
            case KeyEvent.VK_DOWN: {
                direction = "D";
                break;
            }
            case KeyEvent.VK_LEFT: {
                direction = "L";
                break;
            }
            case KeyEvent.VK_RIGHT: {
                direction = "R";
                break;
            }
            default: {
                break;
            }
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    /**
     * 事件监听--需要固定的时间来刷新,10次/1s
     *
     * @param e
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && !isFail) {
            //吃食物
            if (snakeX[0] == foodX && snakeY[0] == foodY) {
                //长度+1
                length++;
                //分数+10
                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];
            }
            //头部移动,并设置边界
            switch (direction) {
                case "U": {
                    snakeY[0] -= 25;
                    //设置边界
                    if (snakeY[0] < 75) {
                        snakeY[0] = 650;
                    }
                    break;
                }
                case "D": {
                    snakeY[0] += 25;
                    //设置边界
                    if (snakeY[0] > 650) {
                        snakeY[0] = 75;
                    }
                    break;
                }
                case "L": {
                    snakeX[0] -= 25;
                    //设置边界
                    if (snakeX[0] < 25) {
                        snakeX[0] = 850;
                    }
                    break;
                }
                case "R": {
                    snakeX[0] += 25;
                    //设置边界
                    if (snakeX[0] > 850) {
                        snakeX[0] = 25;
                    }
                    break;
                }
                default: {
                    break;
                }
            }
            //撞到自己的身体,就失败了
            for (int i = 1; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
                    isFail = true;
                }
            }
            //重画页面
            repaint();
        }
    }
}

小图标

身体

body

下

down

食物

food

头部

header

左

left

右

right

上

up

最终成品

image-20210401225306291

27.GUI阶段回顾与总结

文章评论