Canvas fillRect() not filling defined canvas

后端 未结 1 1525
旧时难觅i
旧时难觅i 2021-01-24 19:02

I am extending a Canvas and adding it to a JFrame. I understand that AWT and Swing should not be mixed and that drawing on JPanel is preferred but i\'m

1条回答
  •  后悔当初
    2021-01-24 19:23

    The example you've provide works fine. I modified it a little to demonstrate the use of getWidth/height

    enter image description here

    public void run() {
        while (gameRunning) {
            Graphics2D graphics = (Graphics2D) bufferStrategy.getDrawGraphics();
    
            graphics.setColor(Color.RED);
            graphics.fillRect(0, 0, getWidth(), getHeight());
            graphics.setColor(Color.GREEN);
            int width = getWidth() - 50;
            int height = getHeight() - 50;
            graphics.fillRect(25, 25, width, height);
            graphics.setColor(Color.BLACK);
            FontMetrics fm = graphics.getFontMetrics();
            graphics.drawString("Frame Size: " + frame.getWidth() + "x" + frame.getHeight(), 0, fm.getAscent());
            graphics.drawString("Canvas Size: " + getWidth() + "x" + getHeight(), 0, fm.getAscent() + fm.getHeight());
    
            graphics.dispose();
            bufferStrategy.show();
            try {
                Thread.sleep(60);
            } catch (InterruptedException ex) {
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题