-1

I'm having some trouble with the line this.add(p). I get an error saying 'cannot use this in a static context' - Yes, this is a very simple question, but can someone explain why that line won't work and static modes?

    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    import javax.swing.JButton; 
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    public class LeapYear {

    public static void main(String[] args) {
        int nmbr;
        nmbr = Integer.valueOf(JOptionPane.showInputDialog("enter any year"));

        {

            }
            if (nmbr>0 && 4%nmbr==0) {

                JPanel panel = new JPanel();
                panel.add(new JLabel("Name"));
                panel.add(new JTextField(20));

                JButton start = new JButton();
                start.add(new JButton("Start"));
                panel.setBackground(Color.YELLOW);


                this.add(panel);
                panel.setOpaque(false);
        }

        if ((nmbr % 5) == 0) {
            System.out.print(nmbr + " is not multiple of 5.");
        }


    }
    }

(And yes, I'm aware I have imported to many Swings, I was just messing around seeing what I can import.) An answer that a new coder could understand would be greatly appreciated! Thanks

Tom
  • 16,842
  • 17
  • 45
  • 54
  • Don't change your question to something completely different, when it already has an answer addressing the initial issue. If you have a new question/issue, then create a ***new*** post. – Tom Sep 22 '16 at 21:38

1 Answers1

2

They keyword this refers to the instance of the class. In a static context, you have no instance, therefore you can't refer it.

Check this link to learn more about "this" keyword : What is the meaning of "this" in Java?

Community
  • 1
  • 1
Rishi
  • 1,163
  • 7
  • 12