java此代码不会显示矩形,但它应该
我正在做一个JFrame并在上面画一个矩形。 它不起作用,有时完全是黑色的,有时完全是白色的,以下是我的方法
所以render方法被调用了两次,因为它第一次创建缓冲区时,也忽略了帧率,现在是不相关的
Edit1:我解决了一个问题: 它现在正在绘制一个矩形,但有时它只是显示一个白色屏幕。我仍然需要解决这个问题
Edit2:我不仅在寻找解决方案,也在寻找问题发生的原因,所以我不仅仅是盲目地编写代码
public MyFrame(String title,int width,int height)
{
super(title);
this.setSize(width,height);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setUndecorated(true);
this.addKeyListener(new KeyInput());
this.setVisible(true);
}
public void draw(Graphics2D g,int arg)
{
g.setColor(new Color(0,0,0,255));
g.fillRect(0,0,SIZE,SIZE);
g.setColor(new Color(255,255,255));
g.fillRect(0,0,50,50);
}
public void render(int arg)
{
BufferStrategy bs=this.getBufferStrategy();
if(null==bs)
{
this.createBufferStrategy(3);
}
else
{
Graphics2D g=(Graphics2D)bs.getDrawGraphics();
g.setColor(new Color(0,0,0,255));
g.fillRect(0,0,this.getWidth(),this.getHeight());
BufferedImage canvas=new BufferedImage(SIZE,SIZE,2);
int s=Math.min(this.getWidth(),this.getHeight());
g.drawImage(canvas,(this.getWidth()-s)/2,(this.getHeight()-s)/2,s,s,this);
Graphics2D g2=canvas.createGraphics();
this.draw(g2,arg);
bs.show();
g.dispose();
g2.dispose();
}
}
public static void main(String[] args)
{
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
FRAME=new MyFrame("Insert name here!",d.width,d.height,1);
FRAME.render(0);
FRAME.render(0);
}
编辑:这不再是必要的,我已经设法解决了这个问题,无论如何谢谢你的帮助
# 1 楼答案
你需要的所有信息都可以在建议的tutorial气垫船上找到
下面的代码演示如何绘制一个全屏大小的黑色矩形
JFrame
,以及一些关于mcve的附加信息