Swing 設計為 AWT 的超集,大多數 AWT 元件對應同名的 J 前綴類別。遷移核心:類別名加 J、引入 javax.swing、處理 ContentPane。
| AWT (java.awt) | Swing (javax.swing) | 備註 |
|---|---|---|
Button | JButton | |
Label | JLabel | |
TextField | JTextField | |
TextArea | JTextArea | |
Checkbox | JCheckBox | |
CheckboxGroup | ButtonGroup + JRadioButton | 架構不同 |
Choice | JComboBox | |
List | JList | |
Scrollbar | JScrollBar | 通常用 JScrollPane |
Canvas | JPanel | 繪圖基底 |
Panel | JPanel | |
Window/Frame/Dialog | JWindow/JFrame/JDialog | 頂層容器 |
MenuBar/Menu/MenuItem | JMenuBar/JMenu/JMenuItem |
// AWT: 直接加入 Frame
Frame f = new Frame();
f.add(button);
// Swing: 必須加入 ContentPane
JFrame f = new JFrame();
f.getContentPane().add(button); // 或 f.add(button) JDK 1.5+ 自動轉發
原因:JFrame 為 RootPaneContainer,內含 JRootPane → contentPane、glassPane、layeredPane,支援分層、玻璃窗、選單列整合。
// AWT 版本
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AwtDemo extends Applet {
Button b1 = new Button("Btn 1"), b2 = new Button("Btn 2");
TextField t = new TextField(20);
public void init() {
ActionListener al = e -> t.setText(((Button)e.getSource()).getLabel() + " Pressed");
b1.addActionListener(al); add(b1);
b2.addActionListener(al); add(b2);
add(t);
}
}
// Swing 遷移版本
package c13.swing;
import javax.swing.*;
import java.awt.event.*;
public class JButtonDemo extends JApplet { // Applet → JApplet
JButton b1 = new JButton("JButton 1"), b2 = new JButton("JButton 2");
JTextField t = new JTextField(20);
public void init() {
ActionListener al = e -> t.setText(((JButton)e.getSource()).getText() + " Pressed");
b1.addActionListener(al); add(b1); // JApplet.add() 自動轉發至 ContentPane
b2.addActionListener(al); add(b2);
add(t);
}
public static void main(String[] args) {
JButtonDemo applet = new JButtonDemo();
JFrame frame = new JFrame("JButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet, BorderLayout.CENTER); // 必須用 ContentPane
frame.setSize(300, 100);
applet.init(); applet.start();
frame.setVisible(true);
}
}
java.awt.* 元件類別 → javax.swing.J*Frame → JFrame,Dialog → JDialog,Applet → JAppletgetContentPane().add() (JDK 1.5+ 可省略)BoxLayout、OverlayLayout 等新選擇ActionListener 等均在 java.awt.event)paint(Graphics) → paintComponent(Graphics) (雙緩衝自動支援)UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())JTable、JTree、JTabbedPane、JSpinner、JSlider 等 AWT 無對應。