3

why p1.setPreferredSize(new Dimension(200,200)) is showing error.It say illegal start of type

class Menu extends JFrame  {
    JPanel p1=new JPanel();

    //Package p1 does not exist illegal start of type
    p1.setPreferredSize(new Dimension(200,200));
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109

1 Answers1

1

You can't assign parameter to a class attribute outside a method, constructor or static block.


I guess you need a constructor:

class Menu extends JFrame  {
    JPanel p1;

    public Menu() {
         p1 = new JPanel();
         p1.setPreferredSize(new Dimension(200,200));
    }
}

if you will pass fixed dimension always maybe will be better a static block :

class Menu extends JFrame  {
    static JPanel p1;
    // more elements

    static {
         p1 = new JPanel();
         p1.setPreferredSize(new Dimension(200,200));
         // more assignements
    }
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109