JAVA——GUI学习

1.简介

GUI的核心技术:Swing AWT

快被淘汰了!

1.因为界面不美观

2.需要jre环境

3.主要是能了解MVC架构,了解监听

2.AWT

抽象窗口工具包 (Abstract Windowing Toolkit)

2.1Awt介绍

1.包含了很多类和接口

2.元素:窗口、按钮等等

3.java.awt包

2.2组件和容器

1.Frame

import java.awt.*;

public class TestFrame {
    public static void main(String[] args) {
        Frame frame = new Frame("这是标题");

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

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

        //设置背景颜色
        frame.setBackground(Color.green);

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

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

回顾封装,利用封装的特性一次性展示多个窗口

import java.awt.*;

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

class MyFrame extends Frame {
    static int id=0;//窗口的id

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

    }
}

2.面板Panel

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


//Panel 可以看成一个空间,但是不能单独存在,需要放在frame上
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(Color.blue);

        //panel设置坐标,这是相对于frame的坐标
        panel.setBounds(50,50,400,400);
        panel.setBackground(Color.white);

        //frame.add()
        frame.add(panel);

        frame.setVisible(true);

        //监听事件,监听窗口关闭事件
        //适配器模式:
        frame.addWindowListener(new WindowAdapter() {
            //窗口点击关闭的时候需要做的事情
            @Override
            public void windowClosing(WindowEvent e) {
                //结束程序
                System.exit(0);
            }
        });
    }
}

2.3布局管理器

  • 流式布局
import java.awt.*;

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

        //组件-按钮
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");

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

        frame.setSize(200,200);

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

        frame.setVisible(true);
    }
}
  • 东西南北中
import java.awt.*;

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

        Button Eest = 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(Eest,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);
    }
}
  • 表格布局
import java.awt.*;

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

        frame.pack();//pack()方法就是自动调整窗口的大小,以适应放置的组件
        frame.setVisible(true);
    }
}

一个练习JAVA——GUI学习_第1张图片

import java.awt.*;

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

总结

1.Frame是一个顶级窗口

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

3.三种布局:流式,东西南北中,表格

4.应设置大小定位,背景颜色,可见性及监听事件

2.4事件监听

点击按钮响应以及关闭frame的响应

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("输出aaa");

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

多个按钮共享一个监听事件

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("开始-停止");
        Button button1 = new Button("start");
        Button button2 = new Button("stop");

        //可以显示的定义触发会返回的命令,如果不显示定义,则会走默认的值(即上面的Button里的label)!
        //可以多个按钮只写一个监听类
        button1.setActionCommand("button1-start");

        MyMonitor myMonitor = new MyMonitor();

        button1.addActionListener(myMonitor);
        button2.addActionListener(myMonitor);

        frame.add(button1,BorderLayout.NORTH);
        frame.add(button2,BorderLayout.SOUTH);

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

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

2.5输入框TextField监听

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

public class TestText01 {
    public static void main(String[] args) {
        //主函数里一般只写启动
        new MyFrame("这是标题");
    }
}

class MyFrame extends Frame{
    public MyFrame(String title){
        super(title);
        TextField textField = new TextField();
        add(textField);

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

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

        setVisible(true);
        pack();

    }
}

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

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

第一次的写法

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

//简易计算器
public class TestCalculator {
    public static void main(String[] args) {
        new Calculator("简易计算器");
    }
}

//计算器类
class Calculator extends Frame{
    public Calculator(String title){
        super(title);
        //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);

        setVisible(true);
        pack();
    }
}

//监听器类
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("");
    }
}

完全改造成面向对象的写法

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

//简易计算器
public class TestCalculator {
    public static void main(String[] args) {
        new Calculator("简易计算器").loadFrame();
    }
}

//计算器类
class Calculator extends Frame{
    //属性
    TextField num1,num2,num3;
    public Calculator(String title){
        super(title);
    }
    //方法
    public void loadFrame(){
        //3个文本框
        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);

        setVisible(true);
        pack();
    }
}

//监听器类
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.将这个值子 加法 运算后,方到第三个框里cal
        calculator.num3.setText(""+(n1+n2));

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

内部类写法

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

//简易计算器
public class TestCalculator {
    public static void main(String[] args) {
        new Calculator("简易计算器").loadFrame();
    }
}

//计算器类
class Calculator extends Frame{
    //属性
    TextField num1,num2,num3;
    public Calculator(String title){
        super(title);
    }
    //方法
    public void loadFrame(){
        //3个文本框
        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);

