本例示範如何撰寫一個可重用的 JFrame 子類別,透過建構子參數指定標題、寬度、高度,並自動將視窗置中於螢幕。採用 Toolkit 取得螢幕尺寸,計算左上角座標以達到置中效果。
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame {
/**
* 建構子:初始化視窗屬性並置中顯示
* @param sTitle 視窗標題
* @param iWidth 視窗寬度
* @param iHeight 視窗高度
*/
public MainFrame(String sTitle, int iWidth, int iHeight) {
// 取得螢幕尺寸
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// 設定視窗圖示(需確保圖片路徑正確)
ImageIcon ii = new ImageIcon("images/middle.gif");
setTitle(sTitle);
setIconImage(ii.getImage());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 關閉視窗時釋放資源
setSize(iWidth, iHeight);
// 計算置中座標
int w = getSize().width;
int h = getSize().height;
int x = (dim.width - w) / 2;
int y = (dim.height - h) / 2;
setLocation(x, y);
setVisible(true); // 顯示視窗
}
public static void main(String[] args) {
// 使用系統外觀風格
JFrame.setDefaultLookAndFeelDecorated(true);
new MainFrame("Main Frame Demo", 400, 300);
}
}
javax.swing.JFrame,擁有完整視窗功能。Toolkit.getDefaultToolkit().getScreenSize()getSize()(screenWidth - frameWidth)/2, (screenHeight - frameHeight)/2setLocation(x, y)DISPOSE_ON_CLOSE 僅銷毀目前視窗,適合多視窗應用;若為主視窗可用 EXIT_ON_CLOSE 結束程式。JFrame.setDefaultLookAndFeelDecorated(true) 啟用 Swing 預設裝飾(需在建立視窗前呼叫)。images/middle.gif 不存在,getImage() 回傳 null,不會報錯但無圖示。建議使用 getClass().getResource() 載入資源檔。sun.java2d.uiScale 或使用 setAutoRequestFocus(false) 避免縮放問題。JDialog 並設定 setModal(true)。