Java基础-GUI编程讲解

GUI编程

组件

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

简介

GUI的核心技术:Swing和AWT

1.界面不美观

2.需要jre环境

3.GUI是MVC的基础,可以写出自己心里想要的一些小工具,工作需要维护到swing界面。

了解MVC架构,了解监听。

AWT

介绍

  • 抽象的窗口工具
  • 包含了很多的类和接口。
  • GUI:图形用户界面
  • 元素:窗口,按钮,文本框

Java基础-GUI编程讲解_第1张图片

组件和容器

Frame

Java基础-GUI编程讲解_第2张图片

package gui.study;

import java.awt.*;

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

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

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

        //设置背景颜色
        frame.setBackground(new Color(18, 145, 229));

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

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

  • 多个图形界面,自己定义一个MyFrame方法继承Frame
package gui.study;

import java.awt.*;

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

    }
}

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);
    }
}
面板Panel
  • frame.add(Panel)

  • 解决了关闭问题:用WindowsListener的子类重写方法

package gui.study;

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

//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(28, 234, 28));

        //panel设置坐标,相对于frame
        panel.setBounds(50,50,400,400);
        panel.setBackground(new Color(12, 99, 205));

        //frame.add(panel):添加面板
        frame.add(panel);

        //可视化
        frame.setVisible(true);

        //监听事件,监听窗口关闭事件,System.exit(0)
        //适配器模式:新new一个窗口的时候需要重新很多方法,现在只用重新一个
        //WindowsAdapter是WindowsListener的子类
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                //关闭程序
                System.exit(0);
            }
        });

    }
}

布局管理器
  • 流式布局(FlowLayout)
package gui.study;

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

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

        //组件-按钮
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        //设置为流式布局
        frame.setLayout(new FlowLayout(FlowLayout.RIGHT));

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

        frame.setSize(200,200);

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

  • 东西南北中局部(BorderLayout)
package gui.study;

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

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

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

  • 表格布局(GridLayout)
package gui.study;

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

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

        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.setSize(100,100);
        frame.add(btn1);
        frame.add(btn2);
        frame.add(btn3);
        frame.add(btn4);
        frame.add(btn5);
        frame.add(btn6);

        //java函数:自动选择最优的布局
        frame.pack();
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
练习

Java基础-GUI编程讲解_第3张图片

package gui.study;

import java.awt.*;

public class ExerTest {
    public static void main(String[] args) {
        //总
        Frame frame = new Frame();
        frame.setLayout(new GridLayout(2,1));
        frame.setVisible(true);
        frame.setSize(100,100);
        frame.setLocation(50,50);
        frame.setBackground(Color.BLACK);

        //四个面板
        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面板里面加p2面板
        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面板里面加p4面板
        p3.add(p4,BorderLayout.CENTER);

        frame.add(p1);
        frame.add(p3);

    }
}

事件监听

  • 多个按钮共享一个事件
package gui.study.lesson2;

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

public class TestActionEvent1 {
    public static void main(String[] args) {
        //两个按钮实现同一个监听
        //开始  停止
        Frame frame = new Frame("开始-停止");
        Button button = new Button("start");
        Button button1 = new Button("stop");

        //可以显示定义触发会返回的命令,不显示即走默认的值
        //可以多个按钮只写一个监听类
        button1.setActionCommand("button1-stop");

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

        frame.add(button,BorderLayout.NORTH);
        frame.add(button1,BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }
}

class MyMonitor implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        //e.getActionCommand():获得按钮的信息
        System.out.println("点击按钮:msg=>"+e.getActionCommand());

    }
}

输入框TextField监听

package gui.study.lesson2;

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

public class TestTextField {
    public static void main(String[] args) {
        //启动
        new MyFrame();
    }
}
class MyFrame extends Frame{
    public MyFrame(){
        //创建并添加文本框
        TextField textField = new TextField();
        add(textField);

        //监听这个文本框输入的文字
        //按下enter键就触发这个输入框的事件
        textField.addActionListener(new MyActionListener2());

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

        setVisible(true);
        pack();
        setBounds(200,300,500,500);
        setResizable(false);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
class MyActionListener2 implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        //获得资源,返回一个对象
        //监听了谁就是谁
        TextField field = (TextField) e.getSource();
        System.out.println(field.getText());//获得输入框的文本
        field.setText("");//不能设置null
    }
}
练习
  • 简易计算器,组合+内部类
  • OOP原则:组合大于继承

