GUI基础

GUI编程:

一个界面的组件:

  • 窗口
  • 弹窗
  • 面板
  • 文本框
  • 列边框
  • 按钮
  • 图片
  • 监听事件
  • 鼠标
  • 键盘事件
  • 破解工具

1 简介

Gui的核心技术:Swing AWT,

不流行的原因:

  1. 因为不美观
  2. 需要Gre环境

为什么我们要学习?

  1. 可以写出自己心中的想要的小工具
  2. 工作的时候,也可能需要维护到swiing界面,概率极低
  3. 了结MVC架构,了结监听

2 AWT

2.1 Awt介绍

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

image-20210528231233640

2.2、组件和容器

1、Frame

package com.kang.lesson1;

import java.awt.*;

public class TestFrame {
    public static void main(String[] args) {

        // 看源码,JDK,Frame
        Frame frame = new Frame("我的第一个java图形窗口");

        //设置可见性
        frame.setVisible(true);
        //设置窗口大小
        frame.setSize(200,200);
        //设置窗口背景颜色
        frame.setBackground(new Color(116, 53, 148));
        //设置弹出坐标位置
        frame.setLocation(200, 200);
        //设置大小是否固定
        frame.setResizable(true);

    }
}

结果如下所示:

import java.awt.*;

public class TestFrame2 {
    public static void main(String[] args) {
        new MyFrame(100, 100, 100, 100, Color.YELLOW);
        new MyFrame(200, 100, 100, 100, Color.GRAY);
        new MyFrame(100, 200, 100, 100, Color.blue);
        new MyFrame(200, 200, 100, 100, Color.green);
    }
}
class MyFrame extends Frame {

    static int id = 0;
    public  MyFrame(int x,int y,int w,int h,Color color){
        super("MyFrame"+(++id));
        super.setBounds(x, y, w, h);
        super.setBackground(color);
        setVisible(true);
    }
}

结果显示:

2、 面板

解决了窗口关闭事件!

package com.kang.lesson1;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class TestPanel {
    //panel 可以看成一个空间,但是不能单独存在
    public static void main(String[] args) {
        Frame frame = new Frame();
        //b布局的概念
        Panel panel = new Panel();

        //设置布局
        frame.setLayout(null);
        //设置坐标
        frame.setBounds(100, 100, 500, 500);
        frame.setBackground(new Color(203, 68, 203));

        panel.setBounds(50, 50, 400, 400);
        panel.setBackground(new Color(221, 55, 55));

        //窗口添加面板frame.add(panel)
        frame.add(panel);
        frame.setVisible(true);

        //关闭窗口:监听事件——监听关闭窗口事件System.exit(0);
        frame.addWindowListener(new WindowAdapter() {
//            窗口关闭要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

结果展示:

2.3、 布局

  • 流式布局
package com.kang.lesson1;

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.RIGHT));

        frame.setBounds(100, 100, 300, 300);
        //把按钮添加上去
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);

        frame.setVisible(true);
    }
}

  • 东西南北中
package com.kang.lesson1;

import java.awt.*;

public class TestBorderLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("TestBorderLayout");

        Button button1 = new Button("East");
        Button button2 = new Button("West");
        Button button3 = new Button("South");
        Button button4 = new Button("North");
        Button button5 = new Button("Center");

        frame.add(button1,BorderLayout.EAST);
        frame.add(button2,BorderLayout.WEST);
        frame.add(button3,BorderLayout.SOUTH);
        frame.add(button4,BorderLayout.NORTH);
        frame.add(button5,BorderLayout.CENTER);

        frame.setBounds(100, 100, 400, 400);

        frame.setVisible(true);
    }
}

  • 表格式布局
package com.kang.lesson1;

import java.awt.*;

public class TestGridLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("TestGridLayout");

        Button button1 = new Button("tab1");
        Button button2 = new Button("tab2");
        Button button3 = new Button("tab3");
        Button button4 = new Button("tab4");
        Button button5 = new Button("tab5");
        Button button6 = new Button("tab6");

        frame.setLayout(new GridLayout(3, 2));

        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.add(button6);

        frame.setSize(200, 200);

//        frame.pack(); //java函数,优化布局
        frame.setVisible(true);
    }
}
  • 课后练习
