super.paintComponent()无法正常工作

时间:2019-07-08 15:26:26

标签: java awt

我试图在JPanel中多次绘制形状以模仿动画(动画在其上移动)。问题在于形状正在被重绘,因此多次假装在屏幕上出现在屏幕上,而我所假装的是在重绘一次只能看到一个形状。

方法super.paintComponent()负责重新绘制JPanel的背景,因此,执行重新绘制时,只有一个形状是可见的。

我有以下代码(为了简化和更好地理解而对其进行了简化/简化):

public class Animated_Shape_Test extends JFrame
{
    public static void main(String args[]) throws IOException 
    {
        new Animated_Shape_Test();
    }

    public Animated_Shape_Test() throws IOException
    {
        this.setSize(500, 500);
        this.setPreferredSize(new Dimension(500, 500));
        this.setLocation(new Point(430, 150));
        this.setTitle("Database Launcher v1.0");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setVisible(true);

        DBPanel panel = new DBPanel();

        getContentPane().add(panel, BorderLayout.CENTER);
    }
}

final class DBPanel extends JPanel implements Runnable
{   
    int musicShapePosX = 85;
    int musicShapePosY = 100;
    int SEGMENT_SHAPE_LENGTH = 50;
    int SHAPE_HEIGHT = 10;
    float SHAPE_SPEED = 7.5f; 

    CustomShapeButton musicShapeButton = new CustomShapeButton(musicShapePosX, musicShapePosY, SEGMENT_SHAPE_LENGTH, SHAPE_HEIGHT);

    private ArrayList<Shape> shapes = null;

    protected DBPanel() throws IOException
    {   
        shapes = new ArrayList();

        shapes.add(musicShapeButton);

        this.setOpaque(true);
        this.setFocusable(true);

        startThread();
    }

    public void startThread()
    {
        Thread t = new Thread(this);

        t.start();
    }

    @Override
    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.setColor(getBackground().darker());
        g2.fillRect(0, 0, getWidth(), getHeight());

        g2.setColor(Color.BLACK);
        g2.draw(musicShapeButton);
    }

    public void delay(int milliseconds)
    {
        try
        {
            Thread.sleep(milliseconds);
        } 
        catch (InterruptedException e)
        {
        }
    }

    @Override
    public void run() 
    {
        while (true)
        {
            delay(35);
            animateButtonShapeMusic();
            repaint();
        }
    }

    public void animateButtonShapeMusic()
    {
        if (musicShapePosY < 228)
        {
            musicShapePosY = (int)(musicShapePosY + SHAPE_SPEED);    

            musicShapeButton.drawShape(musicShapePosX, musicShapePosY, SEGMENT_SHAPE_LENGTH, SHAPE_HEIGHT);
        }
    }
}

我在屏幕上重新绘制了几种形状(动画)。 我希望在屏幕上重新绘制单个形状(动画)。

谢谢。

0 个答案:

没有答案