我在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 风险。相反,可以直接在 JPanel 的 paintComponent(...)
方法中进行绘制,或者通过在 BufferedImage 上进行绘制来间接进行绘制(是的,您可以通过 getGraphics()
获取其 Graphics 对象),然后在 PaintComponent 方法中将 BufferedImage 绘制到 GUI。
关于java - 当我调整大小或移动滚动条时,我的线条和椭圆消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33959982/