Search code examples
javaswingawtgraphics2d

Unable to draw over a JPanel


I am trying to draw on a JPanel. When the function drawField is called, it draws nothing. What could be the reason for it?

private void drawField() {
    try {
        Graphics2D field = (Graphics2D) jPanel2.getGraphics();
        field.drawLine(0, 0, 100 , 100);
    }catch(Exception exc) { exc.printStackTrace();}
}

It is called from the main class constructor.


Solution

  • Override the paintComponent method on the panel.

    You cannot draw on a JPanel in the constructor. It is the inappropriate time to do that, and whatever you draw will be overridden as soon as the panel is painted. This happens as soon as it's made visible, so you'll never see what you drew.

    Instead, override the paintComponent method like this:

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawLine(0, 0, 100, 100);
    }
    

    This method gets called on the Event Dispatch Thread as part of the process of drawing the panel itself. This method will be called everytime the contents of the panel need to be painted again, so you are assured that your line will always show up.

    Remember also to set your drawing color to something different if the background is black, as it will default to that color.