在Java中,Swing是一個(gè)圖形用戶界面(GUI)工具包,用于創(chuàng)建窗口、按鈕、文本框等GUI組件。以下是一些常見的Swing用法:
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());
}
}
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());
}
}
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());
}
}
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());
}
}
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還有很多其他功能和組件可以使用。