简体   繁体   中英

ActionListener doesn't seem to be working?

I wanted to make a 2D game. I started making the drawing class, but I came across a problem: the ActionListener wouldn't work. It wouldn't draw or output my message to say it was working. Here is the code:

public class Drawing extends JPanel implements ActionListener {

    private int count = 0;

    public void actionPerformed(ActionEvent e) {
        count++;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        System.out.println("Hi");
        g.setColor(Color.black);
        g.clearRect(0, 0, Boot.WIDTH, Boot.HEIGHT);
        g.fillRect(0, 0, Boot.WIDTH, Boot.HEIGHT);

        g.setColor(Color.white);
        g.drawString("Path count: " + count, 50, 50);
    }
}

I would assume this would work, as I used this way of drawing in other projects. What would be causing this?

You're not supposed to keep a reference to a Graphics object and call paint() directly. You're supposed to call repaint() , and wait for Swing to call the paintComponent() method, that you should override to perform your custom paintings on the Graphics object that Swing passes as argument to the method.

See http://java.sun.com/products/jfc/tsc/articles/painting/index.html for more information.

public class Drawing extends JPanel implements ActionListener {

    private int count = 0;

    public void actionPerformed(ActionEvent e) {
        count++;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        System.out.println("Hi");
        g.setColor(Color.black);
        g.clearRect(0, 0, Boot.WIDTH, Boot.HEIGHT);
        g.fillRect(0, 0, Boot.WIDTH, Boot.HEIGHT);

        g.setColor(Color.white);
        g.drawString("Path count: " + count, 50, 50);
    }
}

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