GUI编程

GUI编程

组件

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

GUI的核心技术:Swing AWT
  1. 因为界面不美观
  2. 需要jre环境
为什么我们要学习
  1. 可以写出自己心中想要的一些小工具。
  2. 工作的时候,也可能维护到swing界面。
  3. 了解MVC框架,了解监听。
2,AWT

2.1,Awt介绍
  1. 包含很多类和接口!GUI!

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

  3. Java.awt

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UCNNh3Oq-1661227529845)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220820144343515.png)]

2.2,组件和容器
  1. Frame

     public static void main(String[] args) {
            //Frame,JDK, 看源码!
            Frame frame = new Frame("我的第一个Java图像界面窗口");
            //需要设置可见性
            frame.setVisible(true);
            //设置窗口大小
            frame.setSize(400,400);
            //设置背景颜色
            frame.setBackground(new Color(85,150,68));
            //弹出的初始位置
            frame.setLocation(200,200);
            //设置大小固定
            frame.setResizable(false);
        }
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BVX1ISNH-1661227529846)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220820144808242.png)]

问题:窗口关闭不掉,停止java程序!

多窗口界面

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

    }
}
class MyFrame extends Frame{
    //多个窗口,设置计数器
    public 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);
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ldOYO6EI-1661227529847)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220820150600333.png)]

  1. 面板Panel

    解决窗口关闭问题

    //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(161, 85,35));
            //设置Panel坐标,相对与frame
            panel.setBounds(50,50,400,400);
            panel.setBackground(new Color(3, 193, 139));
            //将Panel放到Frame中
            frame.add(panel);
            //需要设置可见性
            frame.setVisible(true);
            //监听窗口关闭事件 System.exit(0)
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    //结束程序
                    System.exit(0);
                }
            });
    
        }
    }
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jhIQNVdr-1661227529847)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220820154326888.png)]

2.3,布局管理器
  • 流式布局
public class TestFlowLayout {
    public static void main(String[] args) {
        Frame frame = new Frame();
        //组件-按钮
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        //设置为流失布局
        //frame.setLayout(new FlowLayout());
        //frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
        frame.setSize(200,200);
        //把按钮添加上去
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.setVisible(true);
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Lol55iCa-1661227529848)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220820180526317.png)]

  • 东西南北中
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);


    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zGgvZSQh-1661227529849)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220820181545749.png)]

  • 表格布局
public class TestGridLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("TestGridLayout");

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

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

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

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

    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-irdslDaK-1661227529849)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220820182402566.png)]

public class Demo {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setVisible(true);
        frame.setSize(400,300);
        frame.setLocation(300,400);
        frame.setBackground(Color.black);
        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("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);
            }
        });

    }
}

​ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-p6f912XV-1661227529849)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220820222124479.png)]

总结:

  1. Frame是一个顶级窗口

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

  3. 布局管理器

    1.流式

    2.东南西北中

    3.表格

  4. 大小,定位,背景颜色,可见性,监听!

2.4,事件监听

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

public class TestActionEvent {
    public static void main(String[] args) {
        //点击按钮,触发事件
        Frame frame = new Frame();
        Button button = new Button();
        //因为,addActionListener()需要一个ActionListener,所以我们需要构造一个ActionListener
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);

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

        //关闭窗口
        windowClose(frame);
        frame.setVisible(true);


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

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("aaa");
    }
}

多个按钮,共享一个事件

public class TestActionTwo {
    public static void main(String[] args) {
        //两个按钮,实现同一个监听
        Frame frame = new Frame("开始-停止");
        Button start = new Button("start");
        Button stop = new Button("stop");
        //可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值!
        stop.setActionCommand("button-stop");
        MyMonitor myMonitor = new MyMonitor();
        start.addActionListener(myMonitor);
        stop.addActionListener(myMonitor);

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

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


    }
}
class MyMonitor implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("按钮被点击了:"+e.getActionCommand());
    }
}public class TestActionTwo {
    public static void main(String[] args) {
        //两个按钮,实现同一个监听
        Frame frame = new Frame("开始-停止");
        Button start = new Button("start");
        Button stop = new Button("stop");

        stop.setActionCommand("button-stop");
        MyMonitor myMonitor = new MyMonitor();
        start.addActionListener(myMonitor);
        stop.addActionListener(myMonitor);

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

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


    }
}
class MyMonitor implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("按钮被点击了:"+e.getActionCommand());
    }
}
2.5,输入框事件监听
public class TestText {
    public static void main(String[] args) {
        new MyFrame();
    }
}
class MyFrame extends Frame{
    public MyFrame(){
        TextField textField = new TextField();
        add(textField);

        //监听这个文本框输入的文字
        MyActionListener myActionListener = new MyActionListener();
        //按下enter,就会出发这个输入框的事件
        textField.addActionListener(myActionListener);

        //设置替换编码
        textField.setEchoChar('*');

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

    }
}
class MyActionListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        //获得资源,返回对象
        TextField field = (TextField) e.getSource();
        System.out.println(field.getText());
        field.setText("");
    }
}
2.6,简易计算机,组合+内部类

