当前位置:首页 » 《随便一记》 » 正文

Java Swing开发基本组件_lflcodeplus的博客

2 人参与  2022年05月17日 10:35  分类 : 《随便一记》  评论

点击全文阅读


Java Swing开发基本组件

  • 1 Icon图标
  • 2 JButton按钮
  • 3 JLabel标签
  • 4 文本组件
    • 4.1 JTextField文本框
    • 4.2 JTextArea文本框
    • 4.1 JPasswordField文本框
  • 5 JComboBox组合框
  • 6 JList列表框
  • 7 JRadioButton单选按钮
  • 8 JCheckBox复选框
  • 8 计算器综合案例

1 Icon图标

在这里插入图片描述

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

public class ImageIconDemo extends JFrame {
    public ImageIconDemo() {
        super("ImageIcon图标");

        //创建ImageIcon图标
        ImageIcon qstIcon = new ImageIcon("images\\1.png");

        //设置窗体的Icon
        this.setIconImage(qstIcon.getImage());

        // 设定窗口大小(宽度400像素,高度300像素)
        this.setSize(400, 300);
        // 设定窗口左上角坐标(X轴200像素,Y轴100像素)
        this.setLocation(200, 100);
        // 设定窗口默认关闭方式为退出应用程序
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口可视(显示)
        this.setVisible(true);
    }

