gpt4 book ai didi

java - 这是使用 Java 2D 图形 API 的正确方法吗?

转载 作者:行者123 更新时间:2023-11-29 07:04:35 26 4
gpt4 key购买 nike

我正在为 JBox2D 模拟创建一个图形前端。模拟以增量方式运行,并且在更新之间,应该绘制模拟的内容。类似于游戏,只是没有输入。

我只需要几何图元来绘制 JBox2D 模拟。这个 API 看起来是最简单的选择,但它的设计有点困惑。

目前我有一个名为 Window 的类,它扩展了 JFrame,它包含另一个名为 Renderer 的类作为成员。 Window 类仅初始化自身并提供一个 updateDisplay() 方法(由主循环调用),调用 updateDisplay(objects) Renderer 上的方法。我自己制作了这两个方法,它们的唯一目的是在 Renderer 上调用 repaint()

JPanel 应该这样使用吗?或者我应该使用一些更复杂的动画方法(例如在某些后端线程中涉及事件和/或时间间隔)?

最佳答案

如果您想按设定的时间间隔安排更新,javax.swing.Timer为其提供了Swing集成服务。 Timer 定期在 EDT 上运行它的任务,没有显式循环。 (显式循环会阻止 EDT 处理事件,这会卡住 UI。我对此进行了更深入的解释 here。)

最终在 Swing 中进行任何类型的绘画,您仍然需要做两件事:

  1. 重写 paintComponent 来绘制。
  2. 根据需要调用 repaint 以请求您的绘图可见。 (Swing 通常只在需要时才重新绘制,例如当其他程序的窗口从 Swing 组件上方经过时。)

如果您正在做这两件事,您可能做对了。 Swing 实际上并没有用于动画的高级 API。它的设计主要考虑了绘制 GUI 组件。它当然可以做一些好事,但您必须像现在一样从头开始编写一个组件。

Painting in AWT and Swing如果您没有为它添加书签,它会涵盖一些“幕后”内容。

您可能会查看 JavaFX。我个人不太了解它,但它应该更适合动画。

作为一种优化,可以做的一件事是在单独的图像上绘制,然后在 paintComponent 中将图像绘制到面板上。如果绘画很长,这将特别有用:重绘可以由系统安排,这样可以更好地控制重绘。

如果您不绘制图像,则需要构建一个包含对象的模型,并且每次都在 paintComponent 中绘制所有对象。


下面是一个绘制到图像的例子:

import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;

/**
* Holding left-click draws, and
* right-clicking cycles the color.
*/
class PaintAnyTime {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PaintAnyTime();
}
});
}

Color[] colors = {Color.red, Color.blue, Color.black};
int currentColor = 0;
BufferedImage img = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
Graphics2D imgG2 = img.createGraphics();

JFrame frame = new JFrame("Paint Any Time");
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Creating a copy of the Graphics
// so any reconfiguration we do on
// it doesn't interfere with what
// Swing is doing.
Graphics2D g2 = (Graphics2D) g.create();
// Drawing the image.
int w = img.getWidth();
int h = img.getHeight();
g2.drawImage(img, 0, 0, w, h, null);
// Drawing a swatch.
Color color = colors[currentColor];
g2.setColor(color);
g2.fillRect(0, 0, 16, 16);
g2.setColor(Color.black);
g2.drawRect(-1, -1, 17, 17);
// At the end, we dispose the
// Graphics copy we've created
g2.dispose();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(img.getWidth(), img.getHeight());
}
};

MouseAdapter drawer = new MouseAdapter() {
boolean rButtonDown;
Point prev;

@Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
prev = e.getPoint();
}
if (SwingUtilities.isRightMouseButton(e) && !rButtonDown) {
// (This just behaves a little better
// than using the mouseClicked event.)
rButtonDown = true;
currentColor = (currentColor + 1) % colors.length;
panel.repaint();
}
}

@Override
public void mouseDragged(MouseEvent e) {
if (prev != null) {
Point next = e.getPoint();
Color color = colors[currentColor];
// We can safely paint to the
// image any time we want to.
imgG2.setColor(color);
imgG2.drawLine(prev.x, prev.y, next.x, next.y);
// We just need to repaint the
// panel to make sure the
// changes are visible
// immediately.
panel.repaint();
prev = next;
}
}

@Override
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
prev = null;
}
if (SwingUtilities.isRightMouseButton(e)) {
rButtonDown = false;
}
}
};

