[英]Drawing in JPanel vs JComponent
我需要一些帮助来理解为什么图形在JComponent与JPanel中的工作方式不同。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Particle extends JComponent implements Runnable{
private int x = 45;
private int y = 45;
private int cx;
private int cy;
private int size;
private Color color;
private JFrame frame;
public Color getColor(){
return color = new Color(100,0,190);
}
public Particle(){
frame = new JFrame();
frame.setSize(400, 400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.setVisible(true);
}
public void update(){
x+=1;
y+=1;
}
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getColor());
g2d.fillRect(x, y, 4, 4);
}
public void startThread(){
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
for(int i = 0; i <= 200; i++){
try{
update();
repaint();
Thread.sleep(4);
}catch(Exception e){
System.out.print("Exception at thread.start()");
}
}
}
public static void main(String[] args) {
Particle particle = new Particle();
particle.startThread();
}
}
在上面的示例中,“粒子”恰好从A点移动到B点。
但是当我将粒子从JComponent子类化为JPanel ..
该图形形成一条线..即矩形永远不会从其开始消失。
为什么会这样呢?
解决方案由Toilal发布 。 我想解释为什么 :
在JComponent
的paintComponent
的API文档中
此外,如果您没有调用super的实现,则必须使用opaque属性,即,如果该组件是不透明的,则必须以非不透明的颜色完全填充背景。 如果您不尊重不透明属性,则可能会看到视觉伪像。
对于
JComponent
,此属性的默认值为false。 但是,大多数标准JComponent
子类(例如JButton
和JTree
)上此属性的默认值取决于外观。
添加此代码:
System.out.println(isOpaque());
JComponent
情况下,将输出false
。 JPanel
情况下,将输出true
。 就这样。
在paintComponent实现中调用super.paintComponent(g)。
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getColor());
g2d.fillRect(x, y, 4, 4);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.