    public void paint(Graphics g) {
        //创建ImageIcon图标
        ImageIcon booksIcon = new ImageIcon("images\\1.jpg");
        //在窗体中画图标
        g.drawImage(booksIcon.getImage(), 0, 20, this);
        //显示图标的宽度和高度
        g.drawString("宽:" + booksIcon.getIconWidth() + "px,高:" + booksIcon.getIconHeight() + "px", 20, 210);
    }

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

2 JButton按钮

在这里插入图片描述

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JButtonDemo extends JFrame {
    // 声明组件
    private JPanel p;
    private JButton btnTxt, btnImg;
    private int num = 0;

    public JButtonDemo() {
        super("JButton类");

        // 实例化面板对象p(默认为流布局)
        p = new JPanel();

        // 实例化一个按钮对象,该按钮上显示文字
        btnTxt = new JButton("您点击了0次按钮!");
        // 实例化一个按钮对象,该按钮上显示图标
        btnImg = new JButton(new ImageIcon("images\\1.png"));

        // 注册监听
        btnTxt.addActionListener(new ActionListener() {
            // 行为事件处理方法
            public void actionPerformed(ActionEvent e) {
                // 统计点击按钮的此书
                num++;
                // 改变按钮的文本
                btnTxt.setText("您点击了" + num + "次按钮!");
            }
        });
        btnImg.addMouseListener(new MouseAdapter() {
            // 鼠标按下事件处理,按下左右键加载不同的图片
            public void mousePressed(MouseEvent e) {
                // 获取鼠标按键,判断是否是左键
                if (e.getButton() == MouseEvent.BUTTON1) {
                    // 改变按钮的Icon
                    btnImg.setIcon(new ImageIcon("images\\1.png"));
                }
                // 获取鼠标按键,判断是否是右键
                if (e.getButton() == MouseEvent.BUTTON3) {
                    // 改变按钮的Icon
                    btnImg.setIcon(new ImageIcon("images\\1.png"));
                }
            }
        });

        // 将按钮添加到面板中
        p.add(btnTxt);
        p.add(btnImg);

        // 将面板添加到窗体中
        this.add(p);

        // 设定窗口大小
        this.setSize(600, 640);
        // 设定窗口左上角坐标
        this.setLocation(200, 100);
        // 设定窗口默认关闭方式为退出应用程序
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口可视(显示)
        this.setVisible(true);
    }

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

在这里插入图片描述

3 JLabel标签

在这里插入图片描述

import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class JLabelDemo extends JFrame {
    // 声明组件
    private JPanel p;
    private JLabel lblTxt, lblImg, lblTxtImg;

    public JLabelDemo() {
        super("JLabel类");

        // 实例化面板对象p,面板布局是网格布局(3行1列)
        p = new JPanel(new GridLayout(3, 1));

        // 实例化一个标签对象,显示文字
        lblTxt = new JLabel("这是一个文本标签");
        // 实例化一个标签对象,显示图标
        lblImg = new JLabel(new ImageIcon("images\\2.png"));
        // 实例化一个标签对象,显示文本和标签
        lblTxtImg = new JLabel("商标", new ImageIcon("images\\2.png"),
                SwingConstants.CENTER);

        // 将按钮添加到面板中
        p.add(lblTxt);
        p.add(lblImg);
        p.add(lblTxtImg);

        // 将面板添加到窗体中
        this.add(p);

        // 设定窗口大小
        this.setSize(400, 300);
        // 设定窗口左上角坐标
        this.setLocation(200, 100);
        // 设定窗口默认关闭方式为退出应用程序
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口可视(显示)
        this.setVisible(true);
    }

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

4 文本组件

4.1 JTextField文本框

在这里插入图片描述

4.2 JTextArea文本框

在这里插入图片描述

4.1 JPasswordField文本框

在这里插入图片描述

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

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import javax.swing.JTextField;

//文本组件
public class TextComponentDemo extends JFrame {
    // 声明组件
    private JPanel p;
    private JLabel lblName, lblPwd, lblRePwd, lblAddress, lblMsg;
    // 声明一个文本框
    private JTextField txtName;
    // 声明两个密码框
    private JPasswordField txtPwd, txtRePwd;
    // 声明一个文本域
    private JTextArea txtAddress;

    private JButton btnReg, btnCancel;

    public TextComponentDemo() {
        super("注册新用户");
        // 创建面板,面板的布局为NULL
        p = new JPanel(null);

        // 实例化5个标签
        lblName = new JLabel("用户名");
        lblPwd = new JLabel("密      码");
        lblRePwd = new JLabel("确认密码");
        lblAddress = new JLabel("地      址");
        // 显示信息的标签
        lblMsg = new JLabel();
        // 设置标签的文字颜色是红色
        lblMsg.setForeground(Color.red);

        // 创建一个长度为20的文本框
        txtName = new JTextField(20);

        // 创建两个密码框,长度20
        txtPwd = new JPasswordField(20);
        txtRePwd = new JPasswordField(20);
        // 设置密码框显示的字符为*
        txtPwd.setEchoChar('*');
        txtRePwd.setEchoChar('*');

        // 创建一个文本域
        txtAddress = new JTextArea(20, 2);

        // 创建两个按钮
        btnReg = new JButton("注册");
        btnCancel = new JButton("清空");

        // 注册确定按钮的事件处理
        btnReg.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 设置信息标签为空,清空原来历史信息
                lblMsg.setText("");
                // 获取用户输入的用户名
                String strName = txtName.getText();
                if (strName == null || strName.equals("")) {
                    lblMsg.setText("用户名不能为空!");
                    return;
                }
                // 获取用户输入的密码
                String strPwd = new String(txtPwd.getPassword());
                if (strPwd == null || strPwd.equals("")) {
                    lblMsg.setText("密码不能为空!");
                    return;
                }
                // 获取用户输入的确认密码
                String strRePwd = new String(txtRePwd.getPassword());
                if (strRePwd == null || strRePwd.equals("")) {
                    lblMsg.setText("确认密码不能为空!");
                    return;
                }
                // 判断确认密码是否跟密码相同
                if (!strRePwd.equals(strPwd)) {
                    lblMsg.setText("确认密码与密码不同!");
                    return;
                }
                // 获取用户输入的地址
                String strAddress = new String(txtAddress.getText());
                if (strAddress == null || strAddress.equals("")) {
                    lblMsg.setText("地址不能为空!");
                    return;
                }

                lblMsg.setText("注册成功!");
            }
        });

        // 取消按钮的事件处理
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 清空所有文本组件中的文本
                txtName.setText("");
                txtPwd.setText("");
                txtRePwd.setText("");
                txtAddress.setText("");
                // 设置信息标签为空
                lblMsg.setText("");
            }
        });

        // 定位所有组件
        lblName.setBounds(30, 30, 60, 25);
        txtName.setBounds(95, 30, 120, 25);
        lblPwd.setBounds(30, 60, 60, 25);
        txtPwd.setBounds(95, 60, 120, 25);
        lblRePwd.setBounds(30, 90, 60, 25);
        txtRePwd.setBounds(95, 90, 120, 25);
        lblAddress.setBounds(30, 120, 60, 25);
        txtAddress.setBounds(95, 120, 120, 50);
        lblMsg.setBounds(60, 185, 180, 25);
        btnReg.setBounds(60, 215, 60, 25);
        btnCancel.setBounds(125, 215, 60, 25);

        // 将组件添加到面中
        p.add(lblName);
        p.add(txtName);
        p.add(lblPwd);
        p.add(txtPwd);
        p.add(lblRePwd);
        p.add(txtRePwd);
        p.add(lblAddress);
        p.add(txtAddress);
        p.add(lblMsg);
        p.add(btnReg);
        p.add(btnCancel);

        // 将面板添加到窗体中
        this.add(p);

        // 设定窗口大小
        this.setSize(280, 300);
        // 设定窗口左上角坐标(X轴200像素,Y轴100像素)
        this.setLocation(200, 100);
        // 设定窗口默认关闭方式为退出应用程序
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口可视(显示)
        this.setVisible(true);
    }

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

在这里插入图片描述

5 JComboBox组合框

在这里插入图片描述

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JComboBoxDemo extends JFrame {
    private JPanel p;
    private JLabel lblProvince, lblCity;
    private JComboBox cmbProvince, cmbCity;

    public JComboBoxDemo() {
        super("组合框联动");
        p = new JPanel();

        lblProvince = new JLabel("省份");
        lblCity = new JLabel("城市");

        // 创建组合框,并使用字符串数组初始化其选项列表
        cmbProvince = new JComboBox(new String[]{"北京", "上海", "山东", "安徽"});
        // 创建一个没有选项的组合框
        cmbCity = new JComboBox();

        // 注册监听
        cmbProvince.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                // 获取用户选中的选项下标
                int i = cmbProvince.getSelectedIndex();
                // 清空组合框中的选项
                cmbCity.removeAllItems();
                // 根据用户选择的不同省份,组合框中添加不同的城市
                switch (i) {
                    case 0:
                        cmbCity.addItem("北京");
                        break;
                    case 1:
                        cmbCity.addItem("上海");
                        break;
                    case 2:
                        cmbCity.addItem("济南");
                        cmbCity.addItem("青岛");
                        cmbCity.addItem("烟台");
                        cmbCity.addItem("潍坊");
                        cmbCity.addItem("威海");
                        break;
                    case 3:
                        cmbCity.addItem("合肥");
                        cmbCity.addItem("芜湖");
                        cmbCity.addItem("淮北");
                        cmbCity.addItem("蚌埠");
                        break;
                }
            }
        });

        p.add(lblProvince);
        p.add(cmbProvince);
        p.add(lblCity);
        p.add(cmbCity);

        // 将面板添加到窗体中
        this.add(p);

        // 设定窗口大小
        this.setSize(300, 200);
        // 设定窗口左上角坐标
        this.setLocation(200, 100);
        // 设定窗口默认关闭方式为退出应用程序
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口可视(显示)
        this.setVisible(true);
    }

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

在这里插入图片描述

6 JList列表框

在这里插入图片描述

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

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;

public class JListDemo extends JFrame {
    private JPanel p;
    private JList listLeft, listRight;
    private JButton btnOk, btnCancel;
    DefaultListModel model;

    public JListDemo() {
        super("JList列表");
        this.setLayout(new GridLayout(1, 3));
        // 创建组件
        p = new JPanel(new GridLayout(2, 1));

        // 创建列表,并使用一个字符串数组初始化其选项列表
        listLeft = new JList(
                new String[]{"看书", "写字", "画画", "爬山", "跑步", "游泳"});
        // 设置列表的选择模式为单选
        listLeft.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // 创建一个空的列表
        listRight = new JList();
        // 定义一个默认的列表值模型
        model = new DefaultListModel();
        // 设置列表的值模型
        listRight.setModel(model);

        btnOk = new JButton("——>");
        btnCancel = new JButton("<——");

        // 注册监听
        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 获取用户在左侧列表中选中的选项
                String strSelect = listLeft.getSelectedValue().toString();
                // 添加到右侧
                model.addElement(strSelect);
            }
        });

        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 移除用户在右侧列表选中的选项
                model.remove(listRight.getSelectedIndex());
            }
        });

        // 将组件添加到容器中
        p.add(btnOk);
        p.add(btnCancel);
        this.add(listLeft);
        this.add(p);
        this.add(listRight);

        // 设定窗口大小
        this.setSize(300, 200);
        // 设定窗口左上角坐标
        this.setLocation(200, 100);
        // 设定窗口默认关闭方式为退出应用程序
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口可视(显示)
        this.setVisible(true);
    }

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

在这里插入图片描述

7 JRadioButton单选按钮

在这里插入图片描述
使用单选按钮要经过两个步骤:
①实例化所有的JRadioButton单选按钮对象
②创建一个ButtonGroup按钮组对象,并用其add()方法将所有的单选按钮添加到该组中

//创建单选按钮
JRadioButton rbMale = new JRadioButton("男"true) ;
JRadioButton rbFemale = new JRadioButton("女") ;
//创建按钮组
ButtonGroup bg = new ButtonGroup() ;
//将rb1和rb2两个单选按钮添加到按钮组中,这两个单选按钮只能选中其一
bg.add (rbMale) ;
bg.add (rbFemale) ;

8 JCheckBox复选框

在这里插入图片描述

import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;


public class RadioCheckDemo extends JFrame {
    private JPanel p1, p2;
    private JLabel lblSex, lblLike;
    private JRadioButton rbMale, rbFemale;
    private ButtonGroup bg;
    private JCheckBox ckbRead, ckbNet, ckbSwim, ckbTour;

    public RadioCheckDemo() {
        super("单选和复选");
        this.setLayout(new GridLayout(2, 1));

        p1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        p2 = new JPanel(new FlowLayout(FlowLayout.LEFT));

        lblSex = new JLabel("性别:");
        lblLike = new JLabel("爱好:");
        // 创建单选按钮
        rbMale = new JRadioButton("男", true);
        rbFemale = new JRadioButton("女");
        // 创建按钮组
        bg = new ButtonGroup();
        // 将rb1和rb2两个单选按钮添加到按钮组中,这两个单选按钮只能选中其一
        bg.add(rbMale);
        bg.add(rbFemale);
        // 创建复选框
        ckbRead = new JCheckBox("阅读");
        ckbNet = new JCheckBox("上网");
        ckbSwim = new JCheckBox("游泳");
        ckbTour = new JCheckBox("旅游");

        // 性别相关的组件添加到p1子面板中
        p1.add(lblSex);
        p1.add(rbMale);
        p1.add(rbFemale);
        this.add(p1);

        // 爱好相关的组件添加到p2子面板中
        p2.add(lblLike);
        p2.add(ckbRead);
        p2.add(ckbNet);
        p2.add(ckbSwim);
        p2.add(ckbTour);
        this.add(p2);

        // 设定窗口大小
        this.setSize(300, 100);
        // 设定窗口左上角坐标
        this.setLocation(200, 100);
        // 设定窗口默认关闭方式为退出应用程序
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口可视(显示)
        this.setVisible(true);
    }

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

在这里插入图片描述

8 计算器综合案例

实现一个计算器功能,用户操作按钮或者键盘都能进行算术运算

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculator extends JFrame {
    // 声明一个文本栏控件,用于显示计算结果
    private JTextField txtResult;
    private JPanel p;
    // 定义一个字符串数组,将计算器中按钮的文字都放在该数组中
    private String name[] = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
            "3", "*", "0", ".", "=", "/"};
    // 声明一个按钮数组,该数组的长度以字符串数组的长度为准
    private JButton button[] = new JButton[name.length];
    // 定义一个存放计算结果的变量,初始为0
    private double result = 0;
    // 存放最后一个操作符,初始为“=”
    private String lastCommand = "=";
    // 标识是否是开始
    private boolean start = true;

