Java GUI编程

简介 是什么?怎么玩?如何运用? 组件 窗口 弹窗 面板 文本框 列表框 图片 按钮 监听事件 鼠标 键盘 GUI核心技术:AWT 、Swing 缺点:界面不...

简介

是什么?怎么玩?如何运用?

组件

  • 窗口

  • 弹窗

  • 面板

  • 文本框

  • 列表框

  • 图片

  • 按钮

  • 监听事件

  • 鼠标

  • 键盘

GUI核心技术:AWT 、Swing

缺点:界面不美观,需要jre环境!

优点:MVC架构,了解监听

目标:计网课设需要弄个Web服务器小工具

软件测试课设需要弄个正交表生成小工具

曾经为了方便,上学期用了pygame和pyqt5,如今又回来补Java的GUI了

AWT

介绍

awt: 抽象窗口工具包 (Abstract Window Toolkit )

提供很多类和接口,GUI

元素:窗口、按钮、文本框等

java.awt

image-20200413110932111

两个思路,

  1. ctrl + 左键 看源码,提高英语能力
  2. 对象加点 慢慢看方法

组件和容器

Frame

实例
import java.awt.*;

public class Main {

    public static void main(String[] args) {
        Frame frame = new Frame("第一个窗口");
        frame.setSize(300,300);//窗口大小
        frame.setBackground(Color.blue);//背景颜色
        frame.setLocation(300,100);//出现时左上角在屏幕上的坐标
        //new Color(180, 167,0); //颜色点进去看源码
        frame.setResizable(true);//是否可改变窗体大小

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

image-20200413114654988

出现问题:窗口关不掉!得回到IDE手动停止程序

封装

将上面的简单窗口封装成自己的类

封装类

import java.awt.*;

public class MyFrame extends Frame {
    private static int id = 0; //用于统计窗口
    public  MyFrame(int x, int y, int w, int h,Color color){
        super("Frame"+(++id));
        setBackground(color);
        setBounds(x,y,w,h);
        setVisible(true);
    }

}

主方法调用

import java.awt.*;

public class TestFrame {
    public static void main(String[] args) {
        MyFrame myFrame1 = new MyFrame(300,100,300,300,Color.red);
        MyFrame myFrame2 = new MyFrame(600,100,300,300,Color.yellow);
        MyFrame myFrame3 = new MyFrame(300,400,300,300,Color.blue);
        MyFrame myFrame4 = new MyFrame(600,400,300,300,Color.green);

    }
}

image-20200413120107256

面板Panel

package com.ljh;

import javafx.scene.layout.Pane;

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

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Panel panel = new Panel();
        //设置布局
        frame.setLayout(null); //少了这行frame就会置顶,覆盖其他元素
        frame.setBounds(300,100,300,300);
        frame.setBackground(Color.red);

        //设置面板
        panel.setBackground(Color.cyan);
        panel.setBounds(100,100,200,200);

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

        frame.setVisible(true);

        //监听关闭事件,通过窗口监听适配器重写关闭方法
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

image-20200413141810897

布局管理器

流式布局
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();
        frame.setSize(400,400);

        //设置流式布局
        //frame.setLayout(new FlowLayout());//默认居中
        //frame.setLayout(new FlowLayout(FlowLayout.LEFT));//靠左
        frame.setLayout(new FlowLayout(FlowLayout.RIGHT));//靠右

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

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

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

image-20200413143256299

东西南北中(边界布局)

image-20200413143234547

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("东西南北中");
        frame.setBounds(300,200,400,400);
        //按钮组
        Button east = new Button("East");
        Button west = new Button("West");
        Button south = new Button("South");
        Button north = new Button("North");
        Button center = new Button("Center");

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

        frame.setVisible(true);

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

image-20200413144140737

表格布局
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("东西南北中");
        frame.setBounds(300,200,400,400);

        //设置表格布局
        frame.setLayout(new GridLayout(2,2));

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

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

        frame.setVisible(true);

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

image-20200413144745980

作业Demo

通过前面学习的知识,实现下图布局

image-20200413152003983

分析:

首先Frame用表格布局(GridLayout)分成上半部panel1和下半部panel2,

上下两半分别用左中右布局(BorderLayout),

上部分的中央panel3用表格布局(GridLayout)两行一列

下部分的中央panel4用表格布局(GridLayout)两行两列

代码

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

public class LayoutWork {
    public static void main(String[] args) {
        Frame frame = new Frame("作业1");
        frame.setBounds(300,200,600,400);

        Panel panel1 = new Panel();//上半边
        Panel panel2 = new Panel();//下半边
        Panel panel3 = new Panel();//上中央
        Panel panel4 = new Panel();//下中央

        //设置表格布局
        frame.setLayout(new GridLayout(2,1));
        panel1.setLayout(new BorderLayout());
        panel2.setLayout(new BorderLayout());
        panel3.setLayout(new GridLayout(2,1));
        panel4.setLayout(new GridLayout(2,2));

        //组件 按钮
        Button button0 = new Button("button0");
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        Button button4 = new Button("button4");
        Button button5 = new Button("button5");
        Button button6 = new Button("button6");
        Button button7 = new Button("button7");
        Button button8 = new Button("button8");
        Button button9 = new Button("button9");

        //自顶向下添加
        frame.add(panel1);
        frame.add(panel2);
        panel1.add(button1,BorderLayout.WEST);
        panel1.add(panel3,BorderLayout.CENTER);
        panel1.add(button4,BorderLayout.EAST);
        panel3.add(button2);
        panel3.add(button3);
        panel2.add(button5,BorderLayout.WEST);
        panel2.add(panel4,BorderLayout.CENTER);
        panel4.add(button6);
        panel4.add(button7);
        panel4.add(button8);
        panel4.add(button9);
        panel2.add(button0,BorderLayout.EAST);


        frame.setVisible(true);

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

布局总结:

  1. Frame是顶级窗口
  2. Panel无法单独显示,必须加到某容器中
  3. 布局管理器:流式 边界 表格
  4. 大小,定位,背景颜色,可见性,监听关闭事件

事件监听

当某件事情发生的时候,干什么?

addActionListener(事件);

package com.action;

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 TestButton {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setBounds(300,200,300,200);
        frame.setVisible(true);
        Button button1 = new Button("button");
        button1.addActionListener(new myActionListener());

        frame.add(button1);
        windowClose(frame);

    }

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

}
// 事件监听实现类
class myActionListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("点击");
    }
}

监听输入框

新思想,在main函数里面只有调用启动的语句,不写其他东西。

package com.action;

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 TestActionEvet {
    public static void main(String[] args) {
        new MyFrame();
    }
}

class MyFrame extends Frame{
    public MyFrame(){
        TextField textField = new TextField(5);
        textField.setEchoChar('*');//密码类型隐藏显示
        this.add(textField);
        textField.addActionListener(new MyActionListener());
        this.setVisible(true);
        this.pack();
        WindowClose(this);
    }

