1

从我认为是静态的动作监听器中,我试图从一个类中调用一个非静态方法。我怎样才能从我的课堂上调用我的方法?

public class addContent {

    User Darryl = new User();
    public static void addStuff(){

        //Panel and Frame
        JPanel panel = new JPanel(new BorderLayout());
        JFrame frame = new JFrame("PandaHunterV3");
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new FlowLayout());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Setup labels
        JLabel label = new JLabel("Label");
        frame.getContentPane().add(label);

        //Setup buttons
        JButton button = new JButton("Button");
        frame.getContentPane().add(button);

        //Action listener
        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                Darryl.showHealth();    // HERE IS THE PROBLEM. 
            }
        });

        //Crap
        frame.pack();
        frame.setVisible(true);   
    }
}

以及我试图从中调用方法的班级

public class User {

    int health;

    User(){
        health = 50;
    }

    public void showHealth(){        
        System.out.print(health);
    }

    public void incHealth(){
        health += 20;
    }    
}
4

1 回答 1

6

编辑:将Daryl实例标记为静态或方法标记addStuff()为非静态。

顺便提一句。使用小写来命名变量/实例,使用大写来命名类名。

public class AddContent {
    private User darryl = new User();

    public void addStuff(){

        //Panel and Frame
        JPanel panel = new JPanel(new BorderLayout());
        JFrame frame = new JFrame("PandaHunterV3");
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new FlowLayout());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Setup labels
        JLabel label = new JLabel("Label");
        frame.getContentPane().add(label);
        //Setup buttons
        JButton button = new JButton("Button");
        frame.getContentPane().add(button);
        //Action listener
        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                AddContent.this.darryl.showHealth();    // SHOULD BE FINE
            }
        });
        //Crap
        frame.pack();
        frame.setVisible(true);


}

}
于 2013-06-25T19:45:56.520 回答