r/learnjava • • Dec 09 '20

I NEED HELP WITH MY CODE

So I was trying to code a small game with a simple gui. Don't worry about what the game is supposed to be about, I didn't even get close to that. I got stuck when trying to create a JButton that increased a counter... Here is my code:

import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;

public class Window implements ActionListener {

private static JLabel moneyCounter;

long count = 0;

public static void window() {

    JFrame frame = new JFrame();
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("Game");
    frame.setLayout(null);

    JButton button = new JButton("Button");
    button.setSize(100, 30);
    button.setBackground(Color.black);
    button.setLocation(200, 235);
    button.setVisible(true);
    frame.add(button);
    button.addActionListener((ActionListener)this);

    moneyCounter = new JLabel("0");
    moneyCounter.setSize(100, 30);
    moneyCounter.setHorizontalAlignment(SwingConstants.CENTER);
    moneyCounter.setLocation(200, 135);
    frame.add(moneyCounter);
    moneyCounter.setVisible(true);

    frame.setVisible(true);

}

@Override
public void actionPerformed(ActionEvent e) {
    count++;
    moneyCounter.setText(String.valueOf(count));
}

}

This is the error message that I get: java: non-static variable this cannot be referenced from a static context

Also, I know what the problem is, and I know what I am doing wrong and why it doesn't work, but I don't know how to fix it! I can't just make the method a non-static method, because I have to access that method from the main method, and that wouldn't work if they weren't both static, and the main method is always static, so this one has to be static too, right? How can I fix this? Thanks in advance :)

0 Upvotes

14 comments sorted by

View all comments

2

u/hadoken4555 Dec 09 '20

I think it your count variable. You are trying to access it inside your method, you might need to declare it static. Hope that help. Am not a java expert.

2

u/Elifire12 Dec 09 '20

It didn't really fix it, because "this" is referring to the "window" method (I think), and if you are accessing the "window" method, and you change something in the "count" variable, it is not going to change anything. Also you have to put an ActionListener in that parenthesis, that long variable is 1. not an ActionListener and 2. you can't cast it to an ActionListener. So it didn't really fix the problem. Anyways, I really appreciate that you tried to help me, thank you very much :)