目前代码

//简易计算器
public class TestCalculator {
    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 MyCalculatorListener(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 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("");
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Glvov55G-1661227529850)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220821162728173.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uMoeg8Dz-1661227529851)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220821162744478.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vurk11Si-1661227529851)(C:\Users\JunGao\AppData\Roaming\Typora\typora-user-images\image-20220821162807144.png)]

面向对象写法

//简易计算器
public class TestCalculator {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        calculator.loadFrame();
    }
}
class Calculator extends Frame{
    TextField num1,num2,num3;
    public void loadFrame(){
        num1 = new TextField(10);//字符数
        num2 = new TextField(10);
        num3 = new TextField(20);
        Button button = new Button("=");
        button.addActionListener(new MyCalculatorListener(this));
        Label label = new Label("+");
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
    }
}
class MyCalculatorListener implements ActionListener {
    Calculator calculator = null;
    public MyCalculatorListener(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.清空前两个框
        calculator.num1.setText("");
        calculator.num2.setText("");
    }
}

内部类:更好的包装

//简易计算器
public class TestCalculator {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        calculator.loadFrame();
    }
}
class Calculator extends Frame{
    TextField num1,num2,num3;
    public void loadFrame(){
        num1 = new TextField(10);
        num2 = new TextField(10);
        num3 = new TextField(20);
        Button button = new Button("=");
        button.addActionListener(new MyCalculatorListener());
        Label label = new Label("+");
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        pack();
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    private 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,画笔
public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();

    }
}
class MyPaint extends Frame{
    public void loadFrame(){
        setBounds(200,200,600,500);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    //画笔
    @Override
    public void paint(Graphics g) {
        g.setColor(Color.red);
        //g.drawOval(100,100,100,100);
        g.fillOval(100,100,100,100);
        g.setColor(Color.black);
        g.fillRect(150,200,200,200);
    }
}
2.8,鼠标监听事件,模拟画图工具
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());
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    @Override
    public void paint(Graphics g) {
        //监听鼠标事件
        Iterator iterator = points.iterator();
        while (iterator.hasNext()){
            Point point = (Point) iterator.next();
            g.setColor(Color.BLUE);
            g.fillOval(point.x,point.y,10,10);
        }
    }
    //添加一个点到界面上
    public void addPoint(Point point){
        points.add(point);
    }
    //适配器模式
    private class MyMouseListener 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,窗口监听事件
public class TestWindow {
    public static void main(String[] args) {
        new WindowFrame();
    }
}
class WindowFrame extends Frame {
    public WindowFrame(){
        setBackground(Color.blue);
        setBounds(100,100,200,200);
        setVisible(true);
        this.addWindowListener(new WindowAdapter() {
            //关闭窗口
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
            //激活窗口
            @Override
            public void windowActivated(WindowEvent e) {
                WindowFrame window = (WindowFrame) e.getSource();
                window.setTitle("被激活了");
            }
        });
    }
}
2.10,键盘监听事件
public class TestKeyListener {
    public static void main(String[] args) {
        new KeyFrame();
    }
}
class KeyFrame extends Frame {
    public KeyFrame(){
        setBounds(1,2,300,400);
        setVisible(true);
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                //获取案件code
                int keyCode = e.getKeyCode();
                if(keyCode == KeyEvent.VK_UP){
                    System.out.println("上键");
                }
            }
        });
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
3,Swing

