简体   繁体   English

ActionListener似乎没有工作?

[英]ActionListener doesn't seem to be working?

I wanted to make a 2D game. 我想制作2D游戏。 I started making the drawing class, but I came across a problem: the ActionListener wouldn't work. 我开始制作绘图课程,但我遇到了一个问题: ActionListener不起作用。 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. 你不应该保持对Graphics对象的引用并直接调用paint() 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. 您应该调用repaint() ,并等待Swing调用paintComponent()方法,您应该覆盖该方法以在Swing作为方法参数传递的Graphics对象上执行自定义绘制。

See http://java.sun.com/products/jfc/tsc/articles/painting/index.html for more information. 有关详细信息,请参阅http://java.sun.com/products/jfc/tsc/articles/painting/index.html

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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