首页 > 编程语言 >GUI编程

GUI编程

时间:2023-08-15 18:01:24浏览次数:33  
标签:java GUI 编程 add frame import new public

typora-root-url: ./

GUI编程

告诉大家该怎么学?

  • 这是什么
  • 它怎么玩?
  • 该如何去在我们平时运用?
  • class --可阅读

组件

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

1、简介

Gui的核心技术: Swing AWT

  1. 因为界面不美观
  2. 需要jre环境

为什么我们还要学习?

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

2、AWT

2.1、Awt 介绍

  1. 包含了很多类和接口 GUI
  2. 元素:窗口,按钮,文本框
  3. java.awt (jre\lib\rt.jar\awt)

微信截图_20230809162409

2.2 组件和容器

2.1、Frame

package com.jing.lesson01;


import java.awt.*;

//GUI第一个界面
public class TestFrame {

    public static void main(String[] args) {

        //Frame  JDK   源码
        Frame frame = new Frame("我的第一个图形界面");

        //需要设置可见性
        frame.setVisible(true);

        //设置窗口大小
        frame.setSize(400,400);

        //设置背景颜色  Color
        frame.setBackground(new Color(71, 141, 36));

        //弹出的初始位置
        frame.setLocation(200,200);

        //设置大小固定
        frame.setResizable(false);

    }

}

微信截图_20230809165205

问题:发现无法关闭,停止java程序

尝试封装

package com.jing.lesson01;

import java.awt.*;

public class TestFrame2 {
    public static void main(String[] args) {
      //展示多个窗口 new
        new MyFrame(100,100,200,200,Color.red);
        new MyFrame(300,100,200,200,Color.yellow);
        new MyFrame(100,300,200,200,Color.pink);
        new MyFrame(300,300,200,200,Color.magenta);



    }

}

class  MyFrame extends Frame{
    static int  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);
    }

}

微信截图_20230809170819

idea配置优化

2.2、面板Panel

解决了程序无法关闭

package com.jing.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(59, 152, 45));

        //panel坐标
        panel.setBounds(40,40,400,400);
        panel.setBackground(new Color(189, 31, 189, 255));

        //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);
            }
        });

    }

}

微信截图_20230809174239

2.3、布局

  • 流式布局
package com.jing.lesson01;

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

        frame.setSize(200,200);

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

        frame.setVisible(true);

    }
}

微信截图_20230810104337

  • 东西南北中
package com.jing.lesson01;

import com.sun.xml.internal.fastinfoset.algorithm.BuiltInEncodingAlgorithmState;

import java.awt.*;

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.setSize(200,200);
        frame.setVisible(true);

    }

}

微信截图_20230810103727

  • 表格布局
package com.jing.lesson01;

import java.awt.*;

public class TestGridlayout {

    public static void main(String[] args) {

        Frame frame = new Frame("TestBorderLayout");

        Button btn1 = new Button("btn1");
        Button btn2 = new Button("btn2");
        Button btn3 = new Button("btn3");
        Button btn4 = new Button("btn4");
        Button btn5 = new Button("btn5"); 
        Button btn6 = new Button("btn6");

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

        frame.add(btn1);
        frame.add(btn2);
        frame.add(btn3);
        frame.add(btn4);
        frame.add(btn5);
        frame.add(btn6);

        frame.pack();   //java函数
        frame.setVisible(true);

    }
}

微信截图_20230810103815

作业:

微信截图_20230810104207

思路:

微信截图_20230810110120

package com.jing.lesson01;

