unit
unit

Reputation: 415

Non-static method getText() can not be referenced from a static context

I have written the following code, but continually get a 'non-static method getText() can not be referenced from a static context' error.

Could someone help get me on the right track here?

public class ISBNText extends JTextField
{  
   protected static String bookNum;
   protected JTextField  bookText; 
   public ISBNText() 
   {
       super(20);
       bookText = new JTextField();
   }   
   public String getISBN()
   {           
      String bookNum = ISBNText.getText();
      return bookNum;
   }
   private String validateISBN(String bookNum)
}

Upvotes: 2

Views: 3436

Answers (4)

Jonathon Faust
Jonathon Faust

Reputation: 12545

You're calling getText as though it were a static. Remove ISBNText from in front of it in your getISBN method.

It looks like you're also redundantly instantiating an additional JTextField. The class you're writing is a JTextField and you don't need the additional one you're creating:

protected JTextField bookText;  // get rid of this
public ISBNText() 
{
   super(20);
   bookText = new JTextField();  // and this

Upvotes: 3

T.K.
T.K.

Reputation: 2259

I believe your problem is that you're calling ISBNText.getText(), but the getText() method is not a static method. Just remove the ISBNText from the beginning of that call, and you should be good.

Upvotes: 1

Matten
Matten

Reputation: 17631

The method getText() is not static and should be called on the instance of the object.

public String getISBN()
{           
   String bookNum = this.getText();
   return bookNum;
}

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500825

This line:

String bookNum = ISBNText.getText();

should just be:

String bookNum = getText();

which is implicitly:

String bookNum = this.getText();

The call ISBNText.getText() is trying to call it as if it's a static method - i.e. associated with the type rather than with any specific instance of the type. That clearly doesn't make sense, as the text is associated with an instance of the type. The two alternatives I've shown you are equivalent, finding the text of the ISBNText that getISBN has been called on.

Upvotes: 12

Related Questions