【发布时间】:2018-12-31 05:47:00
【问题描述】:
我正在制作一个游戏,其中需要在一组程序之后更新屏幕(不是每帧都持续更新),我制作了一个较小的程序来测试 Graphics2D 绘图。在这个程序中,我想做的就是在角落里画一个小矩形。但是,矩形似乎没有绘制。我不确定我是否误解了 BufferStrategy 的使用(即有更好的方法来更新游戏),但我尝试调用 draw 方法两次以确保 graphics2D 对象存在且不为空。
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import javax.swing.*;
public class test extends Canvas
{
private JFrame testWindow = new JFrame("Test");
public test()
{
createUI();
}
public static void main(String[] args)
{
new test();
}
public void createUI()
{
testWindow.setSize(500,500);
testWindow.setLayout(null);
testWindow.setLocationRelativeTo(null);
testWindow.setResizable(false);
testWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testWindow.add(this);
testWindow.setVisible(true);
draw();
draw();
}
public void draw()
{
BufferStrategy bs = this.getBufferStrategy();
System.out.println(bs);
//when the program runs this prints null once and then an identifier
if(bs == null)
{
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
g2.fillRect(10,10,100,100);
g2.dispose();
bs.show();
}
}
【问题讨论】:
-
我建议你看看这个 Java Swing 教程Performing Custom Painting。
标签: java swing graphics2d