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);
}
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.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.