java中swing的用法有哪些

小億
99
2023-09-25 18:44:48

在Java中,Swing是一個(gè)圖形用戶界面(GUI)工具包,用于創(chuàng)建窗口、按鈕、文本框等GUI組件。以下是一些常見的Swing用法:

  1. 創(chuàng)建一個(gè)基本的窗口:
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. 使用布局管理器來(lái)布置組件:
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. 響應(yīng)按鈕點(diǎn)擊事件:
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