Swing基本组件的用法(一)

语雀笔记:https://www.yuque.com/huangzhanqi/rhwoir/paaoghdyv0tgksk1icon-default.png?t=N7T8https://www.yuque.com/huangzhanqi/rhwoir/paaoghdyv0tgksk1Java图形化界面: Java图形化界面学习demo与资料 (gitee.com)icon-default.png?t=N7T8https://gitee.com/zhanqi214/java-graphical-interface

Swing组件层次

Swing组件继承体系图:

大部分Swing 组件都是 JComponent抽象类的直接或间接子类(并不是全部的 Swing 组件),JComponent 类定义了所有子类组件的通用方法 ,JComponent 类是 AWT 里 java.awt. Container 类的子类 ,这也是 AWT 和 Swing 的联系之一。 绝大部分 Swing 组件类继承了 Container类,所以Swing 组件都可作为 容器使用 ( JFrame继承了Frame 类)。

Swing组件和AWT组件的对应关系:

大部分情况下,只需要在AWT组件的名称前面加个J,就可以得到其对应的Swing组件名称,但有几个例外:

  1. JComboBox: 对应于 AWT 里的 Choice 组件,但比 Choice 组件功能更丰富 。
    1. JFileChooser: 对应于 AWT 里的 FileDialog 组件 。
      1. JScrollBar: 对应于 AWT 里的 Scrollbar 组件,注意两个组件类名中 b 字母的大小写差别。
      2. JCheckBox : 对应于 AWT 里的 Checkbox 组件, 注意两个组件类名中 b 字母的大小 写差别 。
      3. JCheckBoxMenultem: 对应于 AWT 里的 CheckboxMenuItem 组件,注意两个组件类名中 b字母的大小写差别。

Swing组件按照功能来分类:

  1. 顶层容器: JFrame、JApplet、JDialog 和 JWindow 。
    1. 中间容器: JPanel 、 JScrollPane 、 JSplitPane 、 JToolBar 等 。
    2. 特殊容器:在用户界面上具有特殊作用的中间容器,如 JIntemalFrame 、 JRootPane 、 JLayeredPane和 JDestopPane 等 。
    3. 基本组件 : 实现人机交互的组件,如 JButton、 JComboBox 、 JList、 JMenu、 JSlider 等 。
    4. 不可编辑信息的显示组件:向用户显示不可编辑信息的组件,如JLabel 、 JProgressBar 和 JToolTip等。
    5. 可编辑信息的显示组件:向用户显示能被编辑的格式化信息的组件,如 JTable 、 JTextArea 和JTextField 等 。
    6. 特殊对话框组件:可以直接产生特殊对话框的组件 , 如 JColorChooser 和 JFileChooser 等。

AWT组件的Swing实现

Swing 为除 Canvas 之外的所有 AWT 组件提供了相应的实现,Swing 组件比 AWT 组件的功能更加强大。相对于 AWT 组件, Swing 组件具有如下 4 个额外的功能 :

  1. 可以为 Swing 组件设置提示信息。使用 setToolTipText()方法,为组件设置对用户有帮助的提示信息 。
  2. 很多 Swing 组件如按钮、标签、菜单项等,除使用文字外,还可以使用图标修饰自己。为了允许在 Swing 组件中使用图标, Swing为Icon 接口提供了 一个实现类: Imagelcon ,该实现类代表一个图像图标。
  3. 支持插拔式的外观风格。每个 JComponent 对象都有一个相应的 ComponentUI 对象,为它完成所有的绘画、事件处理、决定尺寸大小等工作。 ComponentUI 对象依赖当前使用的 PLAF , 使用 UIManager.setLookAndFeel()方法可以改变图形界面的外观风格 。
  4. 支持设置边框。Swing 组件可以设置一个或多个边框。 Swing 中提供了各式各样的边框供用户边 用,也能建立组合边框或自己设计边框。 一种空白边框可以用于增大组件,同时协助布局管理器对容器中的组件进行合理的布局。

每个 Swing 组件都有一个对应的UI 类,例如 JButton组件就有一个对应的 ButtonUI 类来作为UI代理 。每个 Swing组件的UI代理的类名总是将该 Swing 组件类名的 J 去掉,然后在后面添加 UI 后缀 。 UI代理类通常是一个抽象基类 , 不同的 PLAF 会有不同的UI代理实现类 。 Swing 类库中包含了几套UI代理,分别放在不同的包下, 每套UI代理都几乎包含了所有 Swing组件的 ComponentUI实现,每套这样的实现都被称为一种PLAF 实现 。以 JButton 为例,其 UI 代理的继承层次下图:

如果需要改变程序的外观风格, 则可以使用如下代码:

//容器:
JFrame jf = new JFrame();

try {

    //设置外观风格
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

    //刷新jf容器及其内部组件的外观
    SwingUtilities.updateComponentTreeUI(jf);
} catch (Exception e) {
    e.printStackTrace();
}

案例:

使用Swing组件,实现下图中的界面效果:

演示代码:

package swing;

import awt.day01.Utils;

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

public class SwingComponentDemo {

