Java另一个静态/非静态问题
发布时间:2020-12-15 08:42:59 所属栏目:Java 来源:网络整理
导读:好的,使用 Eclipse IDE并在静态/非静态问题上绊倒.我想我理解它,但不完全,这是代码. 第一部分,主要是使用swing UI构建器创建的.编辑出评论/进口 public class Screen {private JFrame frame;public JLabel lblNewLabel;public static void main(String[] arg
好的,使用
Eclipse IDE并在静态/非静态问题上绊倒.我想我理解它,但不完全,这是代码.
第一部分,主要是使用swing UI构建器创建的.编辑出评论/进口 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)进行静态引用.然而,如果我使用窗口,而不是屏幕,它找不到对象.这让我非常困惑.我理解代码的方法是main方法创建一个名为window的Screen对象,在初始化时也会创建一个XListener对象.为什么它认为actionPerformed方法是静态的?我知道我缺少一些基本的东西,而且我一直在关注java’trail’并且没有得到它. 解决方法
您应该在操作发生时传入对要影响的Screen对象的引用:
// creates class for listen item public class XListener implements ActionListener { String foo; Screen myScreen; XListener(String setString,Screen scr) { foo = setString; myScreen = scr; } public void actionPerformed(ActionEvent btnNewButton) { myScreen.changeLabel(foo); } } 然后,像这样初始化你的监听器: XListener listenItem = new XListener("Woot",this); 您必须这样做,因为changeLabel()方法是Screen类的实例方法,但您尝试像静态方法一样访问它.通过访问正确的Screen实例,您可以正确调用该方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |