[英]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.