在JPanel和JComponent中进行绘制 [英] Drawing in JPanel vs JComponent
本文介绍了在JPanel和JComponent中进行绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一些帮助来理解为什么图形在JComponent和JPanel中的工作方式不同.
I need some help understanding why the drawing works differently in JComponent vs 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点.
In this above example, the "particle" moves from point A to point B just fine..
但是当我将粒子从JComponent继承到JPanel时.
But when I subclass Particle from JComponent to JPanel..
图形形成一条线..即,矩形永远不会从其开始处消失.
the drawing forms a line.. i.e. the rectangle never disappears from where it starts..
为什么会这样?
推荐答案
在paintComponent实现中调用super.paintComponent(g).
Call super.paintComponent(g) in paintComponent implementation.
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getColor());
g2d.fillRect(x, y, 4, 4);
}
这篇关于在JPanel和JComponent中进行绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文