GUI编程

GUI编程(图形化页面编程)

该如何在我们平时运用

组件:

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

1.简介

GUI的核心技术:Swing AWT

1、界面不美观

2、需要jre环境

学习原因、:

  • 写一些小工具
  • 了解MVC架构,了解监听

2.AWT

2.1、Awt介绍

1.包含很多类和接口

2.元素:窗口,按钮,文本框

3.java.awt

4.

/**
 * GUI的第一个界面
 */
public class TestFrame {
    public static void main(String[] args) {
        //创建窗口
        Frame frame = new Frame("我的第一个Java图像界面窗口");

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

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

        //设置背景颜色,三原色
        frame.setBackground(new Color(87, 157, 191));

        //设置弹出位置
        frame.setLocation(400,400);

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

但是删除不了

利用封装和继承创建多个窗口

public class TestFrame02 {
    public static void main(String[] args) {
    //展示多个窗口
        MyFrame myFrame = new MyFrame(100,100,200,200,Color.blue);
        MyFrame myFrame1 = new MyFrame(300,100,200,200,Color.red);
        MyFrame myFrame2 = new MyFrame(100,300,200,200,Color.green);
        MyFrame myFrame3 = new MyFrame(300,300,200,200,Color.yellow);
    }
}

class MyFrame extends Frame{
    static int id = 0;//弹窗计数器
    //设置构造方法
    public MyFrame(int x,int y,int h,int w,Color color){
        super("MyFrame"+id);
        setBackground(color);
        setBounds(x,y,h,w);
        setVisible(true);
    }
}

2.2面板Panel

解决了关闭问题!

package com.kuang.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(100,100,500,500);
        frame.setBackground(new Color(205, 72, 72));

        //设置panel的坐标
        panel.setBounds(300,300,300,300);
        panel.setBackground(new Color(1,100,10));

        frame.add(panel);

        frame.setVisible(true);
        //监听事件,监听窗口的关闭,System.exit(0);
        frame.addWindowListener(new WindowAdapter() {
            //窗口关闭需要进行的事件
            @Override
            public void windowClosing(WindowEvent e) {
                //适配器
                //结束程序
                System.out.println("结束程序");
                System.exit(0);
            }
        });
    }
}

2.3布局管理器

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

import java.awt.*;

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

        Button button1 = new Button("button");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");

        //设置为流式布局
        frame.setLayout(new FlowLayout(FlowLayout.LEFT ));

        frame.add(button1);
        frame.add(button2);
        frame.add(button3);

        frame.setSize(400,400);

        frame.setVisible(true);

    }
}

  • 东西南北中
public class TestBorderLayer {
    public static void main(String[] args) {
        Frame frame = new Frame("TestBorderLayer");

        Button east = new Button("East");
        Button west = new Button("West");
        Button north = new Button("North");
        Button south = new Button("South");
        Button center = new Button("Center");

        frame.add(east,BorderLayout.EAST);
        frame.add(west,BorderLayout.WEST);
        frame.add(north,BorderLayout.NORTH);
        frame.add(south,BorderLayout.SOUTH);
        frame.add(center,BorderLayout.CENTER);

        frame.setSize(500,500);
        frame.setVisible(true);
    }
}
  • 表格布局(Grid)
package com.kuang.lesson01;

import java.awt.*;

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

        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.setLayout(new GridLayout(2,3));

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

        frame.pack();//java函数!自动调整合适大小
       frame.setVisible(true);
    }
}

小测试

  • 先构思、整体布局(需要多少Panel,每个的布局)
package com.kuang.lesson01;

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

public class LessonTest {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setBounds(400,300,400,300);

        frame.setLayout(new GridLayout(2,1));
        //创建四个面板
        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("west-1"),BorderLayout.WEST);
        p1.add(new Button("east-1"),BorderLayout.EAST);

        p2.add(new Button("p2-1"));
        p2.add(new Button("p2-2"));

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

        p1.add(p2,BorderLayout.CENTER);
        p3.add(p4,BorderLayout.CENTER);
        p3.add(new Button("p3-west"),BorderLayout.WEST);
        p3.add(new Button("p3-east"),BorderLayout.EAST);
        frame.add(p1);
        frame.add(p3);

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

总结:

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

2.4事件监听

package com.kuang.lesson02;

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