完全转换为面向对象写法:

package gui.study.lesson2;

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

/*
1.构造一个类里面的属性和方法,一次构造组件,
2.然后给组件加上监听器,
3.再布局出来
 */
//简易计算器
public class TextComputer {
    public static void main(String[] args) {
        new Computer().loadFrame();
    }
}

//计算器类
class Computer extends Frame{
    //属性
    TextField num1,num2,num3;
    //方法
    public void loadFrame(){
        //3个文本框
        num1 = new TextField(10);//字符数
        num2 = new TextField(10);
        num3 = new TextField(20);
        //1个按钮
        Button button = new Button("=");
        //1个标签
        Label label = new Label("+");
        button.addActionListener(new MyComputerListener( this));
        //添加文本框
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        //布局
        setLayout(new FlowLayout());
        setVisible(true);
        pack();
        setBounds(200,300,500,500);
        setResizable(false);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
//监听器类
class MyComputerListener implements ActionListener{
    //获取计算器这个对象,在一个类中组合另外一个类
    Computer computer = null;
    //构建一个有参构造器调用
    public MyComputerListener(Computer computer) {
        this.computer = computer;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //1.获得加数和被加数
        //2.将这个值运算后放到第三个框
        //3.清除前两个框
        int n1 = Integer.parseInt(computer.num1.getText());//String类型转换int类型,通过包装类来转换
        int n2 = Integer.parseInt(computer.num2.getText());
        computer.num3.setText(" "+(n1+n2));
        computer.num1.setText("");
        computer.num2.setText("");
    }
}

内部类写法:为了更好的包装,内部类的最大好处可以畅通无阻的访问外部的属性和方法。

package gui.study.lesson2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//简易计算器
public class TextComputer {
    public static void main(String[] args) {
        new Computer().loadFrame();
    }
}
//计算器类
class Computer 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 MyComputerListener());
        //添加文本框
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);
        //布局
        setLayout(new FlowLayout());
        setVisible(true);
        pack();
        setBounds(200,300,500,500);
        setResizable(false);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    //监听器类
    //内部类的最大好处可以畅通无阻的访问外部的属性和方法。
   private class MyComputerListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            //1.获得加数和被加数
            //2.将这个值运算后放到第三个框
            //3.清除前两个框
            int n1 = Integer.parseInt(num1.getText());//String类型转换int类型,通过包装类来转换
            int n2 = Integer.parseInt(num2.getText());
            num3.setText(" "+(n1+n2));
            num1.setText("");
            num2.setText("");
        }
    }
}

画笔(draw)

package gui.study.lesson3;

import java.awt.*;

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);
    }
    //画笔
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        //画笔,需要有颜色
        g.setColor(Color.red);
        //g.drawOval(100,100,100,100);//画个圆
        g.fillOval(100,100,100,100);//画实心圆

        g.setColor(Color.blue);
        g.fillRect(150,200,200,200);//画一个实习矩形
        
        //洗画笔
        g.setColor(Color.BLACK);
    }
}

鼠标监听

目的:实现鼠标画画

Java基础-GUI编程讲解_第4张图片

1.需要有一个窗

2.单独一个画笔

3.单独做一个适配器

4.想要有联系就做一个缓冲器,鼠标点开存到集合里面,集合先定义

5.把当前鼠标的位置存储到集合,Paint将其读出来

6.需要不断的重画,就用repaint(),也就是所谓的帧。

package gui.study.lesson3;

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);
        //画板
        setBounds(200,200,400,300);

        //存鼠标点击的点
        points = new ArrayList<>();
        //鼠标监听器,正对这个窗口
        this.addMouseListener(new MyMouseListener());

        setVisible(true);
    }
    //画笔重写方法
    @Override
    public void paint(Graphics g) {
        //画画监听鼠标的事件
        super.paint(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 addPaint(Point point){
        points.add(point);//丢给集合去遍历
    }
    //内部类
    private class MyMouseListener extends MouseAdapter{
        //鼠标:按下,弹起,按住不放
        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame myFrame = (MyFrame) e.getSource();
            //在点击的时候会在界面上产生一个点,这个点就是鼠标的点
            myFrame.addPaint(new Point(e.getX(),e.getY()));
            //每次点击鼠标都需要重新画一次
            myFrame.repaint();
        }
    }
}

窗口监听

