gpt4 book ai didi

java - 为什么我们需要重新绘制 JPanel?

转载 作者:行者123 更新时间:2023-12-01 22:30:35 25 4
gpt4 key购买 nike

问题是当你像这样绘制 JPanel 时:

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor (Color.CYAN);
g.fillRect(10,10,200,50);
g.setColor(Color.RED);
g.fillOval(50,50,50,50);
}

因此,如果创建 JPanel 时,它会绘制一个青色矩形和一个红色椭圆形。问题是,例如,如果您想移动椭圆形,则必须重新绘制整个面板!

如何制作 2D 对象并使其可移动且可更改,而无需重新绘制整个面板?

最佳答案

首先查看 Painting in AWT and SwingPerforming Custom Painting了解绘画过程。

如果您不愿意,您不必“必须”重新绘制整个面板,可以使用 JPanel#repaint(int, int, int, int)它允许您指定要重新绘制的区域。

现在,请记住,如果您需要绘制用于包含椭圆形的区域,然后绘制它现在所在的区域,这可以确保以前的位置也被更新,否则您将出现重影。 .

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testball;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestBall {

public static void main(String[] args) {
new TestBall();
}

public TestBall() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private int x = 100 - 10;
private int y = 100 - 10;
private int delta = 4;

public TestPane() {
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Replace existing area...
repaint(x, y, 21, 21);

x += delta;
if (x + 20 >= getWidth()) {
x = getWidth() - 20;
delta *= -1;
} else if (x < 0) {
x = 0;
delta *= -1;
}
repaint(x, y, 21, 21);
}
});
timer.start();
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.drawOval(x, y, 20, 20);
g2d.dispose();
}

}

}

关于java - 为什么我们需要重新绘制 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27856209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com