Java paint line in existing JPanel with components

Tags: , ,

I’ve been searching for a few hours, including at other questions on stack such as. I need simplest way to draw a line in java in AWT panel

but couldn’t find my answer.

I have a panel gridbaglayout with multiple dynamically generated components. The class extends JFrame and thus can’t extends JPanel as in the question above.

After all the components are added I need to draw lines from 1 to the other,

I got all the coordinates but can’t seem to paint a line.

when using this:

public void paint(Graphics g) {
   g.drawline(100,100,200,200) //I used static values to test first.

a Line will be drawn but the other components are not shown.

When I do this (in the constructor after adding all components etc..):

   Graphics g = getGraphics(); //class extends JFrame thus I can call getGraphics() directly.
   g.drawLine(100,100,400,400); //again static values for test purposes.

All my components are shown but the line isn’t. -> just the same as without the code.

What would be a valid solution for me to call a method with the x1 x2 y1 y2 as paremeters that draws a line in the panel (or frame) with the already existing components?


What you should do is:

  1. Override paintComponent() instead of paint().
  2. First line of paintComponent should call the parent constructor.
  3. Then draw your line.

So it should be something along the lines of:

public void paintComponent(Graphics g) {
    super.paintComponent(g); // this will paint your components
    g.drawLine(100,100,400,400); // this will paint your line

For more information you should check out the Custom Painting Tutorial.

Source: stackoverflow