如下的一小段代码:...
class MyPanel extends JPanel{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(10,10,80,30); }
}
...
我想问其中的super.paintComponent方法有什么用,怎么还看到有的paintComponent中没有用调用super.paintComponent呢,那么什么情况可以去掉,什么时候必须有这行呢?
class MyPanel extends JPanel{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(10,10,80,30); }
}
...
我想问其中的super.paintComponent方法有什么用,怎么还看到有的paintComponent中没有用调用super.paintComponent呢,那么什么情况可以去掉,什么时候必须有这行呢?
再问下,怎么增量绘制呢,比如JPanel上原来有一些图形,后来想再增加其他图形是要调用JPanel的paintComponent(g)方法吗?
第2个问题, 我想是需要重新继承JPanel重写paintComponent, 然后替换已有的JPanel
增量绘制一定要替换掉原来的MyJPanel吗,不能在原来的MyJPanel基础增加绘制一些图形吗,
如果替换,那么super.paintComponent(g)岂不是没用了吗
import java.awt.event.*;
import javax.swing.*;public class ButtonDemo extends JPanel implements ActionListener{
JButton b1,b2;
String message="请点击按钮";
int row=50,col=50; public ButtonDemo(){
//按钮1
b1=new JButton("First Button");
b1.setActionCommand("first");
b1.addActionListener(this);
//按钮2
b2=new JButton("Second Button");
b2.setActionCommand("second");
b2.addActionListener(this); add(b1);
add(b2);
} public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("first")){
message="第一个按钮被按下!";
row=50;
col=50;
}else if(e.getActionCommand().equals("second")){
message="第二个按钮被按下!";
row=50;
col=150;
}
repaint(); //注意这一行
} public void paintComponent(Graphics g){
super.paintComponent(g); //注意这一行
g.drawString(message, col, row);
} public static void main(String args[]){
JFrame jf=new JFrame("按钮测试!");
jf.getContentPane().add(new ButtonDemo());
jf.setSize(300,200);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}paintComponent方法在JPanel初始化时执行一次。使用repaint方法会导致调用paintComponent方法.
如果把super.paintComponent(g)这行注释掉,会发现点击按钮时以前输出的字符串仍然存在,没有被清除掉.