3.1,窗口,面板,标签居中
public class TestJFrame {
    public static void main(String[] args) {
        new MyJFrame().init();
    }
}

class MyJFrame extends JFrame {
    public void init() {
        setBounds(100, 100, 300, 300);
        setVisible(true);
        JLabel label = new JLabel("==========");
        this.add(label);
        //设置标签居中
        label.setHorizontalAlignment(SwingConstants.CENTER);
        //获取容器
        Container container = this.getContentPane();
        container.setBackground(Color.gray);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
3.2,弹窗
public class TestDiaLog {
    public static void main(String[] args) {
        new MyJFrame().init();
    }
}

class MyJFrame extends JFrame {
    public void init() {
        setSize(700, 500);
        setVisible(true);
        //获取容器
        Container container = this.getContentPane();
        //绝对布局
        container.setLayout(null);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        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);
    }
}

//弹窗的窗口
class MyDiaLog extends JDialog {
    public MyDiaLog() {
        this.setVisible(true);
        this.setBounds(100, 100, 500, 500);
        Container container = this.getContentPane();
        container.setLayout(null);
        container.add(new Label("弹窗"));
    }
}
3.3,标签

图标ICON

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

class MyIcon extends JFrame implements Icon {
    private int width;
    private int height;

    public MyIcon() {
    }

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