    //  关闭窗体事件
    public 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) {
        TextField textField = (TextField) e.getSource();//e.getSource是个Object对象
        System.out.println(textField.getText());
        textField.setText("");//获取文本框内容并设置为空
    }
}


简易计算器

用过传参的代码

package com.action;

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

/**
 * 计算器类1 开始是通过传参是形式,传给事件监听类操控文本框。
 */
public class Calculate1 extends Frame {
    TextField num1, num2, num3;

    public Calculate1() {
        //创建自己,一个窗体
        //3个文本框
        num1 = new TextField();
        num2 = new TextField();
        num3 = new TextField();
        Button button = new Button("=");

        setLayout(new FlowLayout());
        add(num1);
        add(new Label("+"));
        add(num2);
        add(button);
        add(num3);

        button.addActionListener(new MyCalculate1Listener(num1, num2, num3));
        pack();
        setVisible(true);
        WindowClose(this);

    }

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

class MyCalculate1Listener implements ActionListener {
    private TextField num1, num2, num3;

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

    @Override
    public void actionPerformed(ActionEvent e) {
        int n1 = Integer.parseInt(num1.getText());
        int n2 = Integer.parseInt(num2.getText());
        num3.setText("" + (n1 + n2));
    }
}


通过组合的方式 (面向对象)

package com.action;

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

/**
 * 计算器类2 通过组合的方式,传给事件监听类一个实例化的图形类,可以直接操作它的属性
 */
public class Calculate2 extends Frame { 
    public TextField num1,num2,num3;

