[英]My lines and ovals disappear when I resize or move scrollbars
i have aj Panel in a jSrollbarPane in netbeans design mode. 我在netbeans设计模式下的jSrollbarPane中有一个j面板。 I want to paint permanently on it untill user presses the button "clear".
我想在其上永久涂漆,直到用户按下“清除”按钮。 My lines and ovals created in path() disappear when I resize or move scrollbars on UI.
在UI上调整大小或移动滚动条时,在path()中创建的线条和椭圆形消失。
My code segment is below, thank you in advance 我的代码段如下,在此先感谢您
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);
}
}
As soon as I saw your title, I knew that you were drawing using a Graphics object obtained via Component#getGraphics()
. 一看到您的标题,我便知道您正在使用通过
Component#getGraphics()
获得的Graphics对象进行绘图。 Don't do this. 不要这样
You should not draw with a Graphics object obtained by calling getGraphics()
on a component. 您不应使用通过在组件上调用
getGraphics()
获得的Graphics对象进行绘制。 This will return a Graphics object that is short lived, risking disappearing graphics or worse, a NullPointerException. 这将返回一个短暂存在的Graphics对象,可能会导致图形消失甚至更糟的是NullPointerException。 Instead, draw in the JPanel's
paintComponent(...)
method either directly, or indirectly by drawing on a BufferedImage (yes, you can get its Graphics object via getGraphics()
) and then drawing the BufferedImage to the GUI within the paintComponent method. 取而代之的是,直接或通过在BufferedImage上进行绘制来间接或间接地绘制JPanel的
paintComponent(...)
方法(是的,您可以通过getGraphics()
获得其Graphics对象),然后在paintComponent方法中将BufferedImage绘制到GUI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.