我有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);
}
提前完成......
答案 0 :(得分:3)
当您的屏幕被覆盖时,Java会调用paintComponent()
来修复屏幕。如果您在paintComponent()
方法之外绘制,那么当屏幕修复后,您的额外绘图将被删除。
所以不要这样做:在paintComponent()
中完成所有绘图。当用户点击某处时,将要绘制的字符串和坐标添加到某种数据结构(即对象列表,每个对象包含一个字符串和一些坐标),然后调用repaint()
。在paintComponent()
方法中,查看该数据结构并绘制字符串。