package com.kang.lesson1;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class ExDemo {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setBounds(100, 100, 300, 300);
        frame.setBackground(new Color(121, 23, 96));
        frame.setVisible(true);
        frame.setLayout(new GridLayout(2, 1));

        Panel p1 = new Panel(new BorderLayout());//panel在创建之初就已经形成,不能再被布局
        Panel p2 = new Panel(new BorderLayout());
        Panel p3 = new Panel(new GridLayout(2, 1));
        Panel p4 = new Panel(new GridLayout(2, 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");

        p3.add(button3);
        p3.add(button4);

        for (int i = 7; i < 11; i++) {
            p4.add(new Button("button"+i));
        }

        p1.add(button1,BorderLayout.WEST);
        p1.add(p3,BorderLayout.CENTER);
        p1.add(button2,BorderLayout.EAST);

        p2.add(button5,BorderLayout.WEST);
        p2.add(p4,BorderLayout.CENTER);
        p2.add(button6,BorderLayout.EAST);

        frame.add(p1);
        frame.add(p2);

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

总结:

  1. Frame是个一个顶级窗口

  2. Panel无法单独显示,必须添加到某个容器中

  3. 布局管理器

    1. 流式布局管理器
    2. 东西南北中管理器
    3. 表格管理器
  4. 大小、背景、颜色,监听

2.4、监听事件

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

package com.kang.lesson2;

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 TestActonEvent {
    public static void main(String[] args) {
        //按下按钮,触发一些事件
        Frame frame = new Frame("TestActonEvent");
        Button button = new Button("button1");

        frame.add(button,BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);

        //因为 addActionListener() 需要一个ActionListener类,所以构造一个ActionListener
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);

        frameClosing(frame);
    }
    //关闭窗口的方法
    public static void frameClosing(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("aaaaaa");
    }
}

多个按钮共享一个事件:

package com.kang.lesson2;

import java.awt.*;
import java.awt.event.*;

public class TestActonEvent02 {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setBounds(100, 100, 200, 200);
        frame.setBackground(new Color(196, 28, 28));
        frame.setVisible(true);
        windowsClose(frame);

        Button button1 = new Button("button-start");
        Button button2 = new Button("button-stop");
        frame.add(button1,BorderLayout.NORTH);
        frame.add(button2,BorderLayout.SOUTH);

        // 在可以显示的定义,触发会返回的命令。如果不设置,则会走默认值
        // 可以多个按钮,用一个监听类
        button1.setActionCommand("start");

        MyMonitor myMonitor = new MyMonitor();
        button1.addActionListener(myMonitor);
        button2.addActionListener(myMonitor);


    }
    //关闭窗口
    public static void windowsClose(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) {
        //e.getActionCommand() 获得按钮的信息
        System.out.println("按钮被点击了,输出的信息:"+e.getActionCommand());
        if (e.getActionCommand().equals("start")){

        }
    }
}

2.5、输入框

package com.kang.lesson2;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestText01 {
    public static void main(String[] args) {
        MyFrame myFrame = 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();
    }
}
class MyActionListener2 implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField field = (TextField) e.getSource();//获得一些资源,返回一个特定的对象
        System.out.println(field.getText());//获得输入的文本框
        field.setText("Love");//NULL ”“

    }
}

2.6、简易计算器,组合+内部类回顾复习

oop原则:组合,大于继承!!!

class A{	public B b;}
  • 加法计算器
//设计一个简单的加法计算器
package com.kang.lesson2;

import java.awt.*;
import java.awt.event.*;

public class TestCalcu {
    public static void main(String[] args) {
        MyFrame2 myFrame2 = new MyFrame2("Calcu");
        myFrame2.Penal();
    }
}