import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.awt.*;

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

        //总的frame
        Frame frame = new Frame("练习作业");
        frame.setLocation(400,300);
        frame.setSize(300,400);
        frame.setBackground(Color.BLACK);
        frame.setVisible(true);
        frame.setLayout(new GridLayout(2,1));

        //4个面板
        Panel p1 = new Panel(new BorderLayout());
        Panel p2 = new Panel(new GridLayout(2,1));
        Panel p3 = new Panel(new BorderLayout());
        Panel p4 = new Panel(new GridLayout(2,2));

        //上面
        p1.add(new Button("East-1"),BorderLayout.EAST);
        p1.add(new Button("West-1"),BorderLayout.WEST);
        p2.add(new Button("p2-btn-1"));
        p2.add(new Button("p2-btn-2"));
        p1.add(p2,BorderLayout.CENTER);

        //下面
        p3.add(new Button("East-2"),BorderLayout.EAST);
        p3.add(new Button("West-2"),BorderLayout.WEST);

        for (int i = 0; i < 4; i++) {
            p4.add(new Button("for-"+i));
        }

        p3.add(p4,BorderLayout.CENTER);

        //把面板放到控件中
        frame.add(p1);
        frame.add(p3);
      //监听关闭
      frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

微信截图_20230810113151

总结:

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

2.4、事件监听

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

package com.jing.lesson02;

import javax.swing.*;
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("btn");

        //因为,addActionListener需要一个ActionListener,我们需要构造一个ActionListener
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);
        //文本框

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

    //关闭窗体事件
    private static void windowsClose(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.jing.lesson02;

import sun.security.x509.FreshestCRLExtension;

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

public class TestActionEventwo {
    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);

    }
}

class   MyMonitor  implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("按钮被点击了:msg==>"+e.getActionCommand());

    }
}

2.5、输入框TextField 监听

package com.jing.lesson02;

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

public class TestText01 {
    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();
    }
}

class MyActionListener2 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField field =(TextField) e.getSource();  //获取一些资源,返回一个对象
        System.out.println(field.getText());//获得输入框的文本
        field.setText("");  //null   ""回车设置为空值
    }
}

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

oop原则 : 组合 大于继承

package com.jing.lesson02;

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

public class TestCalc {
    public static void main(String[] args) {
        new  Calculator();

    }
}

// 计算器类
class  Calculator extends Frame{
    public Calculator()  {
        //3个文本框
        TextField num1 = new TextField(10);
        TextField num2 = new TextField(10);
        TextField num3 = new TextField(20);

        //1个按钮
        Button button = new Button("=");
        button.addActionListener(new MyCalculatorListtener(num1,num2,num3));

        //1个标签
        Label label = new Label("+");

        //布局
        setLayout(new FlowLayout());

        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);
    }
}

//监听器类
class  MyCalculatorListtener implements ActionListener {

    //获取三个变量
    private TextField num1,num2,num3;
    public MyCalculatorListtener(TextField num1,TextField num2,TextField num3) {
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //1.获取加数和被加数
        int n1 = Integer.parseInt(num1.getText());
        int n2 = Integer.parseInt(num2.getText());

        //2.将这个值+法运算后,放到第三个框
        num3.setText(""+(n1+n2));

        //3.清楚前2个框
        num1.setText("");
        num2.setText("");
    }
}

完全改造为面向对象

package com.jing.lesson02;

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

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

// 计算器类
class  Calculator extends Frame{

    //属性
    TextField num1,num2,num3;

    //方法
    public void loadFrame()  {
        //3个文本框
         num1 = new TextField(10);
         num2 = new TextField(10);
         num3 = new TextField(20);
        //1个标签
        Label label = new Label("+");
        //1个按钮
        Button button = new Button("=");
        //监听器
        button.addActionListener(new MyCalculatorListtener(this));

        //布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }
}

//监听器类
class  MyCalculatorListtener implements ActionListener {