package gui.study.lesson3;

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(){
        setBackground(Color.BLUE);
        setBounds(100,100,400,400);
        setVisible(true);
        //匿名内部类
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
            //激活窗口(先隐藏再跳出来就激活了)
            @Override
            public void windowActivated(WindowEvent e) {
                WindowFrame source = (WindowFrame) e.getSource();
                source.setTitle("快回来,别跑了");
                System.out.println("windowActivated");
            }
        });
    }
}

键盘监听

package gui.study.lesson3;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class TestKeyListener {
    public static void main(String[] args) {
        new MyKeyFrame("键盘监听");
    }
}
class MyKeyFrame extends Frame{
    public MyKeyFrame(String title){
        super(title);
        setBounds(1,2,300,400);
        setVisible(true);

        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                //键盘按下的键是哪个
                super.keyPressed(e);
                int keyCode = e.getKeyCode();//获取当前键盘的码
                System.out.println(keyCode);
                if (keyCode == KeyEvent.VK_UP){//直接使用静态属性 VK_xx 
                    System.out.println("你按下上键");
                }
            }
        });
    }
}

Swing

  • 高级点,能画图

窗口、面板

package gui.study.lesson4;

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

//swing下的框架
public class JFrameDemo extends JFrame{
    //init():初始化
    public void init(){
        this.setVisible(true);//走的子类
        this.setBounds(100,100,200,200);

        //关闭事件,swing下不需要监听事件
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //设置文字
        JLabel label = new JLabel("ko");
        this.add(label);

        //容器实例化:与AWT的区别,需要容器实例化
        Container container = this.getContentPane();
        container.setBackground(Color.BLUE);
    }

    public static void main(String[] args) {
        //建立一个窗口
        new JFrameDemo().init();
    }
}

弹窗(Dialog)

package gui.study.lesson4;

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

public class DialogDemo extends JFrame {
    //构造器
    public DialogDemo() {
        this.setBounds(200,200,400,400);
        this.setVisible(true);
        //关闭窗口
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //容器
        Container container = this.getContentPane();
        //绝对定位布局
        container.setLayout(null);
        //按钮
        JButton button = new JButton("点击弹出一个对话框");
        button.setBounds(30,30,200,50);//按钮大小

        container.add(button);

        //点击按钮弹出弹窗
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //弹窗
                new MyDialogDemo();
            }
        });
    }

    public static void main(String[] args) {
        new DialogDemo();
    }
}
//弹窗的窗口
class  MyDialogDemo extends JDialog{//用Dialog的子类不用写那么多方法

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

标签

new JLabel("");
  • 图标:Icon
package gui.study.lesson4;

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

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

    private int width;
    private int height;
    public IconDemo(){//无参构造
        this.setBounds(200,200,400,400);
        this.setVisible(true);
        //关闭窗口
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    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().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;
    }
}

  • 图片:ImageIcon
package gui.study.lesson4;

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("llyy.jpg");

        ImageIcon imageIcon = new ImageIcon(url);
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);//图片居中
        //容器
        Container container = this.getContentPane();
        container.add(label);

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

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

面板(Jpanel)

package gui.study.lesson5;

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 panel = new JPanel(new GridLayout(1,3));
        JPanel panel1 = new JPanel(new GridLayout(1,2));
        JPanel panel2 = new JPanel(new GridLayout(2,3));
        panel.add(new JButton("w"));
        panel.add(new JButton("s"));
        panel.add(new JButton("e"));
        for (int i = 0; i < 2; i++) {
            panel1.add(new JButton("q"));
        }
        for (int i = 0; i < 3; i++) {
            panel2.add(new JButton("r"));
        }

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

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


    }

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

  • 下滑一页(JScrollPanel)
package gui.study.lesson5;

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

public class JScrollDemo extends JFrame {
    public JScrollDemo() {
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(1,3,20,20));

        //文本域
        JTextArea textArea = new JTextArea(20, 50);
        textArea.setText("小朋友");

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

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

    }

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

按钮

package gui.study.lesson5;

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