//计算器显示
class MyFrame2 extends Frame {
    //建立类的初始化参数
    public MyFrame2(String title) {
        super();
        setLayout(new FlowLayout());
        setVisible(true);
        setBackground(new Color(239, 95, 30));
    }
    public void Penal(){

        //一个按钮
        Button button1 = new Button("=");
        //一个标签
        Label label = new Label("+");
        TextField field1 = new TextField(10);//字符数
        TextField field2 = new TextField(10);
        TextField field3 = new TextField(20);

        add(field1);
        add(label);
        add(field2);
        add(button1);
        add(field3);

        //最优化框架
        pack();

        //button动作事件监听
        MyActionListener3 myActionListener3 = new MyActionListener3(field1, field2, field3);
        button1.addActionListener(myActionListener3);

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

class MyActionListener3 implements ActionListener{
    //1. 获取三个变量的值,并转化为int类型
    //2. 将加法运算后的结果,放到第三个框
    //3. 清除前两个框

    private TextField field1;
    private TextField field2;
    private TextField field3;

    public MyActionListener3(TextField field1,TextField field2,TextField field3) {
        this.field1 = field1;
        this.field2 = field2;
        this.field3 = field3;
    }

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

        field1.setText("");
        field2.setText("");
        field3.setText(""+(n1+n2));
    }
}

优化简易计算器代码(组合)

package com.dong.lesson1;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class TestCalcu02 {    public static void main(String[] args) {        Calculator calculator = new Calculator();        calculator.loadCalculator();    }}//计算器class Calculator extends Frame{    //属性:    TextField field1,field2,field3;    //方法:    public void loadCalculator(){        //设置        setBackground(new Color(2, 153, 22));        setLocation(100,100);        setLayout(new FlowLayout());        setVisible(true);        //组件        field1 = new TextField(10);        field2 = new TextField(10);        field3 = new TextField(20);        Label label = new Label("+");        Button button = new Button("=");        //监听        button.addActionListener(new myMonitor(this));        //布局        add(field1);        add(label);        add(field2);        add(button);        add(field3);        //优化布局        pack();    }}//动作监听器class myMonitor implements ActionListener {    //获取这个数据的对象,在一个类中组合另外一个类。    Calculator calculator =null;    //构造器,初始化    public myMonitor(Calculator calculator) {        this.calculator = calculator;    }    @Override    public void actionPerformed(ActionEvent e) {        int n1 = Integer.parseInt(calculator.field1.getText());        int n2 = Integer.parseInt(calculator.field2.getText());        calculator.field1.setText("");        calculator.field2.setText("");        calculator.field3.setText(""+(n1+n2));    }}

再优化简计算器代码(完全改造为面向对象)

内部类:可以是实现更好的包装

package com.dong.lesson1;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class TestCalcu02 {    public static void main(String[] args) {        Calculator calculator = new Calculator();        calculator.loadCalculator();    }}//计算器class Calculator extends Frame{    //属性:    TextField field1,field2,field3;    //方法:    public void loadCalculator(){        //设置        setBackground(new Color(2, 153, 22));        setLocation(100,100);        setLayout(new FlowLayout());        setVisible(true);        //组件        field1 = new TextField(10);        field2 = new TextField(10);        field3 = new TextField(20);        Label label = new Label("+");        Button button = new Button("=");        //监听        button.addActionListener(new myMonitor());        //布局        add(field1);        add(label);        add(field2);        add(button);        add(field3);        //优化布局        pack();    }    //动作监听器    //内部类的最大好吃就是可以畅通无阻的访问外部类的属性    private class myMonitor implements ActionListener {        @Override        public void actionPerformed(ActionEvent e) {            int n1 = Integer.parseInt(field1.getText());            int n2 = Integer.parseInt(field2.getText());            field1.setText("");            field2.setText("");            field3.setText(""+(n1+n2));        }    }}

2.7、画笔

package com.dong.lesson2;import java.awt.*;public class TestPaint {    public static void main(String[] args) {        MyPaint myPaint = new MyPaint();        myPaint.loadMyPaint();    }}class MyPaint extends Frame{    public void loadMyPaint(){        setBounds(100,100,400,500);        setVisible(true);    }    //画笔    @Override    public void paint(Graphics g) {//        super.paint(g);        //画笔,需要有颜色,画笔可以画画        g.setColor(Color.blue);//        g.drawOval(100,100,100,100);        g.fillOval(100,100,50,50);        g.setColor(Color.RED);        g.fillRect(150,150,100,150);        //养成一个习惯,画笔用完,将画笔的颜色还原为最初的颜色    }}

2.8、鼠标监听

目的:

package com.dong.lesson2;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;

public class TestMouseListener {
    public static void main(String[] args) {
        MyFrame frame = new MyFrame("画图");
    }
}
// 鼠标监听的类
class MyFrame extends Frame{
    // 画画需要,
    // 底板(框架)
    // 需要画笔,
    // 需要见监听鼠标事件,从而获取鼠标的坐标,把坐标存起来()
    //画笔读取存储的点位,从而画画
    ArrayList points;
    public MyFrame(String title) {
        super(title);
        setBounds(2,2,400,300);
        setVisible(true);
        points = new ArrayList<>();
        addMouseListener(new MyMouseListener());
    }

    @Override
    public void paint(Graphics g) {
        Iterator iterator=points.iterator();
        while (iterator.hasNext()){
            Point point = (Point) iterator.next();
            g.setColor(new Color(93, 199, 49));
            g.fillOval(point.x,point.y,10,10);
        }
    }
    //添加产生的村储存器中
    public void AddPoint(Point point){
        points.add(point);
    }

    class MyMouseListener extends MouseAdapter{
        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame frame = (MyFrame)e.getSource();
            //把获得点,放在储存器中
            AddPoint(new Point(e.getX(), e.getY()));
            frame.repaint();
        }
    }
}

2.9、 窗口监听

package com.dong.lesson2;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestWindowListener {
    public static void main(String[] args) {
        new WindowFrame();
    }
}
//窗口监听类
class WindowFrame extends Frame{
    public WindowFrame() {
        setVisible(true);
        setBackground(Color.cyan);
        setBounds(100,100,200,300);
        addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("windowClosing");
                setVisible(false);//隐藏敞口
                System.exit(0);//强制关闭窗口
            }