public class TestActionEvent {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Button button = new Button("按钮");

        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);

        frame.add(button,BorderLayout.CENTER);
        frame.setVisible(true);
        frame.setSize(500,500);
        windowClose(frame);
    }

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

}
//事件监听
class MyActionListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("监听了事件");
    }
}

多个按钮共享一个事件

package com.kuang.lesson02;

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

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

        Button start = new Button("start");
        Button end = new Button("end");
        start.setActionCommand("新的值,用来设置getActionCommand,否则为默认标题");

        MyMonitor myMonitor = new MyMonitor();
        start.addActionListener(myMonitor);
        end.addActionListener(myMonitor);

        frame.add(start,BorderLayout.NORTH);
        frame.add(end,BorderLayout.SOUTH);


        frame.setSize(500,500);
        frame.pack();
        frame.setVisible(true);
    }
}
class MyMonitor implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
/*
        if(e.getActionCommand()=="start"){
            System.out.println("输出了:"+e.getActionCommand()+"实现了重用");
        }else if(e.getActionCommand()=="end"){
            System.out.println("点了end");
        }
*/
        System.out.println(e.getActionCommand());

    }
}

2.5、输入框 TextField 监听

package com.kuang.lesson02;

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);
        MyActionListener1 myActionListener1 = new MyActionListener1();
        //监听这个文本框输入的文字
        //按下enter就会触发这个输入框的事件
        textField.addActionListener(myActionListener1);
        //设置替换编码,实现隐蔽性
        textField.setEchoChar('*');

        setVisible(true);
        pack();
    }
}
class MyActionListener1 implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        TextField field = (TextField) e.getSource();
        System.out.println(field.getText());//获得输入的文本
        field.setText("");
    }
}

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

oop原则:组合>继承!

class A extends B{
    
}
class A{
    class B b;
}

目前代码

package com.kuang.lesson02;

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

public class TestCalc {
    public static void main(String[] args) {
        new MyCalculator();
    }
}
//计算器类
class MyCalculator extends Frame{
    public MyCalculator() {
        //三个文本框
        TextField num1 = new TextField(10);
        TextField num2 = new TextField(10);
        TextField num3 = new TextField(20);//设置文本框的最大字符

        //一个按钮
        Button button = new Button("=");
        button.addActionListener(new MyCalculatorListener(num1,num2,num3));
        //一个标签
        Label label = new Label("+");
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);

    }
}
//监听器类
class MyCalculatorListener implements ActionListener{

    //获取三个变量
    private TextField num1,num2,num3;
    public MyCalculatorListener(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.清空前两个框
        num1.setText("");
        num2.setText("");
    }
}

改为完全面向对象

package com.kuang.lesson02;

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

public class TestCalc {
    public static void main(String[] args) {
        new MyCalculator().loadFrame();
    }
}
//计算器类
class MyCalculator extends Frame{
    //属性
    TextField num1,num2,num3;
    //方法
    public void loadFrame() {
        //三个文本框
        //一个按钮
        //一个标签
        num1 = new TextField(10);
        num2 = new TextField(10);
        num3 = new TextField(20);//设置文本框的最大字符
        Button button = new Button("=");
        Label label = new Label("+");

        button.addActionListener(new MyCalculatorListener(this));

        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);
    }
}
//监听器类
class MyCalculatorListener implements ActionListener{

    //获取计算机这个对象,在一个类中组合另外一个类
    MyCalculator calculator = null;

    public MyCalculatorListener(MyCalculator myCalculator){
            this.calculator = myCalculator;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //1.获得加数和被加数
        //2.将两个数做加分后,保存在第三个框
        //3.清空前两个框
        int n1 = Integer.parseInt(calculator.num1.getText());
        int n2 = Integer.parseInt(calculator.num2.getText());

        calculator.num3.setText(""+(n1+n2));
        calculator.num1.setText("");
        calculator.num2.setText("");
    }
}
  • 内部类
    • 更好的包装
package com.kuang.lesson02;

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

