[英]My lines and ovals disappear when I resize or move scrollbars
我在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);
}
}
一看到您的标题,我便知道您正在使用通过Component#getGraphics()
获得的Graphics对象进行绘图。 不要这样
您不应使用通过在组件上调用getGraphics()
获得的Graphics对象进行绘制。 这将返回一个短暂存在的Graphics对象,可能会导致图形消失甚至更糟的是NullPointerException。 取而代之的是,直接或通过在BufferedImage上进行绘制来间接或间接地绘制JPanel的paintComponent(...)
方法(是的,您可以通过getGraphics()
获得其Graphics对象),然后在paintComponent方法中将BufferedImage绘制到GUI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.