从我认为是静态的动作监听器,我试图从类中调用非静态方法。我如何从班上打电话给我的方法?
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;
}
}
答案 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);
}
}