gpt4 book ai didi

java - 更新作为 JFrame 组件的 java Canvas

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

如何从属于 JFrame 组件的 Canvas 的任何类更新屏幕上的图形?我相信它是 JFrame.update(Graphics g)。但我不确定。如果是 JFrame.update(Graphics g),正确的调用方式是什么,从哪里获取参数的 Graphics 对象?

最佳答案

只需调用repaint()即可。

您想要进行的任何自定义绘画都应该在 paintComponent(Graphics) 中完成,并且一定要调用 super.paintComponent(g);

一般来说,将 Graphics 实例的处理留给 Swing。它将提供符合自己标准的自己的产品。

This Oracle tutorial shows just that

<小时/>

下面是一个使用 Swing Timer 每 15 毫秒从 JFrame 请求重绘更新的示例。

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.WindowConstants;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

/**
* @author Obicere
*/
public class ShapeDrawer {

public ShapeDrawer() {
final JFrame frame = new JFrame("Shape Drawer");
final MyPanel panel = new MyPanel();

frame.add(panel);

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);

createRepaintTimer(frame);
}

// Just makes calls for the frame to paint every 15 milliseconds
private void createRepaintTimer(final JFrame frame) {
final Timer timer = new Timer(15, null);

timer.addActionListener(e -> {
if (!frame.isVisible()) {
timer.stop();
} else {
frame.repaint();
}
});

timer.start();
}

public static void main(final String[] args) {
SwingUtilities.invokeLater(ShapeDrawer::new);
}

public class MyPanel extends JPanel {

private long start;

public MyPanel() {
start = System.currentTimeMillis();
}

@Override
protected void paintComponent(final Graphics g) {
// Calling to clear the artifacts!
super.paintComponent(g);

g.setColor(Color.RED);

// Difference between when the current time and when we started
final long difference = System.currentTimeMillis() - start;

// Difference in seconds
final double seconds = difference / 1000d;

// 1 rotation per second
final double rotation = seconds * 1440 / 1000;

final int x = (int) (Math.cos(rotation) * 100);
final int y = (int) (Math.sin(rotation) * 100);

g.drawOval(200 + x - 5, 200 + y - 5, 10, 10);
}

// Just setting the default size of the panel
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}

}

}

如您所见,createRepaintTimer(JFrame) 方法进行调用以请求更新图形。我们不必提供 Graphics 实例,Swing 会为我们处理这个问题。然后,我们在调用 super.paintComponent(Graphics) 后渲染到 MyPanel#paintComponent(Graphics) 方法中为我们提供的 Graphics swing。

关于java - 更新作为 JFrame 组件的 java Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449436/

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