开发者

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

开发者 https://www.devze.com 2023-02-11 07:09 出处:网络
I have written the following code, but continually get a \'non-static method getText() can not be referenced from a 开发者_StackOverflow社区static context\' error.

I have written the following code, but continually get a 'non-static method getText() can not be referenced from a 开发者_StackOverflow社区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)
}


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.


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;
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消