    //获取计算器这个对象,在一个类中组合另外一个类
    Calculator  calculator = null;
    public MyCalculatorListtener(Calculator calculator) {
        this.calculator =calculator;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //1.获取加数和被加数
        int n1 = Integer.parseInt(calculator.num1.getText());
        int n2 = Integer.parseInt(calculator.num2.getText());

        //2.将这个值+法运算后,放到第三个框
        calculator.num3.setText(""+(n1+n2));

        //3.清楚前2个框
        calculator.num1.setText("");
        calculator.num2.setText("");
    }
}

内部类,更好的包装

package com.jing.lesson02;

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

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

// 计算器类
class  Calculator extends Frame{
    //属性
    TextField num1,num2,num3;
    //方法
    public void loadFrame()  {
        //3个文本框
         num1 = new TextField(10);
         num2 = new TextField(10);
         num3 = new TextField(20);
        //1个标签
        Label label = new Label("+");
        //1个按钮
        Button button = new Button("=");
        //监听器
        button.addActionListener(new MyCalculatorListener());

        //布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }

private  class  MyCalculatorListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            //1.获取加数和被加数
            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());

            //2.将这个值+法运算后,放到第三个框
            num3.setText(""+(n1+n2));

            //3.清楚前2个框
            num1.setText("");
            num2.setText("");
        }
    }
}


2.7 画笔

package com.jing.lesson03;

import java.awt.*;

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

class MyPaint  extends Frame{

    public void loadFrame(){
        setBounds(100,100,600,600);
        setVisible(true);
    }

    //画笔
    @Override
    public void paint(Graphics g) {
        //画笔,需要有颜色,画笔可以画画
        g.setColor(Color.magenta);
        g.drawOval(100,100,100,200);
        g.fillOval(100,100,100,100);

        g.setColor(Color.green);
        g.fillRect(150,200,200,200);

        //养成习惯,画笔用完,将还原为最初的颜色
    }
}


2.8 鼠标监听

package com.jing.lesson03;

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

    @Override
    public void paint(Graphics g) {
        //画画,监听鼠标的事件

        Iterator iterator = points.iterator();
        while (iterator.hasNext()){
            Point paint = (Point) iterator.next();
            g.setColor(Color.green);
            g.fillOval(paint.x,paint.y,10,10);
        }
    }

    //添加一个点到界面上
    public void addPaint(Point point){

        points.add(point);
    }

    private class MyMouseListener  extends MouseAdapter{
        //鼠标  按下,弹起 ,按住不放

        @Override
        public void mouseClicked(MouseEvent e) {
            MyFrame myframe = (MyFrame) e.getSource();
            //这个我们点击的时候,就会在界面上产生一个点! 画
            //这个点就是鼠标的点
            myframe.addPaint(new Point(e.getX(),e.getY()));

            //每次点击鼠标都要重新画一次
            myframe.repaint();//刷新
        }
    }
}

2.9 窗口监听

package com.jing.lesson03;

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

public class TestWindows {
    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 MyWindowListener());
//        this.addWindowListener(new WindowAdapter() {
//            @Override//匿名内部类
//            public void windowClosing(WindowEvent e) {
//                System.out.println("你点击的x");
//            }
//        });

    }


    class MyWindowListener extends WindowAdapter {

        @Override
        public void windowClosing(WindowEvent e) {
            setVisible(false); //隐藏窗口,通过按钮,隐藏当前窗口
            System.exit(0);  //正常退出
        }
    }
}

内部类版

package com.jing.lesson03;

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

public class TestWindows {
    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 MyWindowListener());
        this.addWindowListener(new WindowAdapter() {
            @Override//匿名内部类
            public void windowClosing(WindowEvent e) {
                System.out.println("你点击的x");
                System.exit(0);
            }
        });
    }
}

2.10 键盘监听

package com.jing.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()  {
    super();
    setBounds(1,2,300,400);
    setVisible(true);

    this.addKeyListener(new KeyAdapter() {
        //键盘按下
        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            System.out.println(keyCode);//不需要去记录这个数值,直接使用静态属性VK_XXX
            if (keyCode == KeyEvent.VK_UP){
                System.out.println("你按下了上键");
            }
        }
    });

    }
}

3、Swing

3.1 窗口、面板

标签居中

package com.jing.lesson04;

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

