【发布时间】:2011-08-17 20:08:40
【问题描述】:
好的,使用 Eclipse IDE 并被静态/非静态问题绊倒。我想我明白了,但不完全,这里是代码。
第一部分,主要是使用 swing UI builder 创建的。 编辑了 cmets/imports
public class Screen {
private JFrame frame;
public JLabel lblNewLabel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Screen window = new Screen();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Screen() {
initialize();
}
void initialize() {
XListener listenItem = new XListener("Woot"); // creates listen object
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(193, 154, 56, 16);
frame.getContentPane().add(lblNewLabel);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(163, 73, 97, 25);
frame.getContentPane().add(btnNewButton);
btnNewButton.addActionListener(listenItem); // attaches it to listen object
}
void changeLabel(String setString) {
lblNewLabel.setText(setString);
}
}
第二部分是监听类
// creates class for listen item
public class XListener implements ActionListener {
String foo;
XListener(String setString) {
foo = setString;
}
public void actionPerformed(ActionEvent btnNewButton) {
**Screen.changeLabel(foo);**
}
}
它抱怨不能从类型 Screen 对非静态方法 changeLabel(String) 进行静态引用。但是,如果我使用窗口代替屏幕,它找不到对象。这让我非常困惑。我理解代码的方式是主要方法创建一个名为 window 的 Screen 对象,该对象在初始化时还会创建一个 XListener 对象。为什么它认为 actionPerformed 方法是静态的?我知道我缺少一些基本的东西,而且我一直在关注 java 的“轨迹”,只是不明白。
【问题讨论】:
标签: java static-methods