Search code examples
javaswinggraphicsjpaneldraw

Can't draw to canvas: "cannot be applied to given types"


I used a border layout and I put a canvas in the center; where the main game will be, but I can't draw anything to it.

Could anyone point me in the right direction?

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

public class TestingGraphics {

    public static void main (String[] args) {
          GameScene window = new GameScene();
    }
}
import java.awt.*;
import javax.swing.*;

public class GameScene extends JFrame {
       
    Canvas gameCanvas;
    Graphics Pencil;
    JPanel game;
   
    public GameScene() {
        game = new JPanel();
        add(game);

        setTitle("Yet to name this thing.");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
      
        gameCanvas = new Canvas();
        gameCanvas.setPreferredSize(new Dimension(1280, 720));
        game.add(gameCanvas);
     
        drawString();
      
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
   
    public void drawString(Graphics Pencil) {
         Pencil.drawString("boo", 100, 100);
    }
}   

Solution

  • Your problem is that you're making wild guesses on how to draw in Swing and that never works, and your errors include trying to draw directly within a JFrame, trying to call a method without passing in necessary parameters, drawing outside of any painting method.... First and foremost, go to the Swing drawing tutorials which you can find here: Swing Drawing Tutorials -- and read them.

    Next, do as they tell you:

    • Create a class that extends JPanel
    • Draw in the paintComponent method override of that class, not directly in a JFrame
    • Be sure to call the super's paintComponent method in your overridden method.
    • Add your JPanel to a top-level window such as a JFrame
    • Display the GUI
    • Done.