    public void loadFrame(){
        //3个文本框
        num1 = new TextField();
        num2 = new TextField();
        num3 = new TextField();
        Button button = new Button("=");

        setLayout(new FlowLayout());
        add(num1);
        add( new Label("+")) ;
        add(num2);
        add(button);
        add(num3);

        button.addActionListener(new MyCalculate2Listener1(this));
        pack();
        setVisible(true);
        WindowClose(this);

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

class MyCalculate2Listener1 implements ActionListener {
    private Calculate2 cal;//组合!!把别的类丢进来用
    public MyCalculate2Listener1(Calculate2 cal){
        this.cal = cal;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int n1 = Integer.parseInt(cal.num1.getText());
        int n2 = Integer.parseInt(cal.num2.getText());
        cal.num3.setText(""+(n1+n2));
    }
}

内部类的方式

  • 更好的封装
  • 最大的好处,可以取到外部类的属性和方法!
package com.action;

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 Calculate3  extends Frame {
    public TextField num1,num2,num3;

    public void loadFrame(){
        //3个文本框
        num1 = new TextField();
        num2 = new TextField();
        num3 = new TextField();
        Button button = new Button("=");

        setLayout(new FlowLayout());
        add(num1);
        add( new Label("+")) ;
        add(num2);
        add(button);
        add(num3);

        button.addActionListener(new MyCalculate3Listener());
        pack();
        setVisible(true);
        WindowClose(this);

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

    //内部类可以随便对外部类的属性进行操作
    class MyCalculate3Listener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());
            num3.setText(""+(n1+n2));
        }
    }
}


画笔paint

鼠标监听

image-20200426190258357

package com.paint;

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

//实现鼠标画点
public class TestPaint {
    public static void main(String[] args) {
        new MyPaint("画点");
    }

}
//我的画笔类
class MyPaint extends Frame{
    private ArrayList points;
    public MyPaint(String title){
        super(title);
        this.setBounds(200,200,300,300);


        points = new ArrayList<>(); //存点集合
        //在窗口上监听鼠标事件
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                Frame frame = (Frame)e.getSource();
                points.add(new Point(e.getX(), e.getY())) ;
                frame.repaint();
            }
        });
        
        
        this.setVisible(true);
    }
    public void paint (Graphics g){
        Iterator iterator = points.iterator();
        while(iterator.hasNext())
        {
            Point drawPoint = (Point)iterator.next();
            //getGraphics().setColor(Color.black);
            g.fillOval(drawPoint.x,drawPoint.y,5,5);

        }
    }
}

窗口监听

package com.action;

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(){
        this.setBounds(200,200,500,500);
        this.addWindowListener(
            //匿名内部类
            new WindowAdapter() {
                @Override
                public void windowOpened(WindowEvent e) {
                    System.out.println("窗口打开");
                }

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

                @Override
                public void windowClosed(WindowEvent e) {
                    System.out.println("窗口已经关闭");
                }

                @Override
                public void windowIconified(WindowEvent e) {
                    System.out.println("最小化");
                }

                @Override
                public void windowDeiconified(WindowEvent e) {
                    System.out.println("从最小化出现");
                }

                @Override
                public void windowActivated(WindowEvent e) {
                    System.out.println("窗口激活");
                    WindowFrame frame = (WindowFrame) e.getSource();
                    frame.setTitle("您回来啦");
                }

                @Override
                public void windowDeactivated(WindowEvent e) {
                    System.out.println("窗口离开");
                    WindowFrame frame = (WindowFrame) e.getSource();
                    frame.setTitle("你快回来!");
                }

                @Override
                public void windowStateChanged(WindowEvent e) {
                    System.out.println("状态改变");
                }

                @Override
                public void windowGainedFocus(WindowEvent e) {
                    super.windowGainedFocus(e);
                }

                @Override
                public void windowLostFocus(WindowEvent e) {
                    System.out.println("窗口失去焦点");
                }
            });
        setVisible(true);
    }
}

键盘监听

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(){
        this.setBounds(200,200,200,200);
        this.setVisible(true);

        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                // 获取对应字符的ASCII值
                System.out.println(e.getKeyCode());
                if (e.getKeyCode() == KeyEvent.VK_UP){
                    System.out.println("按下了方向上键");
                }
            }
        });
    }
}

Swing

窗口

package Swing;

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

public class JFrameDemo {

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

class MyJFrame extends JFrame {
    public void init() {
        this.setTitle("Swing");
        this.setLayout(new FlowLayout());
        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setBackground(Color.cyan);
//        Container contentPane = this.getContentPane();
//        contentPane.setBackground(Color.cyan);

        JPanel jPanel = new JPanel();
        // 流式布局时根据内容变化大小
        jPanel.setBounds(50, 50, 100, 100);
        jPanel.setBackground(Color.yellow);
        
       
        JLabel jLabel = new JLabel();
        jLabel.setText("hello world");
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        
        this.add(jPanel);
        jPanel.add(jLabel);

        // Swing已经写好了默认关闭窗口的方法!
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在swing中的容器和awt不一样,导致这里的this.setBackground(Color.red);不生效。

image-20200514095909377

应该先获取一个容器,再给容器设置背景颜色。

this.setBackground(Color.red);
改成:
Container contentPane = this.getContentPane();
contentPane.setBackground(Color.red);

image-20200514095945019

面板

package swing;

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

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

    public void init() {
        Container container = this.getContentPane();
        // 大容器装两行两列的面板,之间有间距。
        container.setLayout(new GridLayout(2,2,10,10));

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

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

        container.add(jPanel1);
        container.add(jPanel2);
        container.add(jPanel3);
        container.add(jPanel4);

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

image-20200514153540599

JScroll面板

package swing;

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

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

    public void init() {
        Container container = this.getContentPane();

        JTextArea textArea = new JTextArea(20,50);
        textArea.setText("当内容过多时会常出现滚动条");

        // JScroll
        JScrollPane scrollPane = new JScrollPane(textArea);
		// 调整区域
        // scrollPane.setSize(100,100);

        container.add(scrollPane);

        this.setTitle("滚动");
        this.setBounds(100, 100, 500, 500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}


image-20200514154816038

弹窗

默认就带有关闭事件。

package Swing;

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

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

    public DialogDemo() {
        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        // JFrame容器,放东西
        Container container = this.getContentPane();
        // 绝对布局
        container.setLayout(null);
        JButton button = new JButton("点击弹窗");
        // 用坐标定位组件的位置
        button.setBounds(30,30,100,100);

        container.add(button);

        // 点击按钮时弹出另个窗口
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 跳出弹窗
                new MyDialog("标题","打印消息");
            }
        });
    }
}


class MyDialog extends JDialog {
    // 弹窗自带关闭事件
    public MyDialog(String title, String msg) {
        this.setTitle(title);
        this.setVisible(true);
        this.setBounds(350,350,200,200);

        JLabel label = new JLabel(msg);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        Container container = this.getContentPane();
        container.add(label);
    }
}

image-20200514105113583

标签

标签中放图标

package Swing;

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

public class IconDemo extends JFrame implements Icon {
    private int width;
    private int height;

    public static void main(String[] args) {
        new IconDemo(15, 15);
    }

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

        this.setTitle("图标icon");
        this.setVisible(true);
        this.setBounds(100,100,300,300);
        // 图标放在标签上,也可以放到按钮上~
        JLabel label = new JLabel("icon", this, SwingConstants.CENTER);
        JButton jButton = new JButton("icon", this);
        Container container = this.getContentPane();
        container.add(label);
        // container.add(jButton);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillOval(x,y,width,height);
    }

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

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


image-20200514151416469

标签中放图片

package swing;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;

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

    public void init() {
        this.setTitle("图片标签");
        this.setVisible(true);
        this.setBounds(100, 100, 500, 500);

        JLabel jLabel = new JLabel();
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);

        // 先加入标签再设置图片图标
        Container container = this.getContentPane();
        container.add(jLabel);

