简体   繁体   中英

repaint() not calling paintComponent() in java

I am writing what should be a simple piece of code that creates a JFrame object and then paints the background black and draws a blue square. However, the repaint() method is not calling the paintComponent() method.

This is the code:

import java.util.Vector;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Container;

public class Snake extends JPanel{
        private Vector xCoords = new Vector();
        private Vector yCoords = new Vector();

        public Snake(){
                xCoords.add(150);
                yCoords.add(150);
        }

        public void startJFrame(){
                JFrame window = new JFrame();
                window.setSize(300, 300);
                window.setVisible(true);
                window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                Container c = window.getContentPane();
                c.setBackground(Color.black);
        }

        public void paintRequest(){
                System.out.println("Request to paint received.");
                repaint();
        }

        public void paintComponent(Graphics g){
                super.paintComponent(g);
                System.out.println("paintComponent was called");
                g.setColor(Color.blue);
                int x = (int)xCoords.get(0);
                int y = (int)yCoords.get(0);
                g.fillRect(x, y, 10, 10);
        }

        public static void main(String[] args){
                Snake mkFrame = new Snake();
                mkFrame.startJFrame();
                mkFrame.paintRequest();
        }
}

I know that paintRequest() is being called properly because it prints "Request to paint received", but "paintComponent was called" is never printed. On the gui side, the JFrame window is created and it has a black background, but there is no blue square. Thank you in advance for the help.

There is no Snake ever added to the frame!

Change:

    JFrame window = new JFrame();

To:

    JFrame window = new JFrame();
    window.add(new Snake());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM