2011-08-25 11 views
2

我有一個JPanel,其中使用paintComponent方法執行一些繪圖,之後當用戶點擊JPanel時,繪製一個字符串(或任何繪圖)並隨着用戶移動將鼠標懸停在JPanel上,它將顯示JPanel工具提示中的座標。tooltip文本在java中刪除面板繪圖

1)問題是,當工具提示超出了繪製的字符串時,它會將其刪除,但是此工具提示文本對於我在paintComponent方法中執行的繪圖部分沒有擦除效果。我無法理解爲什麼會發生這種情況。

2)而且,當我點擊字符串,然後最小化和恢復我的應用程序我畫的字符串都消失了。

希望你都明白我的意思。

下面是代碼:

@Override 
public void paintComponent(Graphics graphics) { 
    super.paintComponent(graphics); 
    Graphics2D graphics2D = (Graphics2D) graphics; 
    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
      RenderingHints.VALUE_ANTIALIAS_ON); 

    drawBorder(graphics2D); 
    drawGrid(graphics2D); 
} 

private void drawBorder(Graphics2D graphics2D) { 
    graphics2D.setColor(Color.ORANGE); 
    graphics2D.setStroke(new BasicStroke(borderStroke)); 
    graphics2D.drawRoundRect(panelStartLoc.x, panelStartLoc.y, panelBorder.width, 
      panelBorder.height, borderRoundness, borderRoundness); 
} 

private void drawGrid(Graphics2D graphics2D) { 
    graphics2D.setColor(Color.ORANGE); 
    graphics2D.setStroke(new BasicStroke(gridCellStroke)); 

    for (int row = gridStartLoc.x; row < panelBorder.getWidth(); row += cellWidth + cellHorGap) { 
     for (int col = gridStartLoc.y; col < panelBorder.getHeight(); col += cellHeight + cellVerGap) { 
      graphics2D.drawRoundRect(row, col, cellWidth, cellHeight, cellRoundness, cellRoundness); 
     } 
    } 
} 

public void drawSubjectAtClickLoc(int subjectCode) { 
    Color color = getBackground(); 
    String drawString = null; 
    int subjectDrawXLoc = cellClickLoc.x + 4; 
    int subjectDrawYLoc = (cellClickLoc.y + cellHeight) - 3; 
    Graphics2D graphics2D = (Graphics2D) getGraphics(); 

    if (subjectCode == SUBJECT_CLEAR) { 
     graphics2D.setColor(getBackground()); 
     graphics2D.fillRoundRect(cellClickLoc.x + 2, cellClickLoc.y + 2, cellWidth - 4, 
       cellHeight - 4, cellRoundness, cellRoundness); 
     return; 
    } 
    if (subjectCode == SUBJECT_HUMAN) { 
     color = Color.WHITE; 
     drawString = "H"; 
    } 
    if (subjectCode == SUBJECT_RESOURCE) { 
     color = Color.GREEN; 
     drawString = "R"; 
    } 

    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
      RenderingHints.VALUE_ANTIALIAS_ON); 
    graphics2D.setFont(new Font(null, Font.BOLD, 26)); 
    graphics2D.setColor(color); 
    graphics2D.drawString(drawString, subjectDrawXLoc, subjectDrawYLoc); 
} 

thanx提前....

回答

3

當你的屏幕覆蓋,Java調用paintComponent()修復屏幕。如果您在paintComponent()方法之外繪圖,那麼當屏幕固定時,您的額外繪圖將被刪除。

所以不要這樣做:做所有你的圖紙在paintComponent()。當用戶點擊某處時,將要繪製的字符串和座標添加到某種數據結構(即對象列表,每個對象包含一個字符串和一些座標),然後調用repaint()。在您的paintComponent()方法中,查看該數據結構並繪製字符串。

+0

所以我可以說繪圖應用程序在內存中維護繪製對象的數據結構。是這樣嗎? –

+0

是的,就是這樣。 –

+0

非常感謝...... –