        setVisible(true);
        pack();
    }

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

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

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

            //3.清除前两个框
            num1.setText("");
            num2.setText("");
        }
    }
}

内部类最大的好处,就是畅通无阻地访问外部类的属性和方法!

2.7画笔

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) {
        //画笔,需要有颜色,画笔可以画画
        g.setColor(Color.green);
        g.drawOval(100,100,100,100);
        g.fillOval(100,300,100,100);//实心的圆

        g.setColor(Color.red);
        g.fillRect(200,200,200,200);

        //养成习惯,画笔用完,将他还原到最初的颜色
        g.setColor(Color.black);
    }
}

2.8鼠标监听

目的:想要实现鼠标画画

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

public class TestMouseListener {
    public static void main(String[] args) {
        new MyFrame("画图");
    }
}

class MyFrame extends Frame {
    //画画需要画笔,需要监听鼠标当前的位置,需要集合来存储这个点
    ArrayList points;

    public MyFrame(String title) {
        super(title);
        setBounds(200, 200, 400, 300);
        //存鼠标点击的点
        points = new ArrayList<>();
        setVisible(true);
        //鼠标监听器,正对这个窗口
        this.addMouseListener(new MyMouseListener());
    }

    @Override
    public void paint(Graphics g) { //画笔与画板Frame是绑定的
        //画画,监听鼠标的事件
        Iterator iterator = points.iterator();
        while (iterator.hasNext()) {
            Point point = (Point) iterator.next();
            g.setColor(Color.green);
            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 frame = (MyFrame) e.getSource();
            //这里我们点击的时候,就会在界面上产生一个点!
            //这个点就是鼠标的点
            frame.addPaint(new Point(e.getX(), e.getY()));

            //每次点击鼠标需要重新画一遍
            frame.repaint();//刷新
        }
    }
}

2.9窗口接听

监听类的写法(不推荐)

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() {
        setBounds(100,100,200,200);
        setVisible(true);
        addWindowListener(new MyWindowListener());

    }

    class MyWindowListener extends WindowAdapter {
        @Override
        public void windowClosing(WindowEvent e) {
            //setVisible(false);//隐藏窗口,并不是真正的退出
            System.exit(0);//正常退出为0,非正常退出为1
        }
    }
}

匿名内部类的写法+多种窗口监听方法的使用

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() {
        setBounds(100,100,200,200);
        setVisible(true);
        //addWindowListener(new MyWindowListener());

        this.addWindowListener(
                //匿名内部类
                new WindowAdapter() {
                    @Override
                    public void windowOpened(WindowEvent e) {
                        System.out.println("窗口打开");
                    }

                    @Override
                    public void windowClosed(WindowEvent e) {//一般捕获不到
                        System.out.println("窗口已关闭");
                    }

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

                    @Override
                    public void windowDeactivated(WindowEvent e) {
                        WindowFrame source = (WindowFrame) e.getSource();
                        source.setTitle("窗口被吃掉了");
                        System.out.println("窗口未激活");
                    }

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

}

2.10键盘监听

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(String title){
        super(title);
        setBounds(1,2,300,400);
        setVisible(true);

        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                //获得键盘按下的是哪个键
                System.out.println(e.getKeyCode());
                if (e.getKeyCode()==KeyEvent.VK_0) {
                    System.out.println("你按下了0键");
                }
                //根据按下不同的按钮,产生不同的结果
            }
        });
    }
}

3.Swing

3.1 JFrame窗口、面板

创建一个窗口—(在这个类中为何,设置背景颜色未成功?)

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

public class JFrameDemo {

    //init();初始化
    public void init(){
        JFrame frame = new JFrame("Swing编程");
        frame.setBounds(100,100,200,200);
        frame.setBackground(Color.green);
        frame.setVisible(true);

        //设置文字 JLabel
        JLabel label = new JLabel("hello Swing!");
        frame.add(label);

        //关闭事件
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

    }
}

标签居中—(解决上面的问题,Container)

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

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

class MyJFrame2 extends JFrame{
    public void init(){
        this.setBounds(10,10,200,300);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JLabel label = new JLabel("Swing-Hello!");
        this.add(label);

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

        //获得一个容器
        Container contentPane = this.getContentPane();
        contentPane.setBackground(Color.green);
    }
}

3.2 JDialog弹窗

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

//主窗口
public class DialogDemo extends JFrame {

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

        //JFrame 放东西,容器
        Container container = this.getContentPane();
        //绝对布局
        container.setLayout(null);

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

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

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

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

        Container container = this.getContentPane();
        container.setLayout(null);

