GUI技巧

設置窗體出現在屏幕中央的代碼段

//設置大小

 

this.setSize(680, 440);

//獲取工具

Toolkit t = Toolkit.getDefaultToolkit();

//獲取屏幕尺寸

Dimension scrns = t.getScreenSize();

//獲取窗體尺寸

Dimension fs = this.getSize();

int fw = fs.width;

int fh = fs.height;

this.setTitle("24小時ATM機");

//設置窗體位置

this.setLocation((scrns.width - fw) / 2, (scrns.height - fh) / 2);

this.setLayout(null);

this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);

this.setResizable(false);

this.setVisible(true);

--------------------------------------------------------------------------------

重繪JPanel 設置背景圖片

--------------------------------------------------------------------------------

// 重寫JPanel

public class BgJPanel extends JPanel {

//圖片文件

private Image image;

public BgJPanel() {

super();

//設置不透明

setOpaque(true);

//創建圖像

image = Toolkit.getDefaultToolkit().getImage(

"/com.ccb.gui/card/background.jpg");

}

//重繪

public void paintComponent(Graphics g) {

super.paintComponent(g);

setBackground(Color.WHITE);

//讓圖像大小隨窗體大小變化

if (image != null) {

int height = image.getHeight(this);

int width = image.getWidth(this);

if (height != -1 && height > getHeight())

height = getHeight();

if (width != -1 && width > getWidth())

width = getWidth();

int x = (int) (((double) (getWidth() - width)) / 2.0);

int y = (int) (((double) (getHeight() - height)) / 2.0);

 

//繪圖

g.drawImage(image, x, y, width, height, this);

}

}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章