0

At the moment my program is just supposed to make a black square, however a window appears with a white canvas with nothing in it:

public static void main(String[] args) {

        //basic window stuff
        JFrame mainWindow = new JFrame("Moving Square");
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainWindow.setVisible(true);
        mainWindow.setSize(800,600);
        mainWindow.setLocationRelativeTo(null);

        Canvas mainCanvas = new Canvas();
        mainWindow.add(mainCanvas);

        //making graphics context for the canvas.
        Graphics g = mainCanvas.getGraphics();
        g.setColor(Color.black);
        g.fillRect(250, 250, 250, 250);

    }

What's the issue here? Have I misunderstood the usage of Graphics? (And before anyone suggests, I have already looked at docs and haven't been able to figure out the issue)

Psear
  • 105
  • 8
  • 1
    You're looking at the wrong docs. Your Swing drawing is being done incorrectly. You should not draw with a Graphics object obtained by calling `getGraphics()` on a component. This will return a Graphics object that is short lived, risking disappearing graphics or worse, a NullPointerException. Instead, draw in the JPanel's `paintComponent(...)` method either directly, or indirectly by drawing on a BufferedImage (yes, you can get its Graphics object via `getGraphics()`) and then drawing the BufferedImage to the GUI within the paintComponent method. – Hovercraft Full Of Eels Nov 30 '17 at 19:32
  • 5
    A better "doc": [Lesson: Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html): introductory tutorial to Swing graphics – Hovercraft Full Of Eels Nov 30 '17 at 19:32
  • Ah I think I remember hearing something along these lines, thanks! But for clarification, can you explain the difference between the paintComponent, paint and repaint methods? – Psear Nov 30 '17 at 19:37
  • 1
    `can you explain the difference between the paintComponent, paint and repaint methods?` - that is what the tutorial link is for. – camickr Nov 30 '17 at 19:42
  • 2
    The tutorial that @hover links to explains this already. For gory details, check out the more advanced [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html) – DontKnowMuchBut Getting Better Nov 30 '17 at 19:43
  • @Psear [paintComponent() vs paint() and JPanel vs Canvas in a paintbrush-type GUI](https://stackoverflow.com/questions/12175174/paintcomponent-vs-paint-and-jpanel-vs-canvas-in-a-paintbrush-type-gui/12175819#12175819) – MadProgrammer Nov 30 '17 at 20:37

0 Answers0