        // 通过源代码文件的目录获取路径
        URL url = ImageIconTest.class.getResource("white.jpg");
        ImageIcon imageIcon = new ImageIcon(url);
        System.out.println(imageIcon);
        jLabel.setIcon(imageIcon);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        // 创建图片对象做左上角图标icon
        Image image = null;
        try {
            image = ImageIO.read(url);
            this.setIconImage(image);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


image-20200514151906698

按钮

图片按钮

package swing;

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

public class JbuttonDemo01 extends JFrame {
    public static void main(String[] args) {
        new JbuttonDemo01().init();

    }

    public void init() {
        Container container = this.getContentPane();
        // 将一张图片转成图标
        URL url = JbuttonDemo01.class.getResource("white.jpg");
        Icon icon = new ImageIcon(url);

        // 把图标放在按钮上
        JButton jButton = new JButton(icon);
        container.add(jButton);
        jButton.setToolTipText("这里可以提示文字");


        this.setTitle("图片按钮");
        this.setBounds(100,100,500,500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

}


image-20200514165350915

复选框

package swing;

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

/**
 * 复选框,JCheckBox
 */
public class JbuttonDemo02 extends JFrame {
    public static void main(String[] args) {
        new JbuttonDemo02().init();

    }

    public void init() {
        Container container = this.getContentPane();
        container.setLayout(new FlowLayout());

        container.add(new JLabel("请选择你喜欢的水果,可以选多个。"));
        JCheckBox checkBox1 = new JCheckBox("葡萄");
        JCheckBox checkBox2= new JCheckBox("草莓");
        JCheckBox checkBox3 = new JCheckBox("芒果");

        container.add(checkBox1);
        container.add(checkBox2);
        container.add(checkBox3);

        this.setTitle("复选框");
        this.setBounds(100,100,500,500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

}

image-20200514171936995

单选框

package swing;

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

/**
 * 单选框,多选一
 * JRadioButton 圆点选区
 * 将多个复选加到一个组中ButtonGroup
 */
public class JbuttonDemo03 extends JFrame {
    public static void main(String[] args) {
        new JbuttonDemo03().init();

    }

    public void init() {
        Container container = this.getContentPane();
        container.setLayout(new FlowLayout());

        container.add(new JLabel("你所属的年级是"));
        JRadioButton jRadioButton1 = new JRadioButton("大一");
        JRadioButton jRadioButton2 = new JRadioButton("大二");
        JRadioButton jRadioButton3 = new JRadioButton("大三");
        JRadioButton jRadioButton4 = new JRadioButton("大四");

        // 由于单选框只能选择一个,分组
        // 一个组只能选一个
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(jRadioButton1);
        buttonGroup.add(jRadioButton2);
        buttonGroup.add(jRadioButton3);
        buttonGroup.add(jRadioButton4);

        container.add(jRadioButton1);
        container.add(jRadioButton2);
        container.add(jRadioButton3);
        container.add(jRadioButton4);

        this.setTitle("多选一");
        this.setBounds(100, 100, 500, 500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

}

image-20200514171848866

列表

下拉框

package swing;

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

/**
 * 下拉框 JComboBox
 */
public class JcomboxDemo extends JFrame {
    public static void main(String[] args) {
        new JcomboxDemo().init();
    }
    public void init() {
        this.setTitle("下拉框");
        JPanel jPanel = new JPanel();
        jPanel.setBounds(50,50,100,100);


        JComboBox status = new JComboBox();
        status.addItem("大英");
        status.addItem("高数");
        status.addItem("大物");

        jPanel.add(status);
        Container container = this.getContentPane();
        container.add(jPanel);



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


image-20200515000556914

列表框

package swing;

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

/**
 * 列表框可以自动遍历数组内容
 * JList
 */
public class JListDemo extends JFrame{
    public static void main(String[] args) {
        new JListDemo().init();
    }
    public void init() {
        this.setTitle("列表框");
        
        // 生成列表内容
        String[] contents = {"成员1", "成员2", "成员3"};
        // 将列表内容添加到列表框
        JList list = new JList(contents);
        
        Container container = this.getContentPane();
        container.add(list);
        this.setBounds(100,100,500,500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}


image-20200515001215123

应用场景

  • 选择地区,或一些单个选项
  • 列表展示信息,一般是动态扩容~

文本框

package swing;

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

/**
 * 文本框 JTextField
 * 密码框 JPasswordField
 * 文本域 JTextArea
 */
public class TextDemo extends JFrame {
    public static void main(String[] args) {
        new TextDemo().init();
    }
    public void init(){
        this.setTitle("文本");
        Container container = this.getContentPane();
        container.setLayout(null);
        JTextField jTextField = new JTextField("文本框");
        jTextField.setBounds(50,50,100,20);
        // 密码框
        JPasswordField jPasswordField = new JPasswordField();
        jPasswordField.setBounds(50, 200, 100, 20);
        // 也可以手动设置
        // jPasswordField.setEchoChar('+');

        JTextArea jTextArea = new JTextArea();
        jTextArea.setBounds(50, 300, 100, 80);

        container.add(jTextField);
        container.add(jPasswordField);
        container.add(jTextArea);

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


image-20200515100531281

窗体自适应

package swing;

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

/**
 * 通过当前屏幕显示合适大小的窗体
 */
public class WindowSize {
    public static void main(String[] args) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = (int) screenSize.getWidth();
        int screenHeight = (int) screenSize.getHeight();
        System.out.println("屏幕宽度:" + screenWidth + ",屏幕高度:" + screenHeight);

        // 窗体与屏幕占比
        double percent = 0.5;
        int frameWidth = (int) (screenWidth * percent);
        int frameHeight = (int) (screenHeight * percent);
        System.out.println("窗体宽度:" + frameWidth + ",窗体高度:" + frameHeight);


        int x = (screenWidth - frameWidth) / 2;
        int y = (screenHeight - frameHeight) / 2;
        System.out.println("相对坐标x:" + x + ",y:" + y);

        JFrame jFrame = new JFrame();
        jFrame.setVisible(true);
        jFrame.setBounds(x,y,frameWidth,frameHeight);
    }


}


学习链接

  • 发表于 2020-05-15 12:40
  • 阅读 ( 151 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除