所有 Swing 元件必須在事件分派執行緒(EDT)中建立與操作,使用 EventQueue.invokeLater() 確保執行緒安全。
public class FrameTest {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
SimpleFrame frame = new SimpleFrame();
frame.setExtendedState(Frame.MAXIMIZED_BOTH); // 全螢幕
frame.setTitle("Christmas");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class SimpleFrame extends JFrame {
public SimpleFrame() {
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
setSize(screenSize.width, screenSize.height);
// 設定圖示
setIconImage(new ImageIcon("D:/icon.png").getImage());
}
}
繼承 JComponent,覆寫 paintComponent(Graphics g):
public void paintComponent(Graphics g) {
g.drawString("Hello World!", 75, 100);
}
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
使用 Graphics2D 與 Shape 介面:
Graphics2D g2 = (Graphics2D) g; Rectangle2D rect = new Rectangle2D.Double(100, 100, 200, 150); Ellipse2D ellipse = new Ellipse2D.Double(); ellipse.setFrame(rect); // 以外接矩形定義橢圓 g2.draw(rect); g2.draw(ellipse); g2.draw(new Line2D.Double(100, 100, 300, 250)); // 對角線 // 繪製圓形 Ellipse2D circle = new Ellipse2D.Double(); circle.setFrameFromCenter(200, 175, 350, 325); // 圓心 + 半徑 g2.draw(circle);
g2.setColor(Color.BLUE); g2.fill(rect); // 填充 g2.draw(rect); // 邊框
Font f = new Font("Dialog", Font.BOLD, 36);
g2.setFont(f);
FontRenderContext ctx = g2.getFontRenderContext();
Rectangle2D bounds = f.getStringBounds("Hello World!", ctx);
// 置中計算
double x = (width - bounds.getWidth()) / 2;
double y = (height - bounds.getHeight()) / 2;
double ascent = -bounds.getY();
double baseY = y + ascent;
g2.drawString("Hello World!", (int)x, (int)baseY);
// 畫基線與外框
g2.setPaint(Color.LIGHT_GRAY);
g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));
g2.draw(new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight()));
class ImageComponent extends JComponent {
private Image image;
public ImageComponent() {
image = new ImageIcon("D:/image.jpg").getImage();
}
public void paintComponent(Graphics g) {
if (image == null) return;
g.drawImage(image, 0, 0, null);
}
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
}
| 類別 | 用途 |
|---|---|
| JFrame | 主視窗容器 |
| JComponent | 自訂繪圖基底類別 |
| Graphics2D | 進階 2D 繪圖 |
| Shape 介面 | 幾何圖形統一介面 |
| FontRenderContext | 字體度量資訊 |