关于JPanel设置背景图片的Bug说明_我在故我思_百度空间

关于JPanel设置背景图片的Bug说明
Panel可以像网页控件一样设置背景图片,主要是通过覆写JPanel的
paint(Graphics g)方法和paintComponent(Graphics g)方法;

但是二者有区别:

JLabel类同其它的Swing组件一样,继承至javax.swing.Jcomponent.Swing。它们都是通过调用JComponent组件的paint方法来画界面。我们可以通过重载JComponent的公开方法paint来修改一个组件画界面的行为。下面是一个JComponent的paint方法的定义。

public void paint(Graphicsg)

作为paint方法的参数传进来的对象Graphics是一个绘图面板。为了优化绘图这个操作,paint方法被分割成三个具有保护(protected)属性的方法:paintComponent, paintBorder, paintChildren。paint方法调用这三个方法同时将它接受到的Graphics实例传递给这三个方法。

根据以上所说的,如果你想重画SWING的外观话就应该根据你要画的内容选择到底是重写paintComponent或paintBorder或paintChildren方法。如果同时重写了paint与paintComponent方法的话,则只会调用paint方法,而不执行paintComponent了。


所以:
通用的添加背景的方法可以是:
protected void paint(Graphics g) {
try {
BufferedImage img = ImageIO.read(My_Auditor_JPanel.class.getResource("/images/aa.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
} catch (IOException e) {
e.printStackTrace();
}
}
和:

protected void paintComponent(Graphics g) {
try {
BufferedImage img = ImageIO.read(My_Auditor_JPanel.class.getResource("/images/aa.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
} catch (IOException e) {
e.printStackTrace();
}
}
//但是推荐第二种方法;否则第一种方法可能导致背景图片遮盖住面板的其他控件。
//第二种覆写 paintComponent(Graphics g)则不会!

相关文档
最新文档