public class TestCalc {
    public static void main(String[] args) {
        new MyCalculator().loadFrame();
    }
}
//计算器类
class MyCalculator extends Frame{
    //属性
    TextField num1,num2,num3;
    //方法
    public void loadFrame() {
        //三个文本框
        //一个按钮
        //一个标签
        num1 = new TextField(10);
        num2 = new TextField(10);
        num3 = new TextField(20);//设置文本框的最大字符
        Button button = new Button("=");
        Label label = new Label("+");

        button.addActionListener(new MyCalculatorListener());

        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);
    }
    //监听器类
    //内部类的最大的好处,就是可以畅通无阻的访问外部类的属性和方法
    class MyCalculatorListener implements ActionListener{

        //获取计算机这个对象,在一个类中组合另外一个类
        @Override
        public void actionPerformed(ActionEvent e) {

            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());

            num3.setText(""+(n1+n2));
            num1.setText("");
            num2.setText("");
        }
    }
}

2.7、画笔

package com.kuang.lesson03;

import java.awt.*;

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

class MyPaint extends Frame{
    public void LoadFrame(){
        setVisible(true);
        setBounds(200,200,800,600);
    }
    @Override
    public void paint(Graphics g) {
        //画笔需要颜色,可以画画
        g.setColor(Color.red);
        //g.drawOval(100,100,500,400);
        g.fillOval(100,100,500,300);
        //养成习惯将笔用完,将他还原为最初的颜色(黑色)
    }
}

2.8、鼠标监听

package com.kuang.lesson03;

import javax.xml.stream.FactoryConfigurationError;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
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);
        setVisible(true);
        setBounds(200,200,800,600);
        //存鼠标点击的点
        points = new ArrayList();
        setVisible(true);
        //鼠标监听器,正对这个窗口
        this.addMouseListener(new MyMouesListener());
    }

    @Override
    public void paint(Graphics g) {
        //画画监听鼠标的事件
        Iterator iterator = points.iterator();
        while(iterator.hasNext()){
            Point point = (Point)iterator.next();
            g.setColor(Color.red);
            g.fillOval(point.x,point.y,10,10);
        }
    }

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

    }

    private class MyMouesListener extends MouseAdapter {

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

2.9、窗口监听

package com.kuang.lesson03;

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

public class TestWindow {
    public static void main(String[] args) {
        new WindowFrame();
    }
}
class WindowFrame extends Frame{
    public WindowFrame()  {
        setVisible(true);
        setBackground(Color.BLUE);
        setBounds(100,100,400,400);
        //addWindowListener(new MyWindowsListener());
        //使用匿名内部类最好
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭了窗口");
                System.exit(0);
            }

            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("窗口已经被激活");
                WindowFrame source = (WindowFrame)e.getSource();
                source.setTitle("显示在上面的窗口哦");
            }
        });
    }

/*    class MyWindowsListener extends WindowAdapter{
        @Override
        public void windowClosing(WindowEvent e) {
            setVisible(false);
            System.exit(0);

        }
    }*/
}

2.10、键盘监听

package com.kuang.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(){
        setVisible(true);
        setBackground(Color.BLUE);
        setBounds(100,100,500,300);
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                //获得当前按下的是哪个键
                int keyCode = e.getKeyCode();
                System.out.println(keyCode);
                if(keyCode==KeyEvent.VK_UP){
                    System.out.println("你按下上键");
                }
            }
        });
    }
}

3.Swing

标签居中

package com.kuang.lesson03;

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

public class JFrameDemo {
    public void init(){
        JFrame jFrame = new JFrame("这是一个JFrame窗口");
        jFrame.setVisible(true);
        jFrame.setBackground(Color.BLUE);
        jFrame.setBounds(100,100,400,400);
        Container contentPane = jFrame.getContentPane();
        contentPane.setBackground(Color.BLUE);

        //设置文字
        JLabel label = new JLabel("欢迎来到我的世界");

        jFrame.add(label);
        //标签居中 设置水平对齐
        label.setHorizontalAlignment(SwingConstants.CENTER);
        //关闭事件
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

3.1、窗口

package com.kuang.lesson03;

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

public class JFrameDemo {
    public void init(){
        JFrame jFrame = new JFrame("这是一个JFrame窗口");
        jFrame.setVisible(true);
        jFrame.setBackground(Color.BLUE);
        jFrame.setBounds(100,100,400,400);
        Container contentPane = jFrame.getContentPane();
        contentPane.setBackground(Color.BLUE);

        //设置文字
        JLabel label = new JLabel("欢迎来到我的世界");

        jFrame.add(label);
        //标签居中 设置水平对齐
        label.setHorizontalAlignment(SwingConstants.CENTER);
        //关闭事件
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

3.2、弹窗

JDialog,用来被弹出,默认就有关闭事件!

package com.kuang.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.setBounds(200,200,600,400);
        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 MyDialog();
            }
        });

