winker
winker

Reputation: 11

What makes this context static? And what what to do?

I've just started to learn java and I'm having some problem with static/non-static. The problem with my code is within the actionlistener. When I try to compile it, it says:

non-static method cannot be referenced from a static context.

Am I right to think that a action performed is static? If so, how can I use a actionlistener to perform a method? (I am well aware that I could just put the text in my code, into the actionlistener. But if I had different circumstances...)

 public class But extends JFrame{
    public void test(){
        //A method
        System.out.println("Testing");
    }
}

class TestListener implements ActionListener{
    public TestListener(){}
    public void actionPerformed(ActionEvent e) {
        But.test(); 
}}

Upvotes: 1

Views: 598

Answers (3)

jefflunt
jefflunt

Reputation: 33954

But.test(); 

You need to create an instance of the "But" class. The way you're calling it here is as if it's a static (class) method, as opposed to a non-static (instance) method.

Maybe just a typo.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993105

Your TestListener needs to know which button to call the .test() method on. So try:

class TestListener implements ActionListener {
    private final But but;
    public TestListener(But b) {
        but = b; // save the instance of But that we want to call
    }
    public void actionPerformed(ActionEvent e) {
        but.test(); 
    }
}

This changes the TestListener constructor to take an instance of a But and stores it away internally in the but field. Then, when the action is performed, the .test() method can be called.

You will need to modify the call to the TestListener constructor appropriately.

Upvotes: 1

Bala R
Bala R

Reputation: 108957

test() in But is an instance method (non-static) but you are trying to access it like it's static.

Try

class TestListener implements ActionListener{
    private But but = new But();
    public TestListener(){}
    public void actionPerformed(ActionEvent e) {
        but.test(); 
}}

or if you intend to make test(), change it's signature to

public static void test(){

Upvotes: 2

Related Questions