painComponent(Graphics g)

有点笨 2011-03-10 03:29:46
在一个JPanle的扩展类中画图,
重写protected void painComponent(Graphics g)时,为什么第一句要引入下面这句
super.paintComponent(g);

还有这句是个哪个父类调用的?
...全文
107 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengranxiang 2011-03-10
  • 打赏
  • 举报
回复
是这个样子的:

Swing 中, JComponent 的 paint() 方法会依次调用 paintComponent(), paintBorder(), paintChildren() 三个方法,其中
paintComponent() 的作用为: 绘制组件自己本身
paintBorder() 的作用为: 绘制自己的边框
paintChildren() 的作用为:绘制添加到自己中的 子组件

所有如果你 不调用 super.paintComponent() 只是不会绘制组件本身,也就是: 该组件本身为透明
但是,任然会有边框和加入其中的 子组件

例如:

package prx.swing;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Test extends JPanel {
public Test() {
this.add(new JButton("test"));
this.add(new JLabel("test"));
this.add(new JTextField("test"));

this.setBackground(Color.BLUE); //设置背景为蓝色
this.setBorder(BorderFactory.createLineBorder(Color.red));//红色边框
this.setPreferredSize(new Dimension(300, 300));
}

protected void paintComponent(Graphics g) {
// super.paintComponent(g); //只会影响Test本身的绘制,不会影响边框和其他组件,取消注释将看到蓝色背景。
g.fillRect(0, 0, 100, 100);
}

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Test());
frame.pack();
frame.setVisible(true);
}
}

有点笨 2011-03-10
  • 打赏
  • 举报
回复
额,应该这样问,调用的是哪个父类里面的paintComponent method
有点笨 2011-03-10
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 huan0911612504 的回复:]
这句话应该是自己调用啊,怎么会是父类调用的呢?
[/Quote]

额,可是JPanel类中没有paintComponent method哎
huan0911612504 2011-03-10
  • 打赏
  • 举报
回复
这句话应该是自己调用啊,怎么会是父类调用的呢?
hardsonxu 2011-03-10
  • 打赏
  • 举报
回复
因为要调用父类的绘图方法绘制面板的其它元素。
你当然也可以不调用,自己来绘制面板所需要的所有元素。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