PaintAnyTime() {
// RenderingHints let you specify
// options such as antialiasing.
imgG2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
imgG2.setStroke(new BasicStroke(3));
//
panel.setBackground(Color.white);
panel.addMouseListener(drawer);
panel.addMouseMotionListener(drawer);
Cursor cursor =
Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
panel.setCursor(cursor);
frame.setContentPane(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

PaintAnyTime screenshot


如果例程长时间运行并且重绘可能同时发生,则也可以使用双缓冲。绘图是对与显示的图像分开的图像进行的。然后,当绘图例程完成后,图像引用会被交换,因此更新是无缝的。

例如,您通常应该为游戏使用双缓冲。双缓冲可防止图像以部分状态显示。例如,如果您在游戏循环中使用后台线程(而不是 Timer)并且游戏正在重绘,则可能会发生这种情况。如果没有双缓冲,这种情况会导致闪烁或撕裂。

默认情况下,Swing 组件是双缓冲的,因此如果您的所有绘图都发生在 EDT 上,则您无需自己编写双缓冲逻辑。 Swing 已经做到了。

这是一个稍微复杂一些的例子,它显示了一个长时间运行的任务和一个缓冲区交换:

import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.*;

/**
* Left-click to spawn a new background
* painting task.
*/
class DoubleBuffer {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new DoubleBuffer();
}
});
}

final int width = 640;
final int height = 480;

BufferedImage createCompatibleImage() {
GraphicsConfiguration gc =
GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
// createCompatibleImage creates an image that is
// optimized for the display device.
// See http://docs.oracle.com/javase/8/docs/api/java/awt/GraphicsConfiguration.html#createCompatibleImage-int-int-int-
return gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}

// The front image is the one which is
// displayed in the panel.
BufferedImage front = createCompatibleImage();
// The back image is the one that gets
// painted to.
BufferedImage back = createCompatibleImage();
boolean isPainting = false;

final JFrame frame = new JFrame("Double Buffer");
final JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Scaling the image to fit the panel.
Dimension actualSize = getSize();
int w = actualSize.width;
int h = actualSize.height;
g.drawImage(front, 0, 0, w, h, null);
}
};

final MouseAdapter onClick = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (!isPainting) {
isPainting = true;
new PaintTask(e.getPoint()).execute();
}
}
};

DoubleBuffer() {
panel.setPreferredSize(new Dimension(width, height));
panel.setBackground(Color.WHITE);
panel.addMouseListener(onClick);
frame.setContentPane(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

void swap() {
BufferedImage temp = front;
front = back;
back = temp;
}

class PaintTask extends SwingWorker<Void, Void> {
final Point pt;

PaintTask(Point pt) {
this.pt = pt;
}

@Override
public Void doInBackground() {
Random rand = new Random();

synchronized(DoubleBuffer.this) {
Graphics2D g2 = back.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
RenderingHints.VALUE_STROKE_PURE);
g2.setBackground(new Color(0, true));
g2.clearRect(0, 0, width, height);
// (This computes pow(2, rand.nextInt(3) + 7).)
int depth = 1 << ( rand.nextInt(3) + 7 );
float hue = rand.nextInt(depth);
int radius = 1;
int c;
// This loop just draws concentric circles,
// starting from the inside and extending
// outwards until it hits the outside of
// the image.
do {
int rgb = Color.HSBtoRGB(hue / depth, 1, 1);
g2.setColor(new Color(rgb));

int x = pt.x - radius;
int y = pt.y - radius;
int d = radius * 2;

g2.drawOval(x, y, d, d);

++radius;
++hue;
c = (int) (radius * Math.cos(Math.PI / 4));
} while (
(0 <= pt.x - c) || (pt.x + c < width)
|| (0 <= pt.y - c) || (pt.y + c < height)
);

g2.dispose();
back.flush();

return (Void) null;
}
}

@Override
public void done() {
// done() is completed on the EDT,
// so for this small program, this
// is the only place where synchronization
// is necessary.
// paintComponent will see the swap
// happen the next time it is called.
synchronized(DoubleBuffer.this) {
swap();
}

isPainting = false;
panel.repaint();
}
}
}

绘画套路只是为了画垃圾,需要很长时间:

DoubleBuffer screenshot

关于java - 这是使用 Java 2D 图形 API 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21265576/

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