javax.swing库中的常用组件及其用法
Swing是一个Java的图形用户界面(GUI)工具包,是Java标准库(javax.swing)的一部分。它提供了丰富的组件库,用于创建交互式和可视化的应用程序。下面是javax.swing库中常用组件的介绍及使用例子。
1. JFrame:JFrame是一个顶层的窗口容器,可以用来创建框架窗口。
使用例子:
import javax.swing.JFrame;
public class MainFrame extends JFrame {
public MainFrame() {
setTitle("Hello World");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
2. JPanel:JPanel是一个容器,用于组织其他组件,可以嵌套在JFrame中。
使用例子:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
public class MainFrame extends JFrame {
public MainFrame() {
setTitle("Hello World");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
getContentPane().add(panel);
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
3. JButton:JButton是一个可点击的按钮,用于触发某个操作。
使用例子:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame extends JFrame {
public MainFrame() {
setTitle("Hello World");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
panel.add(button);
getContentPane().add(panel);
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
4. JLabel:JLabel是一个用于显示文本或图像的标签。
使用例子:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
public MainFrame() {
setTitle("Hello World");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel label = new JLabel("Hello World");
panel.add(label);
ImageIcon icon = new ImageIcon("image.jpg");
JLabel imageLabel = new JLabel(icon);
panel.add(imageLabel);
getContentPane().add(panel);
setVisible(true);
