Java Swing库学习

Java Swing 是一个用于创建图形用户界面(GUI)的库。它是Java基础类库的一部分,提供了丰富的组件和布局管理器,能够帮助开发者创建功能强大、跨平台的桌面应用程序。

学习Swing库的步骤

1. 环境配置

确保你已经安装了JDK,并且设置好了开发环境(如Eclipse, IntelliJ IDEA等)。

2. Hello World 示例

首先,编写一个简单的Swing程序,创建一个带有按钮和标签的窗口。

import javax.swing.*;
​
public class HelloWorldSwing {
    private static void createAndShowGUI() {
        // 创建并设置窗口
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
​
        // 添加 "Hello World" 标签
        JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);
​
        // 显示窗口
        frame.setSize(300, 100);
        frame.setVisible(true);
    }
​
    public static void main(String[] args) {
        // 确保创建和更新GUI的代码在事件派发线程中执行
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
3. Swing基础组件

Swing 提供了多种基础组件,如按钮、文本框、标签等。下面是一些常用组件的示例:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
​
public class SwingComponentsDemo {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Swing Components Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setLayout(new FlowLayout());
​
        // 创建按钮
        JButton button = new JButton("Click Me");
        frame.add(button);
​
        // 创建标签
        JLabel label = new JLabel("Hello, Swing!");
        frame.add(label);
​
        // 创建文本框
        JTextField textField = new JTextField(20);
        frame.add(textField);
​
        // 创建复选框
        JCheckBox checkBox = new JCheckBox("Check me");
        frame.add(checkBox);
​
        // 创建单选按钮
        JRadioButton radioButton1 = new JRadioButton("Option 1");
        JRadioButton radioButton2 = new JRadioButton("Option 2");
        ButtonGroup group = new ButtonGroup();
        group.add(radioButton1);
        group.add(radioButton2);
        frame.add(radioButton1);
        frame.add(radioButton2);
​
        // 添加按钮点击事件
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = textField.getText();
                label.setText("Hello, " + text);
            }
        });
​
        frame.setVisible(true);
    }
}
4. 布局管理器

布局管理器用于管理组件在容器中的布局。Swing 提供了多种布局管理器,如 FlowLayout, BorderLayout, GridLayout, BoxLayout 等。

  • FlowLayout: 按添加顺序从左到右排列组件,组件在容器边界内换行。

frame.setLayout(new FlowLayout());
  • BorderLayout: 将容器分为东、西、南、北、中五个区域,组件添加到相应区域。

frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);
  • GridLayout: 将容器划分为等大小的网格。

frame.setLayout(new GridLayout(2, 2)); // 2 行 2 列
  • BoxLayout: 允许在单行或单列中排列组件。

frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
5. 事件处理

Swing 使用事件监听器模式来处理用户交互。例如,按钮的点击事件可以使用 ActionListener 来处理。

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // 事件处理逻辑
    }
});
6. 示例:一个简单的计算器

下面是一个简单的计算器示例,演示了如何使用Swing创建复杂的GUI。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
​
public class Calculator {
    private JFrame frame;
    private JTextField display;
    private JPanel panel;
    private double result;
    private String operator;
    private boolean start;
​
    public Calculator() {
        frame = new JFrame("Calculator");
        display = new JTextField("0");
        panel = new JPanel();
        result = 0;
        operator = "=";
        start = true;
​
        display.setEditable(false);
        frame.add(display, BorderLayout.NORTH);
​
        panel.setLayout(new GridLayout(4, 4));
        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"
        };
​
        for (String text : buttons) {
            addButton(panel, text);
        }
​
        frame.add(panel, BorderLayout.CENTER);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
​
    private void addButton(Container container, String text) {
        JButton button = new JButton(text);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand();
                if ('0' <= command.charAt(0) && command.charAt(0) <= '9' || command.equals(".")) {
                    if (start) {
                        display.setText(command);
                    } else {
                        display.setText(display.getText() + command);
                    }
                    start = false;
                } else {
                    if (start) {
                        if (command.equals("-")) {
                            display.setText(command);
                            start = false;
                        } else {
                            operator = command;
                        }
                    } else {
                        calculate(Double.parseDouble(display.getText()));
                        operator = command;
                        start = true;
                    }
                }
            }
        });
        container.add(button);
    }
​
    private void calculate(double x) {
        switch (operator) {
            case "+":
                result += x;
                break;
            case "-":
                result -= x;
                break;
            case "*":
                result *= x;
                break;
            case "/":
                result /= x;
                break;
            case "=":
                result = x;
                break;
        }
        display.setText("" + result);
    }
​
    public static void main(String[] args) {
        new Calculator();
    }
}

参考资料

  • 26
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值