我想首先删除按钮,然后在函数cam()中执行内容

时间:2015-12-30 08:03:18

标签: java eclipse user-interface

代码:

p.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        System.out.println("Welcome to Guess the number Game");
        System.out.println("You have 3 chances to guess a number between 0 and 10 excluding 10");

        ne.remove(p);

        // ne.removeAll();
        ne.revalidate();
        ne.repaint();
    }

    public void cam() {

        gamer2 game = new gamer2();
        game.generatenum();
    }
});

p是一个JButton。

  • 我未在cam()内调用actionPerformed()的原因是,如果我执行此操作,则只会在generatenum()执行后删除该按钮。我希望首先删除该按钮。

1 个答案:

答案 0 :(得分:1)

cam()方法属于匿名类(ActionListener' s子类),在这个匿名类中没有方法调用cam()。这就是为什么你收到那个警告

在我看来,你应该这样做

p.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        System.out.println("Welcome to Guess the number Game");
        System.out.println("You have 3 chances to guess a number between 0 and 10 excluding 10");

        ne.remove(p);

        // ne.removeAll();
        ne.revalidate();
        ne.repaint();
        cam();
    }

});

public void cam() {

    gamer2 game = new gamer2();
    game.generatenum();
}

或者你可以这样做

p.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        System.out.println("Welcome to Guess the number Game");
        System.out.println("You have 3 chances to guess a number between 0 and 10 excluding 10");

        ne.remove(p);

        // ne.removeAll();
        ne.revalidate();
        ne.repaint();
        cam();
    }

    public void cam() {

        gamer2 game = new gamer2();
        game.generatenum();
    }
});