public class JButtonDemo extends JFrame {
    public JButtonDemo() {
        Container container = this.getContentPane();
        URL url = JButtonDemo.class.getResource("llyy.jpg");
        Icon imageIcon = new ImageIcon(url);//把图片变成图标

        //把图标放在按钮上
        JButton button = new JButton();
        button.setIcon(imageIcon);
        button.setToolTipText("图片按钮");

        container.add(button);

        this.setVisible(true);
        this.setBounds(200,200,500,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }


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

  • 单选按钮(JRadioButton):需要分组(ButtonGroup)
package gui.study.lesson5;

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

public class JButtonDemo extends JFrame {
    public JButtonDemo() {
        Container container = this.getContentPane();
        URL url = JButtonDemo.class.getResource("llyy.jpg");
        Icon imageIcon = new ImageIcon(url);//把图片变成图标

        //单选框
        JRadioButton radioButton1 = new JRadioButton("01");
        JRadioButton radioButton2 = new JRadioButton("02");
        JRadioButton radioButton3 = new JRadioButton("03");
        //由于单选框只能选择一个需要分组
        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.setBounds(200,200,500,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }


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

  • 多选按钮(JCheckBox)
package gui.study.lesson5;

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

public class JButtonDemo extends JFrame {
    public JButtonDemo() {
        Container container = this.getContentPane();
        //单选框
        JCheckBox checkBox1 = new JCheckBox("01");
        JCheckBox checkBox2 = new JCheckBox("02");

        container.add(checkBox1,BorderLayout.NORTH);
        container.add(checkBox2,BorderLayout.SOUTH);

        this.setVisible(true);
        this.setBounds(200,200,500,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

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

列表

  • 下拉框(JComBox)
package gui.study.lessson6;

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

public class TestCombobox extends JFrame {
    public TestCombobox() {

        Container container = getContentPane();

        JComboBox status = new JComboBox();

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

        container.add(status);

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

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

  • 列表框(JList)
package gui.study.lessson6;

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

public class TestCombobox1 extends JFrame {
    public TestCombobox1(String title) {
        super(title);
        Container container = getContentPane();
        //生成列表的内容
        //String[] contents = {"1","2","3"};
        Vector contents = new Vector();
        contents.add("客户1");
        contents.add("客户2");
        contents.add("客户3");
        //列表中需要放入的内容
        JList list = new JList(contents);
        container.add(list);

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

    public static void main(String[] args) {
        new TestCombobox1("客户端");
    }
}

文本框

package gui.study.lessson6;

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

public class TestTextDemo extends JFrame {
    public TestTextDemo() {

        Container container = this.getContentPane();

        JTextField textField = new JTextField("HELLO");
        JTextField textField1 = new JTextField("WORLD",20);

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

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

    }

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

密码框(JPasswordField)

文本域(JTextArea)

游戏:贪吃蛇

  • 需要帧、键盘监听、定时器Timer
package gui.study.snack;

import javax.swing.*;

//游戏的主启动页
public class StartGame extends JFrame {
    public StartGame(String title) {
        super(title);
        //正常游戏界面都在面上
        this.add(new GamePanel());

        this.setVisible(true);
        this.setBounds(10,10,900,720);
        this.setResizable(false);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new StartGame("小小贪吃蛇");
    }
}

package gui.study.snack;
//定义一个数据,初始化,画上去,监听事件(键盘,事件)
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;

//游戏的面板
public class GamePanel extends JPanel implements KeyListener, ActionListener {
    //定义蛇的身体结构
    int length;//蛇的长度
    int[] snakeX = new int[600];//蛇的x坐标
    int[] snakeY = new int[500];//蛇的y坐标
    String direction;//初始方向
    //食物的坐标
    int foodx;
    int foody;
    Random random = new Random();
    boolean isStart = false; //游戏当前的状态,开始、停止
    boolean isFail = false;//游戏失败状态
    int score;
    int level;
    //定时器:以毫秒为单位 1000ms = 1s
    Timer timer =  new Timer(100,this);//100ms刷新一次这个监听器

    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;//第二个身体的坐标
        direction = "R";//初始方向向右
        foodx = getFoodx();
        foody = getFoody();
       // foodx = 25 + 25*random.nextInt(34);//850/25=34:为边界   25是每一个事物的大小
        //foody = 75 +25*random.nextInt(24);//600/25 = 24:为上下边界
        score = 0;
        level = 1;
    }
    public int getFoodx(){
        int x = 25 + 25*random.nextInt(34);
        boolean isFlag = true;
        while (isFlag){
            for (int i = 0; i < snakeX.length; i++) {
                if (snakeX[i] == x){
                    x = 25 + 25*random.nextInt(34);
                }else {
                    isFlag = false;
                }
            }
        }
        return x;
    }
    public int getFoody(){
        int y = 75 +25*random.nextInt(24);
        boolean isFlag = true;
        while (isFlag){
            for (int i = 0; i < snakeY.length; i++) {
                if (snakeY[0] == y){
                    y = 75 +25*random.nextInt(24);
                }else {
                    isFlag = false;
                }
            }
        }
        return y;
    }
    //绘制面板,游戏里的所有东西都是这个画笔来画
    @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,17));
        g.drawString("长度:" + length,750,30);
        g.drawString("当前积分:" + score,750,55);
        g.drawString("当前等级:" + level,220,30);
        //画食物
        Data.food.paintIcon(this,g,foodx,foody);
        //把小蛇画上去
        if (direction.equals("R")){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头初始化向右
        }else if (direction.equals("L")){
            Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头初始化向右
        }else if (direction.equals("U")){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);//蛇头初始化向右
        }else if (direction.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){
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//设置字体 粗体40号
            g.drawString("按下空格开始游戏!",300,300);
        }
        if (isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));//设置字体 粗体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){
            if (!direction.equals("D")){//不能回头
                direction = "U";
            }
        }else if (keyCode == KeyEvent.VK_DOWN){
            if (!direction.equals("U")){
                direction = "D";
            }
        }else if (keyCode == KeyEvent.VK_RIGHT){
            if (!direction.equals("L")){
                direction = "R";
            }
        }else if (keyCode == KeyEvent.VK_LEFT){
            if (!direction.equals("R")){
                direction = "L";
            }
        }
    }
    //定时器,事件监听:通过固定的时间来刷新 1s=10次
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && !isFail){//如果游戏开始状态就动小蛇
            //吃事物
            if (snakeX[0] == foodx && snakeY[0] == foody){//与食物重合
                length++;
                score+=10;
                switch (score){
                    case 100:
                        level++;
                        break;
                    case 300:
                        level++;
                        break;
                    case 500:
                        level++;
                        break;
                    case 1000:
                        level++;
                        break;
                    case 2000:
                        level++;
                        break;
                    case 4000:
                        level++;
                        break;
                }
                //再次随机食物
                //foodx = 25 + 25*random.nextInt(34);
                //foody = 75 +25*random.nextInt(24);
                foodx = getFoodx();
                foody = getFoody();
            }
            //移动
            for (int i = length -1; i >0 ; i--) {//走的是上一个身体待过单独位置所以length-1
                snakeX[i] = snakeX[i-1];//向前移动一节
                snakeY[i] = snakeY[i-1];
            }
            //走向
            if (direction.equals("R")){
                snakeX[0] = snakeX[0]+25;//一个身体就是25
                if (snakeX[0] > 850){ snakeX[0] = 25;}//边界判断
            }else if (direction.equals("L")){
                snakeX[0] = snakeX[0]-25;
                if (snakeX[0] < 25){ snakeX[0] = 850;}//边界判断
            }else if (direction.equals("U")){
                snakeY[0] = snakeY[0] - 25;
                if (snakeY[0] < 75){ snakeY[0] = 650;}//边界判断
            }else if(direction.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) {

    }

}

package gui.study.snack;

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

//数据中心
public class Data {

    public static URL headerURL = Data.class.getResource("statics/header.png");
    public static URL bodyURL = Data.class.getResource("statics/body.png");
    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 foodURL = Data.class.getResource("statics/food.png");
   // public static URL food1URL = Data.class.getResource("statics/food1.png");
    public static ImageIcon header = new ImageIcon(headerURL);
    public static ImageIcon body = new ImageIcon(bodyURL);
    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 food = new ImageIcon(foodURL);
   // public static ImageIcon food1 = new ImageIcon(food1URL);
}

eY[0] == snakeY[i]){
isFail = true;
}
}

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

@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {

}

}


```java
package gui.study.snack;

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

//数据中心
public class Data {

    public static URL headerURL = Data.class.getResource("statics/header.png");
    public static URL bodyURL = Data.class.getResource("statics/body.png");
    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 foodURL = Data.class.getResource("statics/food.png");
   // public static URL food1URL = Data.class.getResource("statics/food1.png");
    public static ImageIcon header = new ImageIcon(headerURL);
    public static ImageIcon body = new ImageIcon(bodyURL);
    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 food = new ImageIcon(foodURL);
   // public static ImageIcon food1 = new ImageIcon(food1URL);
}

你可能感兴趣的:(java基础,java,后端)