Another static / non static problem with Java
OK, use the eclipse IDE and stumble over static / non - static issues I think I understand it, but not completely. It's code
The first part is mainly created using the swing UI builder Edit comments / 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); } }
The second part is the audience class
// 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);** } }
It complains that non - static method changelabel (string) cannot be statically referenced from type screen However, if I use a window instead of a screen, it cannot find an object This makes me very confused The way I understand the code is that the main method creates a screen object called window, and an xlistener object will also be created during initialization Why does it think the actionperformed method is static? I know I lack some basic things, and I've been paying attention to Java 'trail' and haven't got it
Solution
You should pass in a reference to the screen object to be affected when the operation occurs:
// 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); } }
Then initialize your listener like this:
XListener listenItem = new XListener("Woot",this);
You have to do this because the changelabel () method is an instance method of the screen class, but you try to access it like a static method By accessing the correct screen instance, you can call this method correctly