    private JFrame frame = new JFrame("Swimg测试");
    private JMenuBar jMenuBar = new JMenuBar();
    private JMenu fileMenu = new JMenu("文件");
    private JMenuItem openFile = new JMenuItem("打开文件");
    private JMenuItem newFile = new JMenuItem("新建文件");
    private JMenuItem saveFile = new JMenuItem("保存文件");
    private JMenuItem exit = new JMenuItem("退出",new ImageIcon("src/swing/img/component/exit.png"));
    private JMenu editMenu = new JMenu("编辑");
    private JCheckBoxMenuItem autoWrap = new JCheckBoxMenuItem("自动换行");
    private JMenuItem copy = new JMenuItem("复制",new ImageIcon("src/swing/img/component/copy.png"));
    private JMenuItem paste = new JMenuItem("粘贴",new ImageIcon("src/swing/img/component/paste.png"));
    private JMenu formate = new JMenu("格式");
    private JMenuItem annotation = new JMenuItem("注释");
    private JMenuItem deAnnotation = new JMenuItem("取消注释");
    private Box xBox = new Box(BoxLayout.X_AXIS);
    private Box yBox = new Box(BoxLayout.Y_AXIS);
    private Box vBox = new Box(BoxLayout.Y_AXIS);
    private JPanel panel1 = new JPanel();
    private JPanel panel2 = new JPanel();
    private String[] color = {"红色", "绿色", "蓝色"};
    private JComboBox<String> jComboBox = new JComboBox<>(color);
    private JList<String> jList = new JList<>(color);
    private JTextArea textArea = new JTextArea(8, 20);
    private JRadioButton male = new JRadioButton("男", true);
    private JRadioButton female = new JRadioButton("女", false);
    private ButtonGroup genderGroup=new ButtonGroup();
    private JCheckBox isMarried = new JCheckBox("是否已婚?", false);
    private JTextField textField = new JTextField(30);
    private JButton ok = new JButton("确定", new ImageIcon("src/swing/img/component/ok.png"));
    private JPopupMenu popupMenu = new JPopupMenu();
    private ButtonGroup styleGroup = new ButtonGroup();
    JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal 风格",true);
    JRadioButtonMenuItem nimbusItem = new JRadioButtonMenuItem("Nimbus 风格",true);
    JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows 风格",true);
    JRadioButtonMenuItem classicItem = new JRadioButtonMenuItem("Windows 经典风格",true);
    JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif 风格",true);
//    JScrollPane scrollPane = new JScrollPane();
    public void init(){
        //菜单栏
        frame.setJMenuBar(jMenuBar);
        frame.setBackground(Color.GRAY);
        jMenuBar.add(fileMenu);
        jMenuBar.add(editMenu);
        fileMenu.add(openFile);
        fileMenu.add(newFile);
        fileMenu.add(saveFile);
        fileMenu.add(exit);
        editMenu.add(autoWrap);
        editMenu.add(copy);
        editMenu.add(paste);
        editMenu.add(formate);
        formate.add(annotation);
        formate.add(deAnnotation);
        annotation.setToolTipText("将程序代码注释起来");
        exit.addActionListener(e -> System.exit(0));
        newFile.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_MASK));
        newFile.addActionListener(e -> textArea.append("用户点击了新建文件"));
        saveFile.setAccelerator(KeyStroke.getKeyStroke('S',InputEvent.CTRL_MASK));
        saveFile.addActionListener(this::textAreaClear);
        //X轴box组装
        frame.add(xBox);
        xBox.add(yBox);
        xBox.add(jList);

        //Y轴box组装
        yBox.add(vBox);
        vBox.add(textArea);
        vBox.add(panel1);
        vBox.add(panel2);
        panel1.add(jComboBox);
        genderGroup.add(male);
        genderGroup.add(female);
        panel1.add(male);
        panel1.add(female);
        panel1.add(isMarried);
        panel2.add(textField);
        panel2.add(ok);

        //右键菜单组装
        this.buildRightMenu();


        Utils.setJFrame(frame);
    }

    private void buildRightMenu() {
        textArea.add(popupMenu);
        popupMenu.add(metalItem);
        popupMenu.add(nimbusItem);
        popupMenu.add(windowsItem);
        popupMenu.add(classicItem);
        popupMenu.add(motifItem);
        styleGroup.add(metalItem);
        styleGroup.add(nimbusItem);
        styleGroup.add(windowsItem);
        styleGroup.add(classicItem);
        styleGroup.add(motifItem);
        //给组件设置右键菜单,不需要使用监听器,只需要调用setComponentPopupMenu()方法即可,更简单。
        textArea.setComponentPopupMenu(popupMenu);
//        textArea.add(scrollPane);
        metalItem.addActionListener(e -> {
            try {
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                this.updateUI();
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            } catch (InstantiationException ex) {
                throw new RuntimeException(ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            } catch (UnsupportedLookAndFeelException ex) {
                throw new RuntimeException(ex);
            }
        });
        nimbusItem.addActionListener(e -> {
            try {
                UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
                this.updateUI();
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            } catch (InstantiationException ex) {
                throw new RuntimeException(ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            } catch (UnsupportedLookAndFeelException ex) {
                throw new RuntimeException(ex);
            }
        });
        windowsItem.addActionListener(e -> {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                this.updateUI();
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            } catch (InstantiationException ex) {
                throw new RuntimeException(ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            } catch (UnsupportedLookAndFeelException ex) {
                throw new RuntimeException(ex);
            }
        });
        classicItem.addActionListener(e -> {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
                this.updateUI();
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            } catch (InstantiationException ex) {
                throw new RuntimeException(ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            } catch (UnsupportedLookAndFeelException ex) {
                throw new RuntimeException(ex);
            }
        });
        motifItem.addActionListener(e -> {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                this.updateUI();
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            } catch (InstantiationException ex) {
                throw new RuntimeException(ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            } catch (UnsupportedLookAndFeelException ex) {
                throw new RuntimeException(ex);
            }
        });


    }

    private void updateUI() {
        SwingUtilities.updateComponentTreeUI(frame.getContentPane());
        SwingUtilities.updateComponentTreeUI(jMenuBar);
        SwingUtilities.updateComponentTreeUI(popupMenu);
    }

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

    private void textAreaClear(ActionEvent e) {
        textArea.setText("");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.huang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值