从非静态Java获取静态(ActionListener)

时间:2013-06-25 19:43:56

标签: java swing static actionlistener

从我认为是静态的动作监听器,我试图从类中调用非静态方法。我如何从班上打电话给我的方法?

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

1 个答案:

答案 0 :(得分: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);


}

}