0

I want to draw lines between two JPanels ; please verify my code as its giving an NULL pointer Exception at "g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);"

Code::

Draw(JPanel one , JPanel two)
{
    //Draw Line
     Graphics2D g=null;
     Graphics2D g2d = (Graphics2D) g;
     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
     RenderingHints.VALUE_ANTIALIAS_ON);
     g2d.setColor(Color.lightGray);
     2d.fillRect(0, 0, getWidth(), getHeight());
     g2d.setColor(Color.black);
     Stroke s = new BasicStroke(4.0f);


    // For getting the points of JPanel ona and two//

     int x1 = one.getX() + one.getWidth() / 2;
     int y1 = one.getY() + one.getHeight() / 2;
     int x2 = one.getX() + one.getWidth() / 2;
     int y2 = two.getY() + two.getHeight() / 2;

    //Drawing line
     g2d.drawLine(x1, y1, x2, y2);
}
Asd
  • 103
  • 2
  • 12

2 Answers2

4

Because you are casting and storing NULL value to g2d.

Look at this code:

Graphics2D g=null;
Graphics2D g2d = (Graphics2D) g;

In the first line, g is NULL. And it is being cast and assigned to g2d. So, g2d becomes NULL which means it can't be used.

Ravi Trivedi
  • 2,340
  • 2
  • 14
  • 20
  • what to do then ? suggestions ? – Asd May 18 '13 at 10:18
  • It is highly unrecommended to override `paint` of any component. I'm also fairly certain that if you did override the `paint` method of the parent container, it would still not work properly. Spent some time with a similar question and run into that problem my self – MadProgrammer May 18 '13 at 10:32
  • @asd, please refer MadProgrammer's answer on how to accurately use Graphics component – Ravi Trivedi May 18 '13 at 10:37
  • Just a reference for both of you, check out [Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/) and [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html) for more details about painting in Swing ;) – MadProgrammer May 18 '13 at 10:39
  • how to include panels ?? JPanel one and JPanel two paint(Graphics,JPanel one,JPanel two) is not working – Asd May 18 '13 at 10:45
  • @asd, please post any new code in the Question. it is easy to read and follow. – Ravi Trivedi May 18 '13 at 10:47
1

You have a number of options.

The basic premises is, you need some way to paint "over" the top of the current container (and it's children).

You could, override the paint method of the parent container, but this HIGHLY unrecommended as it can produce a lot of nasty side-effects.

A better solution would to take advantage of the JRootPane's glass pane

  • Check here for more details.
  • Check here for an example

You could also use JXLayer (or JLayer as it's known in Java 7) to achieve the same results, but I don't have an example readily available

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366