当我调整大小或移动滚动条时,我的线条和椭圆消失了

时间:2015-11-27 14:55:34

标签: java swing jpanel jscrollpane graphics2d

我在netbeans设计模式下的jSrollbarPane中有一个j面板。我想在其上永久绘画,直到用户按下“清除”按钮。当我在UI上调整大小或移动滚动条时,我在path()中创建的线条和椭圆会消失。

我的代码段在下面,提前谢谢

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { 
//i create some public double arrays here like x[] and y[]
}

 private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      

        path(x, y, 0);
    }    
 public void path(double[] X, double[] Y, int type) {
        Graphics2D gfx = (Graphics2D) jPanel1.getGraphics();
        int xT, yT, xL, yL;
        getContentPane();
        scale = jSlider1.getValue();
        switch (type) {
            case 0:
                gfx.setStroke(new BasicStroke(3));
                break;
            case 1:
                gfx.setStroke(new BasicStroke(1));
                gfx.setPaint(Color.blue);
                break;
            case 2:
                gfx.setStroke(new BasicStroke(1));
                gfx.setPaint(Color.green);
                break;
            case 3:
                gfx.setStroke(new BasicStroke(1));
                gfx.setPaint(Color.red);
                break;
            default:
                gfx.setStroke(new BasicStroke(1));
                gfx.setPaint(Color.yellow);
                break;
        }

        for (int l = 1; l < size; l++) {
            xT = (int) (scale * X[l - 1]);
            yT = (int) (scale * Y[l - 1]);
            xL = (int) (scale * X[l]);
            yL = (int) (scale * Y[l]);

            gfx.drawOval(xT, yT, 5, 5);
            gfx.drawLine(xT, yT, xL, yL);

        }
    } 

1 个答案:

答案 0 :(得分:3)

当我看到你的标题时,我知道你正在使用通过Component#getGraphics()获得的Graphics对象进行绘制。不要这样做。

您不应使用通过在组件上调用getGraphics()获得的Graphics对象进行绘制。这将返回一个短暂的Graphics对象,冒着消失的图形或者更糟的是NullPointerException。相反,直接或通过绘制BufferedImage(是的,您可以通过paintComponent(...)获取其Graphics对象)间接绘制JPanel的getGraphics()方法,然后在paintComponent方法中将BufferedImage绘制到GUI