JAVA GUI编程

GUI编程

告诉大家怎么学

  • 这是什么
  • 他怎么玩
  • 该如何去在我们平时中运用

组件

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

1、简介

GUI的核心技术:Swing AWT

  1. 界面不美观

  2. 需要jre环境!

为什么我们要学习

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

2、AWT

2.1、AWT介绍

  1. 抽象的窗口工具

  2. 包含了很多类和接口!GUI:图形用户界面

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

  4. java.awt

  5. 组件Component

    • image

2.2、组件和容器

1、Frame

public class TestFrame {
    public static void main(String[] args) {
        //设置标题
        Frame Frame = new Frame("AWT窗口");
        //设置可见性
        Frame.setVisible(true);
        //设置窗口大小
        Frame.setSize(820,170);
        //设置窗口位置
        Frame.setLocation(500,500);
        //设置背景颜色color
        Frame.setBackground(Color.BLUE);
        //设置大小固定
        Frame.setResizable(false);
    }
}

image

问题:没有关闭窗口

尝试回顾封装

package com.GUI.JFrame;

import java.awt.*;

public class 多个窗口 {
    public static void main(String[] args) {
            new MyFrame(100,100,200,200,Color.BLUE);
            new MyFrame(300,100,200,200,Color.BLUE);
            new MyFrame(500,100,200,200,Color.BLUE);
            new MyFrame(700,100,200,200,Color.BLUE);
    }
}
class MyFrame extends Frame{
        static  int id = 0;//计数器
        public  MyFrame(int x,int y,int w, int h,Color color){
            super("Myframe+"+(++id));
            setVisible(true);
            setBounds(x,y,w,h);
            setBackground(color);
        }
}

image

2、面板panel

