gpt4 book ai didi

java - 多个 Graphics2D 对象

转载 作者:行者123 更新时间:2023-12-02 08:34:08 25 4
gpt4 key购买 nike

我有一个 JPanel 的 Graphics 对象,并且工作正常:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;

public class GraphicsTest extends JPanel
{
private Graphics2D g2d;
private String state;
private int x, y;

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g2d = (Graphics2D) g;
g2d.setClip(0, 0, getWidth(), getHeight());

g2d.setColor(Color.BLACK);
g2d.drawString("STATE: " + state, 5, 15);
g2d.drawString("Mouse Position: " + x + ", " + y, 5, 30);

g2d.setColor(Color.red);
Rectangle2D r2d = new Rectangle2D.Double(x,y,10,10);
g2d.draw(r2d);
Test t = new Test();
super.add(t);

repaint();
}

public void setState(String state) { this.state = state; }
public String getState() { return state; }

public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
}

我正在尝试一个新的图形组件,当我实例化一个新的测试并将其添加到 GraphicsTest 中时,没有任何反应。我到底做错了什么?

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;

public class Test extends JComponent
{
private Graphics2D g2d;
private String state;
private int x, y;

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g2d = (Graphics2D) g.create();

g2d.setColor(Color.GREEN);
g2d.fill(new Rectangle2D.Double(60, 60,
10, 10));

repaint();
}

public void setState(String state) { this.state = state; }
public String getState() { return state; }

public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }

}

谢谢!

最佳答案

您应该只添加一次测试组件并设置布局:

public GraphicTest()
{
super();
setLayout(new BorderLayout());
add(new Test(),BorderLayout.CENTER);
}

此外,不要保存 Graphics2D 对象,因为一旦 paintComponent 完成,它们将无效,并且不要在 paintComponent 内调用 repaint 。如果您需要动画并在 setXXX 方法中调用 repaint 来更改组件的外观,请使用计时器。

关于java - 多个 Graphics2D 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2438739/

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