public class JFrameDemo {
    //init()  初始化
    public void init(){
        //顶级窗口
        JFrame jf = new JFrame("z这是一个JFrame窗口");
        jf.setVisible(true);
        jf.setBounds(100,100,200,300);
        jf.setBackground(Color.pink);

        //设置文字JLable
        JLabel label = new JLabel("欢迎光临");

        jf.add(label);

        //让文本标签居中
        label.setHorizontalAlignment(SwingConstants.CENTER);

        //容器实例化
        Container contentPane = jf.getContentPane();
        contentPane.setBackground(Color.pink);

        //关闭事件
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        //建立一个窗口
        new   JFrameDemo().init();

    }
}

3.2 弹窗

package com.jing.lesson04;

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

//主窗口
public class DialogDemo extends JFrame {


    public DialogDemo() {
        this.setVisible(true);
        this.setSize(700,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //JFrame  放东西,需要容器
        Container container = this.getContentPane();
        container.setLayout(null);

        //按钮
        JButton button = new JButton("点击弹出一个对话框");//创建弹窗
        button.setBounds(30,30,200,50);

        //点击这个按钮的时候,弹出一个弹窗,监听事件
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //弹窗
                new MyDialogDemo();

            }
        });
        //添加按钮
        container.add(button);
    }

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

//弹窗的窗口
class  MyDialogDemo extends JDialog{
    public MyDialogDemo() {
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        container.setLayout(null);
        
        container.add(new Label("带你学java"));
    }
}

3.3 标签

图标

package com.jing.lesson04;

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

//图标,需要实现类,Frame继承
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 void init(){
        IconDemo iconDemo = new IconDemo(15, 15);
        //图标放在标签,也可以放在按钮上
        JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);

        Container container = getContentPane();
        container.add(label);

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

    }


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

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

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

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

图片

package com.jing.lesson04;

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

public class ImageIconDemo extends JFrame {

    public ImageIconDemo() {
        //获取图片的地址
        JLabel label = new JLabel("ImageIcon");
        URL url = ImageIconDemo.class.getResource("tx.jpg");

        ImageIcon imageIcon = new ImageIcon(url);
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(label);

        setVisible(true);

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        setBounds(100,100,300,400);
    }

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

3.4 面板

JPanel

package com.jing.lesson05;

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

public class JPanelDemo extends JFrame {
    public JPanelDemo() {
        Container container = this.getContentPane();

        container.setLayout(new GridLayout(2,1,10,10));//后面的参数是间距

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

        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        panel2.add(new JButton("2"));
        panel2.add(new JButton("2"));
        panel3.add(new JButton("3"));
        panel3.add(new JButton("3"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));

        container.add(panel1);
        container.add(panel2);
        container.add(panel3);
        container.add(panel4);
        
        this.setVisible(true);
        this.setSize(500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

JScroll 滚动条

package com.jing.lesson05;

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

public class JScrollDemo extends JFrame {
    public JScrollDemo() {
        Container container = this.getContentPane();

        //文本域
        JTextArea textArea = new JTextArea(20, 50);
        textArea.setText("欢迎来到Java世界");

        container.add(textArea);

        //Scroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);

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


    }

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

3.5 按钮

图片按钮

package com.jing.lesson05;

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

public class JButtonDemo01 extends JFrame {
    public JButtonDemo01()  {
        Container container = this.getContentPane();
        //将一个图片编程图标
        URL resource = JButtonDemo01.class.getResource("tx.jpg");
        Icon icon = new ImageIcon(resource);

        //把这个图标放到按钮上
        JButton button = new JButton();
        button.setIcon(icon);
        button.setToolTipText("图片按钮");

        //add
        container.add(button);

        this.setVisible(true);
        this.setSize(500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

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

  • 单选按钮
package com.jing.lesson05;

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

public class JButtonDemo02 extends JFrame {
    public JButtonDemo02()  {
        Container container = this.getContentPane();
        //将一个图片编程图标
        URL resource = JButtonDemo02.class.getResource("tx.jpg");
        Icon icon = new ImageIcon(resource);

        //单选框
        JRadioButton radioButton1 = new JRadioButton("JRadioButton01");
        JRadioButton radioButton2 = new JRadioButton("JRadioButton02");
        JRadioButton radioButton3 = new JRadioButton("JRadioButton03");

        //由于单选框只能选择一个,分组,一个组里只能选择一个
        ButtonGroup group = new ButtonGroup();
        group.add(radioButton1);
        group.add(radioButton2);
        group.add(radioButton3);

        container.add(radioButton1,BorderLayout.CENTER);
        container.add(radioButton2,BorderLayout.NORTH);
        container.add(radioButton3,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setSize(500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {
        new JButtonDemo02();
    }
}
  • 复选按钮
package com.jing.lesson05;

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

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

        //多选框
        JCheckBox checkBox01 = new JCheckBox("checkBox01");
        JCheckBox checkBox02 = new JCheckBox("checkBox02");

        container.add(checkBox01,BorderLayout.NORTH);
        container.add(checkBox02,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setSize(500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {
        new JButtonDemo03();
    }
}
  • 下拉框
package com.jing.lesson06;

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

public class TestComboDemo01 extends JFrame {
    public TestComboDemo01()  {

        Container container = this.getContentPane();

        JComboBox status = new JComboBox();
        
        status.addItem(null);
        status.addItem("正在热映");
        status.addItem("已下架");
        status.addItem("即将上映");
        
        container.add(status);
        
        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

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

3.6 列表框

package com.jing.lesson06;

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

public class TestComboDemo02 extends JFrame {
    public TestComboDemo02()  {

        Container container = this.getContentPane();

        //生成列表的内容
        String[]  contents = {"1","2","3"};
        //列表中需要放入内容
        JList jList = new JList(contents);

        container.add(jList);

        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

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

应用场景

选择地区,或者一些单个选项

列表 展示信息,一般是动态扩容

3.7 文本框

  • 文本框
package com.jing.lesson06;

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

public class TestTextDemo01 extends JFrame {
    public TestTextDemo01()  {

        Container container = this.getContentPane();

        //文本框
        JTextField textField = new JTextField("hello");
        JTextField textField2 = new JTextField("world");

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

        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {

        new TestTextDemo01();
    }
}

  • 密码框
package com.jing.lesson06;

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

public class TestTextDemo02 extends JFrame {
    public TestTextDemo02()  {

        Container container = this.getContentPane();

        //密码框
        JPasswordField passwordField = new JPasswordField();
        passwordField.setEchoChar('*');

        container.add(passwordField);

        this.setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {

        new TestTextDemo02();
    }
}

  • 文本域
package com.jing.lesson05;

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

public class JScrollDemo extends JFrame {
    public JScrollDemo() {
        Container container = this.getContentPane();

        //文本域
        JTextArea textArea = new JTextArea(20, 50);
        textArea.setText("欢迎来到Java世界");

        container.add(textArea);

        //Scroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);

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


    }

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

HTML + Servlet

MVC

C/S B/S

贪吃蛇

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

键盘监听

定时器Timer


  1. 定义数据

  2. 画上去

  3. 监听事件

    键盘,事件

startgame

package com.jing.snake;

import javax.swing.*;

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);
    }
}

GamePanel

package com.jing.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坐标25*25
    int[] snakeY = new int[500]; //蛇的y坐标25*25
    String fx;
    //食物的坐标
    int  foodx ;
    int  foody;
    Random  random = new Random();
    int  score ;//成绩

    //游戏当前的状态,开始,停止
    boolean  isStart = false;   //默认是不开始
    boolean  isfail = false;    //游戏失败状态


    //定时器
    Timer timer =  new Timer(100,this);  //100毫秒执行一次


    //构造器
    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 ="R";//初始方向向右


        foodx = 25 + 25*random.nextInt(35);
        foody = 75 + 25*random.nextInt(55);

        score = 0;

    }


    //绘制面板,我们的游戏中所有东西,都用这个画笔来画
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏
        //绘制静态的面板
        this.setBackground(Color.WHITE);

        Data.header.paintIcon(this,g,25,11);  //头部广告栏画上去
        g.fillRect(25,75,850,600); //默认的游戏界面

        //画积分
        g.setColor(Color.white);
        setFont(new Font("苹方-简",Font.BOLD,18));
        g.drawString("长度"+length,750,35);
        g.drawString("分数"+score,750,50);

        //画食物
        Data.food.paintIcon(this,g,foodx,foody);

        //把小蛇画上去
        if (fx.equals("R")){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); //蛇头初始化向右
        }  else if (fx.equals("L")){
            Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }  else if (fx.equals("U")){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }  else if (fx.equals("D")){
            Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }

        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }



        //游戏状态
        if (isStart==false){
            g.setColor(Color.WHITE);
            g.setFont(new Font("苹方-简",Font.BOLD,40));//设置字体
            g.drawString("按下空格开始游戏",300,300);
        }

        if (isfail==true){
            g.setColor(Color.red);
            g.setFont(new Font("苹方-简",Font.BOLD,40));//设置字体
            g.drawString("失败,按下空格重新开始",300,300);
        }

    }


    //键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();//获取键盘按键是哪个

        if (keyCode == KeyEvent.VK_SPACE){   //按下空格键
            if (isfail){
                isfail = false;
                init();
            }else {
                isStart = !isStart; //取反
            }
            repaint();
        }

        //小蛇移动
        if(keyCode==KeyEvent.VK_UP){
            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 == false){ //如果游戏是开始状态,就让小蛇动起来

            //吃食物
            if (snakeX[0] == foodx && snakeY[0] == foody){
                //长度加1
                length++;
                //分数+10
                score = score +10;
                //再次随机食物
                foodx = 25 + 25*random.nextInt(34);
                foody = 75 + 25*random.nextInt(24);

            }
            //移动
            for (int i = length-1; i >0 ; i--) { //后一节移动前一节位置
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }

            //走向
            if(fx.equals("R")){
                snakeX[0] = snakeX[0]+25;
                if (snakeX[0]>850){snakeX[0] = 25;}  //边界判断
            }else if(fx.equals("L")){
                snakeX[0] = snakeX[0]-25;
                if (snakeX[0]<25){snakeX[0] = 850;}
            }else if(fx.equals("U")) {
                snakeY[0] = snakeY[0]-25;
                if (snakeY[0] < 75) { snakeY[0] = 650;}
            }else if(fx.equals("D")) {
                snakeY[0] = snakeY[0]+25;
                if (snakeY[0] > 650) { snakeY[0] = 75;}
            }

            //失败判定,撞到自己
            for (int i = 1; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){
                    isfail = true;
                }

            }
            repaint();  //重画

        }
        timer.start();  //定时器开启

    }


    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }


}




Data

package com.jing.snake;

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

//数据中心
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  upURL = Data.class.getResource("/statics/up.png");
    public static URL  downURL = Data.class.getResource("/statics/down.png");
    public static URL  leftURL = Data.class.getResource("/statics/left.png");
    public static URL  rightURL = Data.class.getResource("/statics/right.png");
    public static URL  bodyURL = Data.class.getResource("/statics/body.png");
    public static URL  foodURL = Data.class.getResource("/statics/food.png");
    public static ImageIcon up = new ImageIcon(upURL);
    public static ImageIcon down = new ImageIcon(downURL);
    public static ImageIcon left = new ImageIcon(leftURL);
    public static ImageIcon right = new ImageIcon(rightURL);
    public static ImageIcon body = new ImageIcon(bodyURL);
    public static ImageIcon food = new ImageIcon(foodURL);


}

微信截图_20230814111255

标签:java,GUI,编程,add,frame,import,new,public
From: https://www.cnblogs.com/jingjingn/p/17632020.html

相关文章

  • 让 GPT-4 来修复 Golang “数据竞争”问题(续) - 每天5分钟玩转 GPT 编程系列(7)
    目录1.我以为2.阴魂不散的“数据竞争”问题3.老规矩,关门放GPT-43.1复现问题3.2让GPT-4写一个单元测试3.3修复Wait()中的逻辑漏洞4.总结1.我以为我以为GoPool这个项目会昙花一现,从此在GitHub上封尘。关于GoPool项目诞生的故事:《仅三天,我用GPT-4生成了性能......
  • 《Java编程思想第四版》学习笔记13
    //:Frog.java//TestingfinalizewithinheritanceclassDoBaseFinalization{publicstaticbooleanflag=false;}classCharacteristic{Strings;Characteristic(Stringc){s=c;out.println("Creating......
  • Java并发编程:实现高效、线程安全的多线程应用
    Java并发编程是开发高效、可扩展的多线程应用的关键。合理地利用多线程可以提高程序的性能和响应性,但同时也会引入线程安全的问题。本文将介绍Java并发编程的关键技巧,帮助读者实现高效、线程安全的多线程应用。 线程安全的数据结构和类Java提供了许多线程安全的数据结构和类,如Co......
  • javascript 高级编程系列 - 定型数组
    定型数组是一种用于处理数值类型数据的专用数组,最早是在webGL中使用的,WebGL是OpenGLES2.0的移植版,在web页面中通过<canvas>元素来呈现它。定型数组也被一同移植而来,其可为javascript提供快速的按位运算。在javascript中,数字是以64位浮点格式储存的,并按需转换为32位整数,所以算术......
  • javascript 高级编程系列 - 数组
    1.Array.of创建数组constitems=Array.of(1,2,3);console.log(items);2.Array.from将可迭代对象或类数组对象转换为数组constitems=Array.from('123');console.log(items);3.Array.prototype.find&Array.prototype.findeIndex在数组中查找符合条件的第一......
  • 什么是切面编程?
    在探讨SpringFramework框架时,一个重要而深奥的主题是切面编程(Aspect-OrientedProgramming,AOP)。在本篇博客中,我们将深入分析AOP的概念、原理以及在Spring中的实际应用。切面编程是一种编程范式,旨在将横切关注点(Cross-CuttingConcerns)与主要业务逻辑分离开来。横切关注点是......
  • 异步编程的重要性
    在传统的同步编程中,代码按照顺序执行,当某个操作阻塞时,整个程序可能会受到影响。异步编程通过将任务分解为独立的异步操作,可以提高系统的并发性和响应性。异步编程的原则异步编程的核心原则包括:非阻塞操作:异步操作不会阻塞主线程,使得程序可以继续执行其他任务。回调机制:通过回调函数......
  • () {}用法,Linux shell脚本编程时bad substitution解决办法
     首先,我们要理解badsubstitution的字面意思,它的字面意思是“替换错误”的意思。这种错误的原因呢,通常是我们编写脚本时“{}”和“()”错误使用导致的。比如应该用“()”时,我们用成了“{}”;应该用“()”时,用成了“{}”。 那么如何区分什么时候用什么类型的括号呢?${}中,大括号里......
  • socket编程原理
    socket编程原理1问题的引入UNIX系统的I/O命令集,是从Maltics和早期系统中的命令演变出来的,其模式为打开一读/写一关闭(open-write-read-close)。在一个用户进程进行I/O操作时,它首先调用“打开”获得对指定文件或设备的使用权,并返回称为文件描述符的整型数,......
  • 学习go语言编程之网络编程
    Socket编程Golang语言标准库对Socket编程进行了抽象,无论使用什么协议建立什么形式的连接,都只需要调用net.Dial()即可。Dial()函数Dial()函数的原型如下:funcDial(network,addressstring)(Conn,error)参数含义如下:network:网络协议名字,如:tcp,udp等Dial()函数支持的网络......