            @Override
            public void windowActivated(WindowEvent e) {
                WindowFrame source = (WindowFrame) e.getSource();
                source.setTitle("被激活了");
                System.out.println("windowActivated");
            }
        });
    }
}

2.10、 键盘监听

package com.dong.lesson2;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileReader;

public class TestKeyListener {
    public static void main(String[] args) {
        new KeyFrame();
    }
}
class KeyFrame extends Frame {
    public KeyFrame() {
        setVisible(true);
        setBounds(100,100,200,300);
        setBackground(Color.red);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        addKeyListener(new MyKeyListener());
    }
    class MyKeyListener extends KeyAdapter{
        @Override
        public void keyPressed(KeyEvent e) {
            //获得按键的码
            int keyCode = e.getKeyCode();
            System.out.println(keyCode);
            if (keyCode == KeyEvent.VK_UP){
                System.out.println("你按了上键");
            }
        }
    }
}

3 Swing

3.1、窗口、面板

package com.dong.lesson3;import javax.swing.*;import java.awt.*;public class JFrameDemo {    public void init(){        //JFrame是一个顶级窗口        JFrame jFrame = new JFrame("这是我们的jFrame窗口");        jFrame.setBackground(Color.red);        jFrame.setBounds(100,100,200,200);        jFrame.setVisible(true);        //设置文字:        JLabel jLabel = new JLabel("欢迎欢迎,热泪欢迎");        jFrame.add(jLabel);        //让标签居中        jLabel.setHorizontalAlignment(SwingConstants.CENTER);        //获得一个容器,设置容器背景        Container contentPane = jFrame.getContentPane();        contentPane.setBackground(Color.cyan);        //关闭窗口事件        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);    }    public static void main(String[] args) {        new JFrameDemo().init();    }}

3.2、弹窗

JDialog,本身默认有关闭窗口

package com.dong.lesson3;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JDialogDemo {
    public JDialogDemo() {
        JFrame jf = new JFrame();
        jf.setVisible(true);
        jf.setSize(300,400);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container content = jf.getContentPane();
        content.setBackground(Color.cyan);
        //绝对布局
        content.setLayout(null);
        //设置要给弹窗口按钮
        JButton jButton = new JButton("蹦出弹窗");
        jButton.setBounds(30,30,220,200);
        jButton.setBackground(Color.blue);
        content.add(jButton);

        //监听Button事件
        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() {
        setVisible(true);
        setBackground(Color.BLUE);
        setBounds(100,100,200,300);

        Container container = this.getContentPane();
        container.setLayout(null);
        JLabel label = new JLabel("这是个弹窗");
        label.setBounds(20,20,80,80);
        container.add(label);
    }
}

3.3、标签

  • label
new JLabel("xxxx");
  • 图标1:Icon
package com.kang.lesson3;

import javax.swing.*;
import java.awt.*;

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

    //无参构造
    public IconDemo() {}
    //无参构造
    public IconDemo(int height,int width) {
        this.height = height;
        this.width = width;
    }

    public void init(){
        //生成一个图标
        IconDemo iconDemo = new IconDemo(15, 15);
        //图标放在标签的中间
        JLabel iconTest = new JLabel("IconTest", iconDemo, SwingConstants.CENTER);
        //标签放在容器里面
        Container contentPane = this.getContentPane();
        this.add(iconTest);

        setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

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

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

    @Override
    public int getIconHeight() {
        return this.height;
    }
}
  • 图标2: ImageIcon
package com.kang.lesson3;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class ImageIconDemo extends JFrame {

    public ImageIconDemo() {
        //获取图片的地址
        URL url = ImageIconDemo.class.getResource("tx.jpg");
        //生成一个标签
        JLabel jLabel = new JLabel("ImageIcon");
        //生成一个图片图标
        ImageIcon imageIcon = new ImageIcon(url);
        //把图片图标放在label中
        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();
    }
}

3.4、面板

  • JPanel
package com.kang.lesson4;

import javax.swing.*;
import java.awt.*;

public class JPanelDemo extends JFrame {

    public JPanelDemo() {
        Container contentPane = this.getContentPane();
        
        contentPane.setLayout(new GridLayout(2, 2,10,10));

        JPanel panel1 = new JPanel(new GridLayout(1, 3));
        JPanel panel2 = new JPanel(new GridLayout(2, 1));
        JPanel panel3 = new JPanel(new GridLayout(1, 2));
        JPanel panel4 = new JPanel(new GridLayout(2, 2));

        panel1.add(new JButton("1"));
        panel1.add(new JButton("2"));
        panel1.add(new JButton("3"));
        panel2.add(new JButton("4"));
        panel2.add(new JButton("5"));
        panel3.add(new JButton("6"));
        panel3.add(new JButton("7"));
        panel4.add(new JButton("8"));
        panel4.add(new JButton("9"));
        panel4.add(new JButton("10"));
        panel4.add(new JButton("11"));

        contentPane.add(panel1);
        contentPane.add(panel2);
        contentPane.add(panel3);
        contentPane.add(panel4);

        setVisible(true);
        setBounds(100, 100, 300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JPanelDemo();
    }
}
  • JScrollPanel(产生滚动窗口)
package com.kang.lesson4;

import javax.swing.*;
import java.awt.*;

public class JScrollDemo  extends JFrame {
    public JScrollDemo() {
        //获得容器
        Container contentPane = getContentPane();
        //生成文本域
        JTextArea area = new JTextArea();
        area.setText("花花你真美");
        //生成一个滚动面板容器
        JScrollPane panel = new JScrollPane(area);
        //大容器添加面板容器
        contentPane.add(panel);

        setVisible(true);
        setBounds(50, 50, 400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JScrollDemo();
    }
}

3.5、按钮

  • 图片按钮、
package com.kang.lesson4;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class JButtonDemo01 extends JFrame {
    public JButtonDemo01() {
        //获得容器
        Container contentPane = this.getContentPane();
        //将一个图片变成一个图标
        URL resource = JButtonDemo01.class.getResource("tx.jpg");
        Icon icon = new ImageIcon(resource);

        JButton button = new JButton();
        button.setIcon(icon);
        button.setToolTipText("1234567899");

        contentPane.add(button);

        setVisible(true);
        setBounds(100, 100, 400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

  • 单选框、
package com.kang.lesson4;

import javax.swing.*;
import java.awt.*;

public class JButtonDemo02 extends JFrame {

    public JButtonDemo02() {
        Container contentPane = this.getContentPane();

        //建立单选框按钮
        JRadioButton button1 = new JRadioButton("button1");
        JRadioButton button2 = new JRadioButton("button2");
        JRadioButton button3 = new JRadioButton("button3");
        //创建单选框条件
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(button1);
        buttonGroup.add(button2);
        buttonGroup.add(button3);
        //添加按键到容器中
        contentPane.add(button1,BorderLayout.NORTH);
        contentPane.add(button2,BorderLayout.CENTER);
        contentPane.add(button3,BorderLayout.SOUTH);

        setVisible(true);
        setBounds(100, 100, 400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonDemo02();
    }
}
  • 复选框
 package com.kang.lesson4;

import javax.swing.*;
import java.awt.*;

public class JButtonDemo02 extends JFrame {

    public JButtonDemo02() {
        Container contentPane = this.getContentPane();
		//创建复选框
        JCheckBox jCheckBox01 = new JCheckBox("jCheckBox01");
        JCheckBox jCheckBox02 = new JCheckBox("jCheckBox02");
        contentPane.add(jCheckBox01,BorderLayout.NORTH);
        contentPane.add(jCheckBox02,BorderLayout.SOUTH);

        setVisible(true);
        setBounds(100, 100, 400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

3.6、列表

  • 下拉框
package com.dong.lesson4;

import javax.swing.*;
import java.awt.*;

public class JComboboxDemo extends JFrame {
    public JComboboxDemo() {
        //获得一个容器
        Container contentPane = getContentPane();
        //生成一个下拉框模板
        JComboBox comboBox = new JComboBox();
        //再下拉框模板添加元素
        comboBox.addItem("null");
        comboBox.addItem("正在热映");
        comboBox.addItem("已经下架");
        comboBox.addItem("即将上映");

        //将下拉框放到容器中
        contentPane.add(comboBox);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100,100,300,300);
    }
    public static void main(String[] args) {
        new JComboboxDemo();
    }
}
  • 列表框
package com.dong.lesson4;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class JComboboxDemo2 extends JFrame {
    public JComboboxDemo2() {
        //获得一个容器
        Container contentPane = getContentPane();

//        //生成一个列表的内容:
//        String[] contents = {"1","2","3"};

        Vector contents = new Vector();

        //生成一个列表框
        JList jList = new JList(contents);

        contents.add("大麻子");
        contents.add("二狗子");
        contents.add("大黑蛋");
        contents.add("三毛");

        //将下拉框放到容器中
        contentPane.add(jList);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100,100,300,300);
    }
    public static void main(String[] args) {
        new JComboboxDemo2();
    }
}
  • 应用场景
    • 选择地区,或者一些单个选项
    • 列表,展示信息,一般是动态扩容

3.7、文本框

  • 文本框
package com.dong.lesson4;

import javax.swing.*;
import java.awt.*;

public class TestTextDemo01 extends JFrame {
    public TestTextDemo01() {

        Container contentPane = getContentPane();

        JTextField textField1 = new JTextField("hello",20);
        JTextField textField2 = new JTextField("world",20);

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

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100,100,300,300);
    }
    public static void main(String[] args) {
        new TestTextDemo01();
    }
}
  • 密码框
package com.dong.lesson4;

import javax.swing.*;
import java.awt.*;

public class TestTextDemo02 extends JFrame {
    public TestTextDemo02() {

        Container contentPane = getContentPane();

        JPasswordField passwordField = new JPasswordField();
        passwordField.setEchoChar("*");
        contentPane.add(passwordField);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100,100,300,300);
    }
    public static void main(String[] args) {
        new TestTextDemo02();
    }
}
  • 文本域
        //生成文本域
        JTextArea area = new JTextArea();
        area.setText("花花你真美");
        //生成一个滚动面板容器
        JScrollPane panel = new JScrollPane(area);
        //大容器添加面板容器
        contentPane.add(panel);

四、贪吃蛇

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

键盘监听

定时器 Timer

package com.kang.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.Random;

public class GamePanel extends JPanel implements KeyListener, ActionListener {
    //定义蛇的的数据结构
    int length;//蛇的长度
    int[] snakeX = new int[600];//蛇的x坐标空间
    int[] snakeY = new int[500];//蛇的Y坐标空间
    String fx; //头的方向
    //游戏的状态:开始 or 暂停
    Boolean isStart;
    //食物的坐标
    int foodX;
    int foodY;
    Random random =new Random();
    //游戏是否失败
    Boolean isFail;
    //游戏得分
    int score;

    //定时器 以毫秒为单位进行监听 1000ms = 1s
    Timer timer = new Timer(100,this);


    public GamePanel() {
        init();
        //获得键盘和焦点事件
        this.setFocusable(true);
        this.addKeyListener(this);
        timer.start();

    }

    public void init(){
        length =3;
        snakeX[0]=100;snakeY[0]=100;//脑袋坐标
        snakeX[1]=75;snakeY[1]=100;//第一个身体坐标
        snakeX[2]=50;snakeY[2]=100;//第二个身体坐标
        fx = "right";//头的初始化方向
        isStart = false;//游戏的初始化状态为暂停
        isFail = false;//游戏初始化状态,成功
        score = 0;//初始化得分为0;
        //初始化food位置
        foodX = 25 + 25*random.nextInt(34);
        foodY = 75 + 25*random.nextInt(24);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//刷新
        this.setBackground(Color.WHITE);
        g.drawRect(25, 75, 850, 600);

        g.setColor(Color.BLACK);
        g.setFont(new Font("微软雅黑", Font.BOLD, 50));
        g.drawString("欢迎来到贪吃蛇世界", 25, 60);

        //画得分
        g.setColor(Color.CYAN);
        g.setFont(new Font("微软雅黑", Font.BOLD, 15));
        g.drawString("你的得分:"+ score, 600, 30);
        g.drawString("你的长度:"+ length, 600, 60);

        if (fx.equals("right")){
            Data.right.paintIcon(this, g, snakeX[0],snakeY[0]);//头部向右
        }else if(fx.equals("left")){
            Data.left.paintIcon(this, g, snakeX[0],snakeY[0]);//头部向左
        }else if(fx.equals("up")){
            Data.up.paintIcon(this, g, snakeX[0],snakeY[0]);//头部向左
        }else if(fx.equals("down")){
            Data.down.paintIcon(this, g, snakeX[0],snakeY[0]);//头部向左
        }
//        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]);//初始化第二个身体
        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this, g, snakeX[i],snakeY[i]);//初始化第二个身体
        }
        //画出食物
        Data.body.paintIcon(this, g, foodX, foodY);

        //游戏的状态
        if (isStart == false){
            g.setColor(Color.BLACK);
            g.setFont(new Font("微软雅黑", Font.BOLD, 35));
            g.drawString("请按tab+空格键开始游戏", 300, 300);
        }
        if (isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑", Font.BOLD, 35));
            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){
            fx = "up";
        }else if (keyCode == KeyEvent.VK_DOWN){
            fx = "down";
        }else if (keyCode == KeyEvent.VK_LEFT){
            fx = "left";
        }else if (keyCode == KeyEvent.VK_RIGHT){
            fx = "right";
        }
    }

    //事件监听,-------通过固定事件来刷新,一秒十次
    @Override
    public void actionPerformed(ActionEvent e) {
        //→右移动
        if (isStart && isFail == false){
            //身体移动
            for (int i = length-1; i > 0; i--) {
                snakeX[i]=snakeX[i-1];//向前移动一点
                snakeY[i]=snakeY[i-1];//向前移动一点
            }
            //头部移动
            if (fx.equals("right")){
                snakeX[0]=snakeX[0]+25;
                if (snakeX[0]>850){ snakeX[0]=25; }
            } else if (fx.equals("left")){
                snakeX[0]=snakeX[0]-25;
                if (snakeX[0]<25){ snakeX[0]=850; }
            } else if (fx.equals("up")){
                snakeY[0]=snakeY[0]-25;
                if (snakeY[0]<75){ snakeY[0]=650; }
            } else if (fx.equals("down")){
                snakeY[0]=snakeY[0]+25;
                if (snakeY[0]>650){ snakeY[0]=75; }
            }

            //吃食物
            if (snakeX[0] == foodX && snakeY[0] ==foodY){
                length++;
                foodX = 25 + 25*random.nextInt(34);
                foodY = 75 + 25*random.nextInt(24);
                score += 1;
            }

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

    }
}
//==================================
package com.kang.snake;

import javax.swing.*;
import java.awt.*;

public class StartGames {
    //绘制面板,我们所有的东西都用这个来画
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setBounds(10, 10, 900, 720);
        frame.add(new GamePanel());
    }
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » GUI基础