Java swing

java中swing的用法有哪些

小亿
101
2023-09-25 18:44:48
栏目: 编程语言

在Java中,Swing是一个图形用户界面(GUI)工具包,用于创建窗口、按钮、文本框等GUI组件。以下是一些常见的Swing用法:

  1. 创建一个基本的窗口:
import javax.swing.*;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
  1. 添加按钮:
import javax.swing.*;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
add(button);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
  1. 添加文本框:
import javax.swing.*;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
add(textField);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
  1. 使用布局管理器来布置组件:
import javax.swing.*;
import java.awt.*;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout()); // 使用流式布局管理器
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
add(button1);
add(button2);
add(button3);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}
  1. 响应按钮点击事件:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyWindow extends JFrame {
public MyWindow() {
setSize(300, 200);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button clicked!");
}
});
add(button);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MyWindow());
}
}

这些只是一些基本的用法,Swing还有很多其他功能和组件可以使用。

0
看了该问题的人还看了