    public void init() {
        MyIcon icon = new MyIcon(15, 15);
        //图标放在标签,也可以放在按钮上
        JLabel label = new JLabel("icon", icon, SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(label);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    @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

public class TestImageIcon {
    public static void main(String[] args) {
        new MyImageIcon();
    }
}

class MyImageIcon extends JFrame {
    public MyImageIcon() {
        JLabel label = new JLabel("ImageIcon");
        //获取图片地址
        URL url = MyImageIcon.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, 200, 200);
    }
}
3.4,面板

JPanel

public class TestJPanel {
    public static void main(String[] args) {
        new MyJPanel();
    }
}
class MyJPanel extends JFrame {
    public MyJPanel(){
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(2,1,10,10));
        JPanel panel = new JPanel(new GridLayout(1, 3));
        panel.add(new JButton("1"));
        panel.add(new JButton("1"));
        panel.add(new JButton("1"));
        container.add(panel);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

}

JScrollPane

public class TestJScroll {
    public static void main(String[] args) {
        new MyJScroll();
    }
}
class MyJScroll extends JFrame{
    public MyJScroll(){
        Container container = this.getContentPane();
        //文本域
        JTextArea textArea = new JTextArea(20, 50);
        //JScroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);
        this.setVisible(true);
        this.setBounds(100,100,300,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
3.5,按钮

图片按钮

public class TestImageJButton {
    public static void main(String[] args) {
        new MyImageJButton();
    }
}
class MyImageJButton extends JFrame{
    public MyImageJButton(){
        Container container = this.getContentPane();
        //将一个图片变为图标
        URL url = MyImageJButton.class.getResource("tx.jpg");
        Icon icon = new ImageIcon(url);
        //把这个图标放在按钮上
        JButton button = new JButton();
        button.setIcon(icon);
        button.setToolTipText("图片按钮");
        container.add(button);
        this.setVisible(true);
        this.setSize(500,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
    }
}

单选按钮

public class TestJRadioButton {
    public static void main(String[] args) {
        new MyJRadioButton();

    }
}

class MyJRadioButton extends JFrame {
    public MyJRadioButton() {
        Container container = this.getContentPane();
        JRadioButton jRadioButton1 = new JRadioButton("JRadioButton1");
        JRadioButton jRadioButton2 = new JRadioButton("JRadioButton2");
        JRadioButton jRadioButton3 = new JRadioButton("JRadioButton3");
        //分组
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(jRadioButton1);
        buttonGroup.add(jRadioButton2);
        buttonGroup.add(jRadioButton3);
        container.add(jRadioButton1, BorderLayout.CENTER);
        container.add(jRadioButton2, BorderLayout.NORTH);
        container.add(jRadioButton3, BorderLayout.SOUTH);
        this.setVisible(true);
        this.setSize(500, 300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

复选按钮

public class TestJCheckBox {
    public static void main(String[] args) {
        new MyJCheckBox();
    }
}

class MyJCheckBox extends JFrame {
    public MyJCheckBox() {
        Container container = this.getContentPane();
        //多选框
        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);
    }
}
3.6,列表

下拉框

public class TestJComBox {
    public static void main(String[] args) {
        new MyJComBox();
    }
}

class MyJComBox extends JFrame {
    public MyJComBox() {
        Container contentPane = this.getContentPane();
        JComboBox box = new JComboBox();
        box.addItem(null);
        box.addItem("高");
        box.addItem("中");
        box.addItem("低");
        contentPane.add(box);
        this.setVisible(true);
        this.setSize(500, 300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

列表框

public class TestJComBox {
    public static void main(String[] args) {
        new MyJComBox();
    }
}

class MyJComBox extends JFrame {
    public MyJComBox() {
        Container contentPane = this.getContentPane();
        Vector vector = new Vector();
        JList jList = new JList(vector);
        vector.add("高");
        vector.add("中");
        vector.add("低");
        contentPane.add(jList);
        this.setVisible(true);
        this.setSize(500, 300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
3.7,文本框

文本框

public class TestJTextField {
    public static void main(String[] args) {
        new MyJTextField();
    }
}
class MyJTextField extends JFrame{
    public MyJTextField(){
        Container container = this.getContentPane();
        JTextField textField01 = new JTextField("hello");
        JTextField textField02 = new JTextField("world",20);
        container.add(textField01,BorderLayout.NORTH);
        container.add(textField02,BorderLayout.SOUTH);
        this.setVisible(true);
        this.setSize(500, 300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

密码框

public class TestJPasswordField {
    public static void main(String[] args) {
        new MyJPasswordField();
    }
}
class MyJPasswordField extends JFrame{
    public MyJPasswordField(){
        Container container = this.getContentPane();
        JPasswordField passwordField = new JPasswordField();
        passwordField.setEchoChar('*');
        container.add(passwordField);
        this.setVisible(true);
        this.setSize(500, 300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

文本域

public class TestJScroll {
    public static void main(String[] args) {
        new MyJScroll();
    }
}
class MyJScroll extends JFrame{
    public MyJScroll(){
        Container container = this.getContentPane();
        //文本域
        JTextArea textArea = new JTextArea(20, 50);
        //JScroll面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);
        this.setVisible(true);
        this.setBounds(100,100,300,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
4,贪吃蛇

数据

//数据中心
public class Data {
    public static URL headerURL = Data.class.getResource("static/header.png");
    public static ImageIcon header = new ImageIcon(headerURL);
    public static URL upURL = Data.class.getResource("static/up.png");
    public static ImageIcon up = new ImageIcon(upURL);
    public static URL downURL = Data.class.getResource("static/down.png");
    public static ImageIcon down = new ImageIcon(downURL);
    public static URL leftURL = Data.class.getResource("static/left.png");
    public static ImageIcon left = new ImageIcon(leftURL);
    public static URL rightURL = Data.class.getResource("static/right.png");
    public static ImageIcon right = new ImageIcon(rightURL);
    public static URL bodyURL = Data.class.getResource("static/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);
    public static URL foodURL = Data.class.getResource("static/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);
}

游戏面板

//游戏面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {
    //定义蛇的结构
    int length;//蛇的长度
    int[] snakeX = new int[600];//x坐标
    int[] snakeY = new int[500];//y坐标
    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] = 100;
        snakeY[1] = 100;//第一节身体坐标
        snakeX[2] = 100;
        snakeY[2] = 100;//第二节身体坐标
        fx = "R";
        //随机分布食物
        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.BLACK);
        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("长度", 750, 35);
        g.drawString("分数", 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 = 0; 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, 40));//设置字体
            g.drawString("失败,按下空格重新开始游戏", 300, 300);
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_SPACE) {
            if (isFail) {
                isFail = false;
                init();
            } else {
                isStart = !isStart;//取反
            }
            repaint();
        }
        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";
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && isFail == false) {
            if (snakeX[0] == foodx && snakeY[0] == foody) {
                length++;
                score = score + 10;
                foodx = 25 + 25 * random.nextInt(34);
                foody = 75 + 25 * random.nextInt(24);
            }
            for (int i = 0; i > length - 1; 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 = 0; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
                    isFail = true;
                }
            }
            repaint();
        }
        timer.start();
    }
}

游戏界面

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值