package com.GUI.Panel;

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(0x2020B8));
        //panel设置坐标,相对于frame
        panel.setBounds(50, 50, 400, 400);
        panel.setBackground(new Color(0xB64343));

        frame.add(panel);

        frame.setVisible(true);
        //监听事件
        //监听窗口关闭事件
        //适配器模式
        frame.addWindowListener(new WindowAdapter() {
            /**
             * Invoked when a window is in the process of being closed.
             * The close operation can be overridden at this point.
             *
             * @param e
             */
            //窗口点击关闭的时候需要做的事
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

image

//解决了关闭事件

3、布局管理器

  • 流式布局

    package com.GUI.Layout;
    
    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(500,500);
    
            frame.add(button1);
            frame.add(button2);
            frame.add(button3);
            frame.setVisible(true);
        }
    }
    

    image

  • 东西南北中

    package com.GUI.Layout;
    
    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("E");
            Button west = new Button("W");
            Button south = new Button("S");
            Button north = new Button("N");
            Button center= new Button("C");
    
            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);
    
            frame.addWindowListener(new WindowAdapter() {
                /**
                 * Invoked when a window is in the process of being closed.
                 * The close operation can be overridden at this point.
                 *
                 * @param e
                 */
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    }
    

    image

  • 表格布局Gridlayout

    package com.GUI.Layout;
    
    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("1");
            Button btn2 = new Button("2");
            Button btn3 = new Button("3");
            Button btn4 = new Button("4");
            Button btn5 = new Button("5");
            Button btn6 = new Button("6");
    
            frame.setLayout(new GridLayout(3,2));
    
            frame.add(btn1);
            frame.add(btn2);
            frame.add(btn3);
            frame.add(btn4);
            frame.add(btn5);
            frame.add(btn6);
    
            frame.pack();//java函数!自动最优
            frame.setVisible(true);
    
            frame.addWindowListener(new WindowAdapter() {
                /**
                 * Invoked when a window is in the process of being closed.
                 * The close operation can be overridden at this point.
                 *
                 * @param e
                 */
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    }
    

    image

练习:做出下图布局

image

package com.GUI.Layout;

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

//练习的Demo
public class TestDemo {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setVisible(true);
        frame.setSize(400,300);
        frame.setLocation(300,400);
        frame.setBackground(Color.blue);
        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,1));

        //上面
        p1.add(new Button("East-1"),BorderLayout.EAST);
        p1.add(new Button("Wast-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("Wast-2"),BorderLayout.WEST);
        //下面中间4个
        for (int i = 1; i <= 4; i++) {
            p4.add(new Button("p4-btn"+i));
        }
        p3.add(p4,BorderLayout.CENTER);
        //组装
        frame.add(p1);
        frame.add(p3);
        

        frame.addWindowListener(new WindowAdapter() {
            /**
             * Invoked when a window is in the process of being closed.
             * The close operation can be overridden at this point.
             *
             * @param e
             */
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

总结:

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

2.4、事件监听

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

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

public class TestActionEvent {
    public static void main(String[] args) {
        //按下按钮,触发一些事件
        Frame frame = new Frame();
        Button button = new Button("btn");
        //因为,addActionListEner()需要一个ActionListener,所有我们需要构造一个ActionListener
        MyActiooListener myActiooListener = new MyActiooListener();
        button.addActionListener(myActiooListener);

        frame.add(button,BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
        windowClose(frame);//关闭窗口

    }
    //关闭窗口事件
    private  static  void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            /**
             * Invoked when a window is in the process of being closed.
             * The close operation can be overridden at this point.
             *
             * @param e
             */
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

}
class MyActiooListener implements ActionListener {

    /**
     * Invoked when an action occurs.
     *
     * @param e
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("点击了Btn");
    }
}

image

多个按钮共享一个事件

package com.GUI.Listener;

import javax.accessibility.Accessible;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestAcctionTwo {
    public static void main(String[] args) {
        //两个按钮,实现同一个监听
        //开始 停止

        Frame frame = new Frame("开始-停止");
        Button start = new Button("start");
        Button stop = new Button("stop");

        //设置按钮信息,默认title值
        stop.setActionCommand("停止");
        MyMonitor myMonitor = new MyMonitor();
        start.addActionListener(myMonitor);
        stop.addActionListener(myMonitor);

        frame.setVisible(true);
        frame.add(start,BorderLayout.NORTH);
        frame.add(stop,BorderLayout.SOUTH);
        frame.pack();
    }
}
class MyMonitor implements ActionListener{
    /**
     * Invoked when an action occurs.
     *
     * @param e
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        //获取按钮信息
        //System.out.println("按钮被点击了:msg"+e.getActionCommand());
        if (e.getActionCommand().equals("start")){
            System.out.println("点击了start");
        }else if(e.getActionCommand().equals("停止")){
            System.out.println("点击了停止");
        }
    }
}

image

2.5、输入框监听

密文显示

输入清空

package com.GUI.Listener;

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 TestText01 {
    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('*');
        pack();
        winclose(this);
        setVisible(true);
    }
    public void winclose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            /**
             * Invoked when a window is in the process of being closed.
             * The close operation can be overridden at this point.
             *
             * @param e
             */
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
class MyActionListener implements ActionListener{

    /**
     * Invoked when an action occurs.
     *
     * @param e
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField textField = (TextField) e.getSource();//获得一些资源
        textField.getText();//获取输入框中的文本
        System.out.println(((TextField) e.getSource()).getText());
        textField.setText("");

    }
}

image

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

oop原则:组合,大于基础!

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

Demo1:最初

package com.GUI.TestCale;

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 TesrCalc {
    public static void main(String[] args) {
        new Calculator();
    }
}
//计算器类
class Calculator extends Frame{
    public  Calculator(){
        //3个文本框
        TextField textField1 = new TextField(10);
        TextField textField2 = new TextField(10);
        TextField textField3 = new TextField(20);
        //1个按钮
        Button button = new Button("=");
        button.addActionListener(new MyListener(textField1,textField2,textField3));
        //1个标签
        Label label = new Label("+");

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

        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);

        setVisible(true);
        pack();
        setResizable(false);
        winclose(this);
    }
    public  void  winclose(Frame frame){
        addWindowListener(new WindowAdapter() {
            /**
             * Invoked when a window is in the process of being closed.
             * The close operation can be overridden at this point.
             *
             * @param e
             */
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
//监听类
class  MyListener implements ActionListener{

    private  TextField num1,num2,num3;

    public MyListener(TextField num1, TextField num2, TextField num3) {
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3;
    }

    /**
     * Invoked when an action occurs.
     *
     * @param e
     */
    @Override
    //获取三个变量

    public void actionPerformed(ActionEvent e) {
        //1.获得加数和被加数
        int n1 = Integer.parseInt(num1.getText());
        int n2 = Integer.parseInt(num2.getText());
        //2.将这个值+法运算后,放到第三个框
        num3.setText(""+(n1+n2));
        //清除前两个框
        num1.setText("");
        num2.setText("");
    }
}

Demo02:组合优化

package com.GUI.TestCale;

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 TesrCalc {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}
//计算器类
class Calculator extends Frame{
    //属性
    TextField textField1;
    TextField textField2;
    TextField textField3;

    //方法
    public void loadFrame(){
        textField1 = new TextField(10);
        textField2 = new TextField(10);
        textField3 = new TextField(20);
        //1个按钮
        Button button = new Button("=");
        button.addActionListener(new MyListener(this));
        //1个标签
        Label label = new Label("+");

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

        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);

        setVisible(true);
        pack();
        setResizable(false);
        winclose(this);
    }

    public  void  winclose(Frame frame){
        addWindowListener(new WindowAdapter() {
            /**
             * Invoked when a window is in the process of being closed.
             * The close operation can be overridden at this point.
             *
             * @param e
             */
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}
//监听类
class  MyListener implements ActionListener{
    //获取计算机这个对象,在一个类中组合另外一个类。
    Calculator calculator = null;

    public MyListener(Calculator calculator) {
        this.calculator = calculator;
    }

    /**
     * Invoked when an action occurs.
     *
     * @param e
     */
    @Override


    public void actionPerformed(ActionEvent e) {
        //1.获得加数和被加数
        int n1 = Integer.parseInt(calculator.textField1.getText());
        int n2 = Integer.parseInt(calculator.textField2.getText());
        //2.将这个值+法运算后,放到第三个框
        calculator.textField3.setText(""+(n1+n2));
        //清除前两个框
        calculator.textField1.setText("");
        calculator.textField2.setText("");
    }
}

Demo03:内部类优化

package com.GUI.TestCale;

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 TesrCalc {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}
//计算器类
class Calculator extends Frame{
    //属性
    TextField textField1;
    TextField textField2;
    TextField textField3;

    //方法
    public void loadFrame(){
        textField1 = new TextField(10);
        textField2 = new TextField(10);
        textField3 = new TextField(20);
        //1个按钮
        Button button = new Button("=");
        button.addActionListener(new MyListener(this));
        //1个标签
        Label label = new Label("+");

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

        add(textField1);
        add(label);
        add(textField2);
        add(button);
        add(textField3);

        setVisible(true);
        pack();
        setResizable(false);
        winclose(this);
    }

    public  void  winclose(Frame frame){
        addWindowListener(new WindowAdapter() {
            /**
             * Invoked when a window is in the process of being closed.
             * The close operation can be overridden at this point.
             *
             * @param e
             */
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    //监听器类
    //内部类最大的好处,就是可以畅通无阻的访问外部的属性和方法!
    private class  MyListener implements ActionListener{
        //获取计算机这个对象,在一个类中组合另外一个类。
        Calculator calculator = null;

        public MyListener(Calculator calculator) {
            this.calculator = calculator;
        }

        /**
         * Invoked when an action occurs.
         *
         * @param e
         */
        @Override


        public void actionPerformed(ActionEvent e) {
            //1.获得加数和被加数
            int n1 = Integer.parseInt(calculator.textField1.getText());
            int n2 = Integer.parseInt(calculator.textField2.getText());
            //2.将这个值+法运算后,放到第三个框
            calculator.textField3.setText(""+(n1+n2));
            //清除前两个框
            calculator.textField1.setText("");
            calculator.textField2.setText("");
        }
    }

}

image

2.7、画笔

package com.GUI.Paint;

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

public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}
class MyPaint extends Frame{
    public  void loadFrame(){
        setVisible(true);
        setBounds(200,200,600,500);
        setResizable(false);
        winclose(this);
    }
    /**
     * {@inheritDoc}
     *
     * @param g
     * @since 1.7
     */
    @Override
    public void paint(Graphics g) {
        //画笔。需要有颜色,画笔可以画画
        g.setColor(Color.red);
        g.drawOval(100,100,100,100);
        //空心园
        g.fillOval(100,200,100,100);
        //实心园
        g.setColor(Color.blue);
        g.fillRect(150,250,200,200);
        //养成习惯,画笔用完,将他还原到最初的颜色
    }

    public  void  winclose(Frame frame){
        addWindowListener(new WindowAdapter() {
            /**
             * Invoked when a window is in the process of being closed.
             * The close operation can be overridden at this point.
             *
             * @param e
             */
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

image

2.8、鼠标监听

image

package com.GUI.Listener.MouseListener;

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.Array;
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;
    /**
     * {@inheritDoc}
     *
     * @param g
     * @since 1.7
     */
    @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);
        }
    }

    /**
     * Constructs a new instance of <code>Frame</code> that is
     * initially invisible.  The title of the <code>Frame</code>
     * is empty.
     *
     * @throws HeadlessException when
     *                           <code>GraphicsEnvironment.isHeadless()</code> returns <code>true</code>
     * @see GraphicsEnvironment#isHeadless()
     * @see Component#setSize
     * @see Component#setVisible(boolean)
     */
    public MyFrame(String title) {
        super(title);
        setBounds(200,200,400,300);
        setVisible(true);
        winClose(this);

        //存鼠标点击的点
        points = new ArrayList<>();

        //鼠标监听器,正对这个窗口
        this.addMouseListener(new MyMouseListener());
    }
    //添加一个点到界面上面
    public  void addPaint(Point point){
        points.add(point);

    }
    //关闭方法
    public  void winClose(Frame frame){
        addWindowListener(new WindowAdapter() {
            /**
             * Invoked when a window is in the process of being closed.
             * The close operation can be overridden at this point.
             *
             * @param e
             */
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    //内部类
    private  class  MyMouseListener extends MouseAdapter {
        //鼠标 按下 ,弹起,按住不放

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

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

image

2.9、窗口监听

package com.GUI.Listener.WindowListener;

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

public class TestWindowListener {
    public static void main(String[] args) {
        new WindwsListen();
    }
}
class  WindwsListen extends Frame {
    public  WindwsListen(){
        setBounds(200,200,200,200);
        setVisible(true);
        setBackground(Color.cyan);
        //addWindowListener(new MyWindowsListener());
        //匿名内部类
        this.addWindowListener(new WindowAdapter() {
            //打开
            @Override
            public void windowOpened(WindowEvent e) {
                System.out.println("windowOpened");
            }
            //关闭
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("windowClosing");
            }
            //最小化
            @Override
            public void windowIconified(WindowEvent e) {
                System.out.println("indowIconified");
            }
            //最小化还原
            @Override
            public void windowDeiconified(WindowEvent e) {
                System.out.println("windowDeiconified");
            }
            //激活
            @Override
            public void windowActivated(WindowEvent e) {
                WindwsListen windwsListen =(WindwsListen)e.getSource();
                windwsListen.setTitle("被激活了");
                System.out.println("windowActivated");

            }

        });
    }
//   class  MyWindowsListener extends WindowAdapter{
//        /**
//         * Invoked when a window is in the process of being closed.
//         * The close operation can be overridden at this point.
//         *
//         * @param e
//         */
//        @Override
//        public void windowClosing(WindowEvent e) {
//            setVisible(false);//隐藏
//            System.exit(0);//退出
//        }
//    }
}

image

2.10、键盘监听

package com.GUI.Listener.KeyListener;

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

public class TestKeyListener {
    public static void main(String[] args) {
        new MyFrame();
    }
}
class MyFrame extends Frame{
    MyFrame(){
        setBounds(1,2,300,400);
        setVisible(true);
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                //键盘按下的是哪一个键
                int keyCode = e.getKeyCode();
                System.out.println(keyCode);
                System.out.println(e.getKeyChar());
                if(keyCode ==KeyEvent.VK_UP){
                    System.out.println("你按下了上键");
                }
            }
        });
    }
}

3、Swing

3.1、窗口、容器

package com.GUI.SWING.JFrame;

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

/**
 * JFrame()无标题窗口
 * JFrame(String s)标题为s窗口
 * setBounds 初始位置以及大小
 * setSize大小
 * setVisible 是否可见,默认不可见
 * setResizable是否可调整大小,默认可调整大小
 * setDefauCloseOperation关闭图标的处理
 *      DO_NOTHING_ON_CLOSE什么也不做
 *      HIDE_ON_CLOSE隐藏当前窗口
 *      DISPOSE_ON_CLOSE隐藏当前窗口,并释放窗体占有的其他资源
 *      EXIT_ON_CLOSE结束窗体所在的应用程序
 * */
public class TestJFrame {
    //init();初始化
    public  void init(){
        //顶级窗口
        JFrame frame = new JFrame("这是一个JFrame窗口");
        frame.setVisible(true);
        frame.setBounds(200,200,500,300);
        frame.setResizable(false);
        //关闭事件
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //设置文字Jlabel
        JLabel Label = new JLabel("测试Label");
        frame.add(Label);

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

image

添加容器 修改颜色 标签居中

package com.GUI.SWING.JFrame;

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

public class JFrameDemo {
    public static void main(String[] args) {
        new MyJFrameDemo().init();
    }
}
class MyJFrameDemo extends JFrame{
    public  void init(){
        this.setVisible(true);
        this.setBounds(200,200,200,200);

        JLabel jLabel = new JLabel("测试");
        add(jLabel);

        //让文本居中
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);

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

    }
}

image

3.2弹窗、

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

package com.GUI.SWING.Dialog;

import javax.swing.*;
import javax.swing.plaf.basic.BasicArrowButton;
import java.awt.*;
import java.awt.event.ActionEvent;

//主窗口
public class TestDialog  extends JFrame {
    public TestDialog() {
        super("弹窗测试");
        this.setVisible(true);
        this.setBounds(new Rectangle(1000,300));
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

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

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

        //按钮监听
        button.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //打开弹窗
                new MyDialog();
            }
        });
        //按钮添加到容器里面
        container.add(button);
    }

    public static void main(String[] args) {
        new TestDialog();
    }
}
//弹窗的窗口
class MyDialog extends  JDialog{
    public  MyDialog(){
        this.setVisible(true);
        this.setBounds(100,100,300,200);

        Container container = this.getContentPane();
        container.setLayout(null);
        JLabel label = new JLabel("弹出测试");
        label.setBounds(0,0,200,100);
        container.add(label);

    }
}

image

3.3、标签

label

new JLabel("xxx");

图标标签

package com.GUI.SWING.Icon;

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

//图标,需要实现类,Frame继承
public class TestIcon extends JFrame implements Icon {
    private  int width;
    private  int height;
    //无参构造
    public TestIcon() {
    }

    public TestIcon(int width, int height) {
        this.width = width;
        this.height = height;
    }
    public  void init(){
        TestIcon testIcon = new TestIcon(15,15);
        //图标放在标签,也可以放在按钮上面
        JLabel jLabel = new JLabel("标签", testIcon, SwingConstants.CENTER);
        Container contentPane = getContentPane();
        contentPane.add(jLabel);
        this.setVisible(true);
        pack();
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new TestIcon().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;
    }
}

image

图片标签

package com.GUI.SWING.Icon;

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

public class TestImageIcon extends JFrame {
    public TestImageIcon() throws MalformedURLException {
        //获取图片地址
        URL url =new URL("https://iphoto.macsc.com/icon/icon/256/20210423/116308/4662171.png");
        JLabel jLabel = new JLabel("ImageIcon");

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

        jLabel.setSize(200,150);
        Container container = getContentPane();
        container.add(jLabel);

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

    public static void main(String[] args) throws MalformedURLException {
        new TestImageIcon();
    }
}

image

3.4、面板

Panel

package com.GUI.SWING.Panel;

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

public class JPanelDemo extends JFrame {
    public JPanelDemo()  {
        Container contentPane = this.getContentPane();
        contentPane.setLayout(new GridLayout(2,2,10,10));

        JPanel jPanel1 = new JPanel(new GridLayout(1,3));
        JPanel jPanel2 = new JPanel(new GridLayout(1,3));
        JPanel jPanel3 = new JPanel(new GridLayout(1,3));

        jPanel1.add(new Button("1-1"));
        jPanel1.add(new Button("1-2"));
        jPanel1.add(new Button("1-3"));
        jPanel2.add(new Button("2-1"));
        jPanel2.add(new Button("2-2"));
        jPanel2.add(new Button("2-3"));
        jPanel3.add(new Button("3-1"));
        jPanel3.add(new Button("3-2"));
        jPanel3.add(new Button("3-3"));

        contentPane.add(jPanel1);
        contentPane.add(jPanel2);
        contentPane.add(jPanel3);

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

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

image

ScrollPanel滚动条面板

package com.GUI.SWING.Panel;

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

public class JScrollDemo extends JFrame {
    public JScrollDemo() {
        Container contentPane = this.getContentPane();
//        contentPane.setLayout(new FlowLayout());
        //文本域
        JTextArea jTextArea = new JTextArea(20, 50);
        jTextArea.setText("输入文本:");

//        JTextField  jTextField =new JTextField("输入文本");
//        jTextField.setSize(20,50);
//        contentPane.add(jTextField);

        contentPane.add(jTextArea);

        //Scroll面板
//        JScrollPane jScrollPane = new JScrollPane(jTextField);
        JScrollPane jScrollPane = new JScrollPane(jTextArea);
        contentPane.add(jScrollPane);

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

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

image

3.5、按钮

图片按钮

package com.GUI.SWING.Button;

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

public class JButtonTest01 extends JFrame {
    public JButtonTest01()  {
        Container contentPane = this.getContentPane();
        //图片作为图标
        //        URL url =new URL("https://iphoto.macsc.com/icon/icon/256/20210423/116308/4662171.png");
        URL url = JButtonTest01.class.getResource("img.png");
        ImageIcon imageIcon = new ImageIcon(url);

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

        contentPane.add(button);

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

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

image

单选按钮

package com.GUI.SWING.Button;

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

public class JButtonTest02 extends JFrame {
    public JButtonTest02()  {
    Container contentPane = this.getContentPane();
    //单选框
    JRadioButton jRadioButton01 = new JRadioButton("Button01");
    JRadioButton jRadioButton02 = new JRadioButton("Button02");
    JRadioButton jRadioButton03 = new JRadioButton("Button03");
    //由于单选框只能选择一个,所以得分组,一个组中只能选择一个
    ButtonGroup buttonGroup = new ButtonGroup();
    buttonGroup.add(jRadioButton01);
    buttonGroup.add(jRadioButton02);
    buttonGroup.add(jRadioButton03);

//    jRadioButton01.setHorizontalAlignment(SwingConstants.CENTER);
//    jRadioButton02.setHorizontalAlignment(SwingConstants.CENTER);
//    jRadioButton03.setHorizontalAlignment(SwingConstants.CENTER);
    contentPane.add(jRadioButton01,BorderLayout.CENTER);
    contentPane.add(jRadioButton02,BorderLayout.NORTH);
    contentPane.add(jRadioButton03,BorderLayout.SOUTH);

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

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

image

复选按钮

package com.GUI.SWING.Button;

import com.oop.Demo05.B;

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

public class JButtonTest03  extends JFrame {
    public JButtonTest03()  {
        Container contentPane = this.getContentPane();

        //多选框
        JCheckBox jCheckBo1 = new JCheckBox("checkBo1");
        JCheckBox jCheckBo2 = new JCheckBox("checkBo2");
        JCheckBox jCheckBo3 = new JCheckBox("checkBo3");

        contentPane.add(jCheckBo1,BorderLayout.NORTH);
        contentPane.add(jCheckBo2,BorderLayout.CENTER);
        contentPane.add(jCheckBo3,BorderLayout.SOUTH);

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

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

image

3.6、列表

下拉框

package com.GUI.SWING.ComboBox;

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

public class TestComboBoxDemo01 extends JFrame {
    public TestComboBoxDemo01() {
        Container contentPane = getContentPane();

        JComboBox jComboBox = new JComboBox();

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

        jComboBox.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //监听选择
                //第几项
                System.out.println(jComboBox.getSelectedIndex());
                //选择标签名称
                System.out.println(jComboBox.getSelectedItem());

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

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

image

列表框

package com.GUI.SWING.ComboBox;

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

public class TestComboBoxDemo02 extends JFrame {
    public TestComboBoxDemo02() {
        Container contentPane = getContentPane();

        //生产列表的内容:
        //静态
        String[] contents ={"1","2","3"};
        //动态
        Vector vector = new Vector();
        
        //列表中需要放入内容
        //JList jList = new JList(contents);
        JList jList = new JList(vector);

        vector.add("01");
        vector.add("02");
        vector.add("03");
        contentPane.add(jList);
        this.setVisible(true);
        this.setSize(500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

image

3.7、文本框

文本框

package com.GUI.SWING.Text;

import com.GUI.SWING.ComboBox.TestComboBoxDemo02;

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

public class TestTextDemo01 extends JFrame {
    public TestTextDemo01() {
        Container contentPane = getContentPane();
        //contentPane.setLayout(null);

        JTextField jTextField1 = new JTextField("hello");
        JTextField jTextField2 = new JTextField("world");
        JTextField jTextField3 = new JTextField("!",20);

        contentPane.add(jTextField1,BorderLayout.NORTH);
        contentPane.add(jTextField2,BorderLayout.CENTER);
        contentPane.add(jTextField3,BorderLayout.SOUTH);

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

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

image

密码框

package com.GUI.SWING.Text;

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

public class TestTextPassword extends JFrame {
    public TestTextPassword() {
        Container contentPane = getContentPane();

        JPasswordField jPasswordField = new JPasswordField();
        jPasswordField.setEchoChar('*');
        contentPane.add(jPasswordField);

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

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

image

文本域

package com.GUI.SWING.Text;

import com.GUI.SWING.Panel.JScrollDemo;

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

public class TestTestArea extends JFrame {
    public TestTestArea() {
        Container contentPane = this.getContentPane();
        //文本域
        JTextArea jTextArea = new JTextArea(20, 50);
        jTextArea.setText("输入文本:");
        
        contentPane.add(jTextArea);
        
        JScrollPane jScrollPane = new JScrollPane(jTextArea);
        contentPane.add(jScrollPane);

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

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

image

3.8菜单

package com.GUI.SWING.Menu;


import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;
/**
 * JMenuBar创建菜单条
 *         public void setJMenuBar(JMenBar menubar);唯一
 * JMenu创建菜单
 *         JMenu(String s)创建名为s的菜单
 *         add(item)添加选项
 *         add(String s)添加指定的选项
 *         JMenuItem getItem(int n)得到指定索引处的菜单选项
 *         getItemCount()得到菜单选项数目
 * JmenuItem菜单项
 *          JMenuItem(string s) 构造有标题的菜单项
 *          JMenuItem(string s Icon icon)构造有标题和图标的菜单项
 *          setEnabled设置当前菜单是否可被选择
 *          getLabel得到菜单项的名字
 *          setAccelerator设置快捷键
 *          addSeparator添加分割线
 * */
public class 创建含由菜单的窗口 {
    public static void main(String[] args) {
    win win = new win("一个简单的窗口");
    }
}
class win extends JFrame{
    JMenuBar menuBar;
    JMenu menu;
    JMenuItem item1,item2;
    win(String s){
        setTitle(s);
        setSize(360,170);
        setLocation(120,120);
        setVisible(true);
        menuBar = new JMenuBar();
        menu = new JMenu("文件");
        item1 = new JMenuItem("打开",new ImageIcon("open.gif"));
        item2 = new JMenuItem("打开",new ImageIcon("save.gif"));
        item1.setAccelerator(KeyStroke.getKeyStroke('0'));
        item2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
        menu.add(item1);
        menu.addSeparator();
        menu.add(item2);
        menuBar.add(menu);
        setJMenuBar(menuBar);
        validate();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
}

image

posted @ 2022-01-06 14:48  项sir  阅读(29)  评论(0)    收藏  举报
标题