自訂 JFrame 子類 mainFrame,建構子接受標題、寬、高參數,自動設定圖示、關閉操作、視窗大小並置中於螢幕。
public class mainFrame extends JFrame {
public mainFrame(String title, int width, int height) {
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
ImageIcon icon = new ImageIcon("images/middle.gif");
setTitle(title);
setIconImage(icon.getImage());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(width, height);
int x = (screen.width - getWidth()) / 2;
int y = (screen.height - getHeight()) / 2;
setLocation(x, y);
setVisible(true);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
new mainFrame("main Frame Demo", 400, 300);
}
}
Toolkit.getDefaultToolkit().getScreenSize() 取得螢幕解析度。setLocation(x, y) 計算置中座標:(螢幕寬 - 視窗寬)/2。DISPOSE_ON_CLOSE 僅銷毀當前視窗,不結束整個 JVM(適合多視窗應用)。setIconImage 設定標題列圖示。