-2

My program is supposed to draw a simple line on the Swing generated panel. Everything else is fine except the one error produced by the drawLine command. This is my code:

public static void main(String[] args) {
     JFrame f = new JFrame("Swing Paint Demo");
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.pack();
     f.setVisible(true);
     Graphics.drawLine(20,20,20,20);
   }
}

It produces the error: Cannot make a static reference to the non-static method drawLine(int, int, int, int) from the type Graphics.

Any ideas?

Thanks in advance

Radiodef
  • 37,180
  • 14
  • 90
  • 125
APCoding
  • 303
  • 2
  • 19
  • 4
    You're trying to do graphics programming without reading the tutorial, by simply making up code, and that will never work. Read the tutorial. That's what it's there for. You can find links to the Swing tutorials and to other Swing resources here: [Swing Info](http://stackoverflow.com/tags/swing/info) – Hovercraft Full Of Eels May 09 '15 at 00:13

1 Answers1

2

You need to create a class that extends the swing widget (I'm assuming JPanel in this case) that you want to draw on, and override the paintComponent() method (which is inherited from the parent class of almost all swing components - JComponent).

Something like this would do:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    g.drawLine(20, 20, 20, 20);
}

EDIT: The reason for your error is that you're trying to use methods from the Graphics class directly, rather than from an instance of it. The Graphics class on its own doesn't know anything about your swing application, and has no idea how to draw on it. A better explanation of static can be found here. The swing tutorial linked to above would also be well worth reading.

moarCoffee
  • 1,289
  • 1
  • 14
  • 26
  • While true, it looks more like the OP needs to review basic lessons on how classes and objects work. – Radiodef May 09 '15 at 00:16
  • `paintComponent` should be `protected` not `public` since you should never increase the visibility of an inherited method unnecessarily. Also you should explain better what classes have this method and that should be inherited from. You state that he should "create a class that extends the swing object", but what is "the Swing object"? This will be very unclear to a newbie. – Hovercraft Full Of Eels May 09 '15 at 00:41