    public Calculator() {
        super("计算器");
        // 实例化文本栏控件
        txtResult = new JTextField(20);
        // 设置文本框不是焦点状态
        txtResult.setFocusable(false);
        // 将文本栏控件放置在窗体框架的上方(北部)
        this.add(txtResult, BorderLayout.NORTH);
        // 实例化面板对象,同时设置此面板布局为4行4列的网格布局
        p = new JPanel(new GridLayout(4, 4));
        // 循环实例化按钮对象数组
        // 实例化按钮监听对象
        ButtonAction ba = new ButtonAction();
        // 实例化键盘监听对象
        KeyAction ka = new KeyAction();
        for (int i = 0; i < button.length; i++) {
            button[i] = new JButton(name[i]);
            // 注册监听
            button[i].addActionListener(ba);
            button[i].addKeyListener(ka);
            p.add(button[i]);
        }

        this.add(p, BorderLayout.CENTER);
        // 设定窗口大小
        this.setSize(200, 200);
        // 设定窗口左上角坐标
        this.setLocation(200, 100);
        // 设定窗口默认关闭方式为退出应用程序
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口可视(显示)
        this.setVisible(true);
    }

    // 计算
    public void calculate(double x) {
        if (lastCommand.equals("+"))
            result += x;
        else if (lastCommand.equals("-"))
            result -= x;
        else if (lastCommand.equals("*"))
            result *= x;
        else if (lastCommand.equals("/"))
            result /= x;
        else if (lastCommand.equals("="))
            result = x;
        // 将结果显示在文本栏
        txtResult.setText("" + result);
    }

    // 点击按钮监听
    private class ButtonAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String input = e.getActionCommand();
            // 点击操作符号按钮
            if (input.equals("+") || input.equals("-") || input.equals("*")
                    || input.equals("/") || input.equals("=")) {
                if (start) {
                    if (input.equals("-")) {
                        txtResult.setText(input);
                        start = false;
                    } else
                        lastCommand = input;
                } else {
                    calculate(Double.parseDouble(txtResult.getText()));
                    lastCommand = input;
                    start = true;
                }
            } else {
                if (start) {
                    txtResult.setText("");
                    start = false;
                }
                txtResult.setText(txtResult.getText() + input);
            }
        }
    }

    // 键盘监听
    private class KeyAction extends KeyAdapter {
        public void keyTyped(KeyEvent e) {
            char key = e.getKeyChar();
            // 敲击的键盘是数字
            if (key == '0' || key == '1' || key == '2' || key == '3'
                    || key == '4' || key == '5' || key == '6' || key == '7'
                    || key == '8' || key == '9' || key == '9') {
                if (start) {
                    txtResult.setText("");
                    start = false;
                }
                txtResult.setText(txtResult.getText() + key);
            }
            // 敲击的键盘是操作符号
            else if (key == '+' || key == '-' || key == '*' || key == '/'
                    || key == '=') {
                if (start) {
                    if (key == '-') {
                        txtResult.setText(String.valueOf(key));
                        start = false;
                    } else
                        lastCommand = String.valueOf(key);
                } else {
                    calculate(Double.parseDouble(txtResult.getText()));
                    lastCommand = String.valueOf(key);
                    start = true;
                }
            }
        }
    }

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

在这里插入图片描述


点击全文阅读


本文链接:http://zhangshiyu.com/post/40283.html

按钮  窗口  设定  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1