Search code examples
javauser-interfacevariablesstaticjtextfield

Non-Static Variable Cannot be Referenced From a Static Context: New to GUIs


Whenever I compile this, I get an error reading "non-static variable french cannot be referenced from a static context". I have just started working with GUIs, but I cannot find an answer to this. I'm sure it's something simple, but I cannot figure it out!

Any help would be very greatly appreciated.

 public class ReportCard {
 JTextField french = new JTextField ("French Grade") ;
 public static void main (String args[]) {
    JFrame frame = new JFrame ("Report Card") ;
    frame.setSize(400 , 600) ;
    frame.setVisible(true) ;
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;

    JPanel bigPanel = new JPanel() ;
    frame.getContentPane().add(bigPanel) ;

    bigPanel.add(french) ;   

Solution

  • I would strongly suggest reading up on how static works there are many people who can explain it much better than i can.For now you can do a couple of things. make french static

     static JTextField french = new JTextField ("French Grade") ;
    

    or put it in to the main method which will inherently make it static since its already in a static context.

    public class ReportCard {
     public static void main (String args[]) {
        JTextField french = new JTextField ("French Grade") ;
        JFrame frame = new JFrame ("Report Card") ;
        frame.setSize(400 , 600) ;
        frame.setVisible(true) ;
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
    
        JPanel bigPanel = new JPanel() ;
        frame.getContentPane().add(bigPanel) ;
    
        bigPanel.add(french) ;