        container.add(new Label("虚空掠食者-卡兹克"));

    }
}

3.3 Icon、ImageIcon标签

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("img2.png");

        ImageIcon imageIcon = new ImageIcon(url);
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);

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

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

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

3.4文本域JScroll面板

JPanel

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

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

        container.setLayout(new GridLayout(2,2,10,10));//后面两个参数是设置间距

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

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

        container.add(panel);
        container.add(panel2);
        container.add(panel3);
        container.add(panel4);

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

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

JScrollPanel

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

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

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

        //文本域
        JTextArea textArea = new JTextArea(20, 50);
        textArea.setText("欢迎学习Java");

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

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

3.5按钮

图片按钮

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

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

    public JButtonDemo01(){
        Container container = this.getContentPane();
        //将一个图片变为图标
        URL url = JButtonDemo01.class.getResource("img2.png");
        Icon icon = new ImageIcon(url);

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

        container.add(button);

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

单选按钮/复选按钮

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

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

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

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

        //由于单选框是能选择一个,需要分组,复选框则不需要分组
        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(100,100,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

复选框

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

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

    public JButtonDemo03(){
        Container container = this.getContentPane();
        //将一个图片变为图标
        URL url = JButtonDemo01.class.getResource("img2.png");
        Icon icon = new ImageIcon(url);

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

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

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

3.6下拉框、列表框

下拉框

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

public class TestComboboxDemo01 extends JFrame {
    public TestComboboxDemo01(){

        Container container = this.getContentPane();

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

        container.add(status);

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

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

列表框

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

public class TestComboboxDemo02 extends JFrame {
    public TestComboboxDemo02(){

        Container container = this.getContentPane();

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

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

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

3.7文本框、密码框

文本框

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

public class TestTextDemo01 extends JFrame {
    public static void main(String[] args) {
        new TestTextDemo01();
    }

    public TestTextDemo01() {
        Container container = this.getContentPane();

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

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


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

密码框

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

public class TestTextDemo02 extends JFrame {
    public static void main(String[] args) {
        new TestTextDemo02();
    }

    public TestTextDemo02() {
        Container container = this.getContentPane();

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

        container.add(passwordField);


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

JAVA-GUI_贪吃蛇小游戏(一个小项目)

启动类

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

public class StartGame extends JFrame{
    public static void main(String[] args) {
        new StartGame();
    }

    public StartGame() throws HeadlessException {
        super("贪吃蛇小游戏");
        this.add(new GamePanel());

        this.setBounds(10,10,900,720);
        this.setResizable(false);//窗口大小不可变
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

资源加载类

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 ImageIcon up=new ImageIcon(upURL);

    public static URL downURL=Data.class.getResource("statics/down.png");
    public static ImageIcon down=new ImageIcon(downURL);

    public static URL leftURL=Data.class.getResource("statics/left.png");
    public static ImageIcon left=new ImageIcon(leftURL);

    public static URL rightURL=Data.class.getResource("statics/right.png");
    public static ImageIcon right=new ImageIcon(rightURL);

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

面板主要实现类

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];
    int[] snakeY=new int[500];
    String fx;

    //食物的坐标
    int foodx;
    int foody;
    Random random=new Random();

    int score;//成绩
    //游戏当前的状态:开始、停止
    boolean isStart=false;//默认是不开始
    boolean isFail=false;//游戏失败
    //定时器
    Timer timer=new Timer(150,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;
        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.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,55);

        //画食物
        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,40));//设置字体
            g.drawString("失败,按下空格重新开始",300,300);
        }

    }

    //事件监听---需要通过固定事件来刷新,1s=10次
    @Override
    public void actionPerformed(ActionEvent e) {
        if(isStart&&isFail==false){//如果游戏是开始状态,就让小蛇动起来
            //吃食物
            if(snakeX[0]==foodx&&snakeY[0]==foody){
                //长度+1
                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(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
                    isFail=true;
                }
            }

            //边界判断

            repaint();
        }
        timer.start();
    }

    @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_W||keyCode==KeyEvent.VK_UP){
            fx="U";
        }else if(keyCode==KeyEvent.VK_S||keyCode==KeyEvent.VK_DOWN){
            fx="D";
        }else if(keyCode==KeyEvent.VK_A||keyCode==KeyEvent.VK_LEFT){
            fx="L";
        }else if(keyCode==KeyEvent.VK_D||keyCode==KeyEvent.VK_RIGHT){
            fx="R";
        }
    }

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

你可能感兴趣的:(JavaSE,java)