我想在两个JPanel之间绘制线条;请验证我的代码是否给出了一个NULL指针Exception at “g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);”
代码::
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);
}
答案 0 :(得分:4)
因为您投射且存储 NULL
值为g2d
。
看看这段代码:
Graphics2D g=null;
Graphics2D g2d = (Graphics2D) g;
在第一行中,g
为NULL
。它正在投射并分配给g2d
。因此,g2d
变为NULL
,这意味着无法使用它。
答案 1 :(得分:1)