简体   繁体   English

在两个JPanel之间画线

[英]Drawing line between two JPanels

I want to draw lines between two JPanels ; 我想在两个JPanel之间画线; please verify my code as its giving an NULL pointer Exception at "g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);" 请在“ g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);”中验证我的代码是否为其提供了NULL指针异常。

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 . 因为您正在 NULL转换存储g2d

Look at this code: 看下面的代码:

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

In the first line, g is NULL . 在第一行中, gNULL And it is being cast and assigned to g2d . 并将其g2d并分配给g2d So, g2d becomes NULL which means it can't be used. 因此, g2d变为NULL ,这意味着它无法使用。

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. 您可以覆盖父容器的paint方法,但是不建议这样做,因为它会产生很多讨厌的副作用。

A better solution would to take advantage of the JRootPane 's glass pane 更好的解决方案是利用JRootPane的玻璃窗格

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 您也可以使用JXLayer (或Java 7中的JLayer )来达到相同的结果,但是我没有一个可用的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM