简体   繁体   中英

Java: paint doesn't call with repaint

Let me be honest, I'm not really know what I'm doing. I just moved from python to Java, and i'm still trying to get used to all the classes and the types things.

I decide to make a break with java concepts tutorials and start to get my hands dirty. According to my understanding, I'm using swing to paint a ball on the screen and make it move.

I tried to design a ball object that handle the ball position and the screen bumping, but the ball doesn't moved at all. When I turn on the debug I noticed that the paint() function get called only at creation, but not get called with repaint().

I got a feeling that I'm using a bad tutorial to do this stuff, its look like there is a better way to do it.

Anyway, I will be glad to hear what you guys thinking.

Edit: After I saw your comments I notice that paint actually get called when I put sysout there. Its seems that the debugger doesn't jump to there before I put sysout in paint() . My guess is that I'm not really changing the position of the ball.

@SuppressWarnings("serial")
public class Tennis extends JPanel {
    Ball ball = new Ball(50,50);

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                RenderingHints.VALUE_ANTIALIAS_ON);
        int[] position = ball.getPosition();
        g2d.fillOval(position[0],position[1], 30, 30);
    }

    public static void main(String[] args) {

        JFrame frame = new JFrame("Mini Tennis");

        Tennis game = new Tennis();
        frame.add(game);
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        while (true) {
            // just change the position and check for bump
            game.ball.move(game.getHeight(), game.getWidth());
            game.repaint();

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

Change paint() to paintComponent(), for an explanation of the differences therein see this .

@Override
public void paintComponent(Graphics g){ //CHANGE HERE
    super.paintComponent(g);            //AND HERE
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
            RenderingHints.VALUE_ANTIALIAS_ON);
    int[] position = ball.getPosition();
    g2d.fillOval(position[0],position[1], 30, 30);
}

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