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