首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Swing 圖形介面開發入門:六大核心範例從視窗到圖片顯示

     編輯:Java 相關知識

核心原則

所有 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字體度量資訊
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved