Java 如何在JPanel中设置背景而不使用paintComponent()中的超级调用
在这个程序中,我想画一系列相互作用形成网络的线条。每次计时器滴答作响时,都会画一条线。因此,我不能在paintComponent中调用super.paintComponent,因为我需要显示前面的行。但是,我想设置背景颜色,据我所知,只有在第一次调用super时才能调用setBackground方法。我不确定fillRect方法是否有效,因为它每次都会在旧直线上绘制一个矩形。我尝试在构造函数中使用setBackground方法,但它也不起作用 这是我的密码:Java 如何在JPanel中设置背景而不使用paintComponent()中的超级调用,java,swing,jpanel,paintcomponent,setbackground,Java,Swing,Jpanel,Paintcomponent,Setbackground,在这个程序中,我想画一系列相互作用形成网络的线条。每次计时器滴答作响时,都会画一条线。因此,我不能在paintComponent中调用super.paintComponent,因为我需要显示前面的行。但是,我想设置背景颜色,据我所知,只有在第一次调用super时才能调用setBackground方法。我不确定fillRect方法是否有效,因为它每次都会在旧直线上绘制一个矩形。我尝试在构造函数中使用setBackground方法,但它也不起作用 这是我的密码: import java.awt.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class prettyWebPanel extends JPanel implements ActionListener {
Timer time = new Timer(100,this);
private Color colour1 = Color.black;
private Color colour2 = Color.white;
JButton start = new JButton("Start");
int j = 0;
public prettyWebPanel() {
setPreferredSize(new Dimension (550,550));
this.add(start);
start.addActionListener(this);
setBackground(colour1);
}
public void paintComponent(Graphics g) {
setBackground(colour1);
setForeground(colour2);
if (j<490) g.drawLine(20, 20+j, 20+j, 500);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == start) time.start();
else if (e.getSource() == time) {
j+=10;
repaint();
}
}
}
因为我需要显示前面的行
然后你需要做增量绘制。有关执行此操作的两种常用方法,请参见:
保留要绘制的对象列表,并每次重新绘制
在缓冲区图像上进行绘制。
因此,我不能在paintComponent中调用super.paintComponent,因为我需要显示前面的行。你的整个绘画方法都是错误的。放下它,用传统的方法。避免重新绘制以前的工作的一种方法是将所有内容绘制到BuffereImage,然后您也可以在JLabel中显示该图像。这个问题似乎与主题无关,因为它涉及的是一个最佳方法与所问问题完全不同的问题。使用fillRect按您喜欢的方式在paintComponent方法中绘制背景很好。@xiaowang如果我每次调用fillRect,它会在先前绘制的直线上绘制矩形,对吗?哦,我太傻了。我意识到我可以使用if语句只绘制一次矩形!谢谢: