在 JPanel 与 JComponent 中绘图

2024-04-27

我需要一些帮助来理解为什么 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 点很好。

但是当我将 Particle 从 JComponent 子类到 JPanel 时..

绘图形成一条线..即矩形永远不会从它开始的地方消失..

为什么会这样呢?


解决方案已发布Toilal https://stackoverflow.com/a/16998448/2040040。我想解释一下why:

In API 文档paintComponent of JComponent http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#paintComponent%28java.awt.Graphics%29

此外,如果您不调用 super 的实现,则必须遵守不透明属性,也就是说,如果该组件是不透明的,则必须以非不透明的颜色完全填充背景。如果您不遵守不透明属性,您可能会看到视觉伪影。

In setOpaque of JComponent http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setOpaque%28boolean%29

该属性的默认值为 falseJComponent。但是,大多数标准上此属性的默认值JComponent子类(例如JButton and JTree) 取决于外观和感觉。

添加此代码:

System.out.println(isOpaque());
  • In JComponent case false被打印。
  • In JPanel case true被打印。

就这样。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 JPanel 与 JComponent 中绘图 的相关文章

随机推荐