[英]How to set the background in a JPanel without using the super call in paintComponent()
In this program, I want to draw a series of lines that interact to form a web. 在此程序中,我想绘制一系列相互影响以形成网络的线。 Each time the timer ticks, a line is drawn.
每次计时器计时时,都会画一条线。 Therefore, I cannot have the
super.paintComponent(g)
call in the paintComponent()
because I need the previous lines to appear. 因此,我在
paintComponent()
无法调用super.paintComponent(g)
,因为我需要前面的几行出现。 However, I would like to set the background colour and as far as I've found, the setBackground()
method can be called only if the super call is first made. 但是,我想设置背景色,据我所知,只有在第一次进行超级调用时才能调用
setBackground()
方法。 I am not sure if the fillRect
method would work either because it would draw a rectangle over the old line each time. 我不确定
fillRect
方法是否会起作用,因为它每次都会在旧行上绘制一个矩形。 I tried having the setBackground()
method in the constructor, and it did not work either. 我尝试在构造函数中使用
setBackground()
方法,但该方法也不起作用。
Here is my code: 这是我的代码:
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();
}
}
}
because I need the previous lines to appear.
因为我需要出现前几行。
Then you need to do incremental painting. 然后,您需要进行增量绘画。 See Custom Painting Approaches for two common ways to do this:
请参阅自定义绘画方法,以了解两种常见的实现方法:
List
of objects to paint and repaint them every time List
BufferedImage
. BufferedImage
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.