Java Swing库学习

2024-06-13 17:52
文章标签 java 学习 swing

本文主要是介绍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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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();}
}

参考资料

  • Java Swing 官方教程

  • Java Swing API 文档

这篇关于Java Swing库学习的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1058005

相关文章

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Java字符串处理全解析(String、StringBuilder与StringBuffer)

《Java字符串处理全解析(String、StringBuilder与StringBuffer)》:本文主要介绍Java字符串处理全解析(String、StringBuilder与StringBu... 目录Java字符串处理全解析:String、StringBuilder与StringBuffer一、St

springboot整合阿里云百炼DeepSeek实现sse流式打印的操作方法

《springboot整合阿里云百炼DeepSeek实现sse流式打印的操作方法》:本文主要介绍springboot整合阿里云百炼DeepSeek实现sse流式打印,本文给大家介绍的非常详细,对大... 目录1.开通阿里云百炼,获取到key2.新建SpringBoot项目3.工具类4.启动类5.测试类6.测

Spring Boot循环依赖原理、解决方案与最佳实践(全解析)

《SpringBoot循环依赖原理、解决方案与最佳实践(全解析)》循环依赖指两个或多个Bean相互直接或间接引用,形成闭环依赖关系,:本文主要介绍SpringBoot循环依赖原理、解决方案与最... 目录一、循环依赖的本质与危害1.1 什么是循环依赖?1.2 核心危害二、Spring的三级缓存机制2.1 三

在Spring Boot中浅尝内存泄漏的实战记录

《在SpringBoot中浅尝内存泄漏的实战记录》本文给大家分享在SpringBoot中浅尝内存泄漏的实战记录,结合实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录使用静态集合持有对象引用,阻止GC回收关键点:可执行代码:验证:1,运行程序(启动时添加JVM参数限制堆大小):2,访问 htt

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

浅析Java中如何优雅地处理null值

《浅析Java中如何优雅地处理null值》这篇文章主要为大家详细介绍了如何结合Lambda表达式和Optional,让Java更优雅地处理null值,感兴趣的小伙伴可以跟随小编一起学习一下... 目录场景 1:不为 null 则执行场景 2:不为 null 则返回,为 null 则返回特定值或抛出异常场景

SpringMVC获取请求参数的方法

《SpringMVC获取请求参数的方法》:本文主要介绍SpringMVC获取请求参数的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下... 目录1、通过ServletAPI获取2、通过控制器方法的形参获取请求参数3、@RequestParam4、@

SpringBoot应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll