Circles disappear when maximizing, minimizing or resizing my JFrame.
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | JFrame frame = new JFrame(); frame.setSize(400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JPanel panel1 = new JPanel(){ @Override protected void paintComponent(Graphics g) { int w = getWidth(); int h = getHeight(); for (int i = 0; i < w; i+=100) { g.drawLine(i, 0, i, h); } } }; panel1.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseClicked(MouseEvent arg0) { int x = arg0.getX(); int y = arg0.getY(); Graphics g = (Graphics) panel1.getGraphics(); g.setColor(Color.black); g.fillOval(x, y, 100, 100); } }); frame.add(panel1); frame.setVisible(true); |
它的作用是当我点击画一个圆圈的框架。当我最大化或最小化或调整框架大小时画了一些圆圈后,圆圈消失了。我该如何解决呢?
您应该覆盖面板的paintComponent() 方法。圆圈应添加到列表中。在 paintComponent() 调用 super 然后遍历列表绘制每个圆圈。