设置窗体出现在屏幕中央的代码段
//设置大小
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);
}
}
}