        container.add(button);
    }

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

//弹窗的窗口
class MyDialog extends JDialog{
    public MyDialog(){
        setVisible(true);
        setBounds(300,300,500,500);
        //setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //默认就有关闭事件
        Container container = this.getContentPane();
        container.setLayout(null);
        Label label = new Label("完成第一个弹窗");
        label.setVisible(true);
        label.setSize(100,100);
        container.add(label);

    }
}

3.3、标签

icon

package com.kuang.lesson04;

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

//图标,需要实现类 Frame继承
public class IconDemo extends JFrame implements Icon {

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

    public void init(){
        IconDemo iconDemo = new IconDemo(15,15);
        //图标放在标签上,也可以放在按钮上
        JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(label);

        setVisible(true);
        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,width,height);

    }

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

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

图片icon

package com.kuang.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("tp.png");

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

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

3.4、面板

Jpanel

package com.kuang.lesson05;

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

public class JPanelDemo extends JFrame {
    public JPanelDemo(){
        Container container = getContentPane();
        container.setLayout(new GridLayout(2,1,10,10));//设置间距

        JPanel panel1 = new JPanel(new GridLayout(1,3));
        JPanel panel2 = new JPanel(new GridLayout(2,3));
        JPanel panel3 = new JPanel(new GridLayout(1,1));
        panel1.add(new Button("1"));
        panel1.add(new Button("1"));
        panel1.add(new Button("1"));
        panel2.add(new Button("2"));
        panel2.add(new Button("2"));
        panel2.add(new Button("2"));
        panel2.add(new Button("2"));
        panel2.add(new Button("2"));
        panel2.add(new Button("2"));
        panel3.add(new Button("3"));

        container.add(panel1);
        container.add(panel2);
        container.add(panel3);

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

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

可以划动的文本框

package com.kuang.lesson05;

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

public class JScrollDemo extends JFrame {
    public JScrollDemo(){
        Container container = this.getContentPane();
        JTextArea textArea = new JTextArea(20, 50);//一行写20个,写50行
        textArea.setText("欢迎输入:");
        container.add(textArea);
        //Scroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);

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

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

3.5、按钮

图片按钮

package com.kuang.lesson05;

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

public class JButtonDemo01 extends JFrame {
    public JButtonDemo01() {
        Container container = getContentPane();
        //将图片变为一个图标
        URL resource = JButtonDemo01.class.getResource("tp1.png");
        Icon icon = new ImageIcon(resource);
        //把这个图标放在按钮上
        JButton button = new JButton();
        button.setIcon(icon);
        button.setToolTipText("这是一个图片按钮");

        container.add(button);

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

    public static void main(String[] args) {
        new JButtonDemo01();
    }
}
  • 单选按钮
package com.kuang.lesson05;

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

public class JButtonDemo02 extends JFrame {
    public JButtonDemo02() {
        Container container = getContentPane();
        //将图片变为一个图标
        URL resource = JButtonDemo01.class.getResource("tp1.png");
        Icon icon = new ImageIcon(resource);

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

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

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



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

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

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

public class JButtonDemo03 extends JFrame {
    public JButtonDemo03() {
        Container container = getContentPane();
        //将图片变为一个图标
        URL resource = JButtonDemo01.class.getResource("tp1.png");
        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);
        
        setVisible(true);
        setBounds(100,100,500,500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

3.6、列表

  • 下拉框
package com.kuang.lesson06;

import javafx.scene.control.ComboBox;

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

/**
 * 演示下拉框
 */
public class TestComboboxDemo01 extends JFrame {
    public TestComboboxDemo01() {
        Container container = getContentPane();

        JComboBox comboBox = new JComboBox();

        comboBox.addItem(null);
        comboBox.addItem("正在上映");
        comboBox.addItem("正在热映");
        comboBox.addItem("即将上映");
        comboBox.addItem("已下架");

        container.add(comboBox);

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

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

    }
}
  • 列表框
package com.kuang.lesson06;

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

public class TestComboboxDemo02 extends JFrame {
    public TestComboboxDemo02() {
        Container container = getContentPane();
        //生成列表的内容
        String[] contents = {"1","2","3","4","5"};
        //列表中需要放入的内容
        JList jList = new JList(contents);

        container.add(jList);
        
        setVisible(true);
        setBounds(100,100,350,500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

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

3.7、文本框

  • 文本框
package com.kuang.lesson06;

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

public class TestTextDemo01 extends JFrame {
    public TestTextDemo01() {
        Container container = getContentPane();

        JTextField textField = new JTextField("hello");
        JTextField textField2 = new JTextField("world");

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


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

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

    }
}
  • 密码框
package com.kuang.lesson06;

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

public class TestTextDemo02 extends JFrame {
    public TestTextDemo02() {
        Container container = getContentPane();

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

        container.add(passwordField);

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

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

    }
}
  • 文本域

    package com.kuang.lesson05;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class JScrollDemo extends JFrame {
        public JScrollDemo(){
            Container container = this.getContentPane();
            //文本域
            JTextArea textArea = new JTextArea(20, 50);//一行写20个,写50行
            textArea.setText("欢迎输入:");
            container.add(textArea);
            //Scroll面板
            JScrollPane scrollPane = new JScrollPane(textArea);
            container.add(scrollPane);
    
            setBounds(100,100,500,500);
            setVisible(true);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) {
            new JScrollDemo();
        }
    }
    

贪吃蛇

键盘监听

定时器Timer


StartGame类

package com.kuang.snake;

import javax.swing.*;

//游戏的主启动类
public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.setBounds(10,10,915,720);//原900,720
        frame.setResizable(false);//窗口大小不可变
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //正常的游戏界面就应该在面板上
        frame.add(new GamePanel());

        frame.setVisible(true);
    }
}

GamePanel类

 package com.kuang.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 = "R";

    //食物的坐标
     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);//获得键盘监听事件
    }

    public void init(){
        length = 3;
        snakeX[0] = 100;snakeY[0] = 100;//蛇头的坐标
        snakeX[1] = 75;snakeY[1] = 100;//第一个身体的坐标
        snakeX[2] = 50;snakeY[2] = 100;//第二个身体的坐标
        fx = "R";//初始方向向右
        timer.start();//游戏一开始定时器就启动
        //把食物随机分布在页面上
        foodx = 25 + 25*random.nextInt(34);
        foody = 75 + 25*random.nextInt(24);
        score=0;//成绩
    }


    //绘制面板,我们游戏中的所有东西,都是用这个画笔画的
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏作用
        //绘制静态面板
        this.setBackground(Color.WHITE);
        Data.header.paintIcon(this,g,25,11);//头部广告栏
        g.fillRect(25,75,850,600);

        //画积分
        g.setColor(Color.WHITE);
        g.setFont(new Font("微软雅黑",Font.BOLD,18));//设置字体
        g.drawString("长度: "+length,750,30);
        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){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑",Font.BOLD,50));
            g.drawString("游戏失败!按下空格重新开始",150,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";
         }

     }
     //事件监听--需要通过固定的事件来刷新,eg 一秒十次
     @Override
     public void actionPerformed(ActionEvent e) {
        if(isStart&&isFail==false){//如果游戏是开始状态,就让小蛇动起来

            //吃食物
            if(snakeX[0]==foodx&&snakeY[0]==foody){
                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];
            }

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

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


            repaint();//重画页面
        }
        timer.start();//定时器开启
     }

     @Override
     public void keyReleased(KeyEvent e) {

     }

     @Override
     public void keyTyped(KeyEvent e) {

     }


 }

Data类

package com.kuang.snake;

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

//数据中心
public class Data {
    //绝对路径
    //相对路径  / 相当于当前项目
    public static URL headerURL = Data.class.getResource("statics/header.png");
    public static ImageIcon header = new ImageIcon(headerURL);

    public static URL upURL = Data.class.getResource("statics/up.png");
    public static URL downURL = Data.class.getResource("statics/down.png");
    public static URL rightURL = Data.class.getResource("statics/right.png");
    public static URL leftURL = Data.class.getResource("statics/left.png");
    public static ImageIcon up = new ImageIcon(upURL);
    public static ImageIcon down = new ImageIcon(downURL);
    public static ImageIcon right = new ImageIcon(rightURL);
    public static ImageIcon left = new ImageIcon(leftURL);

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

}
posted @ 2021-10-07 17:15  肖寒*  阅读(29)  评论(0编辑  收藏  举报