Repaint() doesn't clear the frame

前端 未结 3 405
故里飘歌
故里飘歌 2020-12-19 18:45
public class Graphics2DTest extends JPanel implements ActionListener{
private Timer time = new Timer(5,(ActionListener) this);
int x = 0,y = 0;
public void paintComp         


        
相关标签:
3条回答
  • 2020-12-19 18:53

    You need to clear the background first.

    A resource is this:

    http://java.sun.com/products/jfc/tsc/articles/painting/

    0 讨论(0)
  • 2020-12-19 18:58

    You need to repaint the background each time as well. Add code to paint the background before you paint the rectangle.

    0 讨论(0)
  • 2020-12-19 19:16

    Have you tried calling super.paintComponent(g) in your paintComponent method? This will clear prior images drawn in your JPanel:

    public void paintComponent(Graphics g){
      super.paintComponent(g);
      Graphics2D gui = (Graphics2D) g;
      Rectangle2D rectangle = new Rectangle2D.Double(x,y,100,150);
      gui.setPaint(Color.GREEN);
      gui.fill(rectangle);
      //time.start();
    }
    

    Also, don't start a timer or do any program logic within the paintComponent method. First of all you cannot absolutely control when or if the method will be called, and secondly, this method must be concerned only with painting and nothing else, and needs to be as fast as possible.

    For instance:

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    
    import javax.swing.*;
    
    public class Graphics2DTest extends JPanel implements ActionListener {
        private Timer time = new Timer(5, (ActionListener) this);
        int x = 0, y = 0;
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D gui = (Graphics2D) g;
            Rectangle2D rectangle = new Rectangle2D.Double(x, y, 100, 150);
            gui.setPaint(Color.GREEN);
            gui.fill(rectangle);
            //time.start();
        }
    
        public void actionPerformed(ActionEvent arg0) {
            x++;
            y++;
            repaint();
        }
    
        public Graphics2DTest() {
            setPreferredSize(new Dimension(700, 500));
            time.start();
        }
    
        private static void createAndShowUI() {
            JFrame frame = new JFrame("Graphics2DTest");
            frame.getContentPane().add(new Graphics2DTest());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    createAndShowUI();
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题