我有一个JPanel
,使用paintComponent
方法在其上执行一些绘制,之后当用户单击JPanel
时,会出现一个字符串在其上绘制(或任何绘图),当用户将鼠标移到 JPanel
上时,它会在 JPanel
的工具提示中显示坐标。
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);
}
提前致谢......
最佳答案
当您的屏幕被覆盖时,Java 会调用 paintComponent()
来修复屏幕。如果您在 paintComponent()
之外绘制方法,那么当屏幕固定好后,你多余的图画就会被删除。
所以不要这样做:在 paintComponent()
中完成所有绘图。当用户单击某处时,将要绘制的字符串和坐标添加到某种数据结构(即对象列表,每个对象包含一个字符串和一些坐标),然后调用 repaint()
。在你的paintComponent()
方法,查看该数据结构并绘制字符串。
关于java - 工具提示文本删除java中的面板绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7190645/