简体   繁体   中英

Why isn't my code being read after the Frame construction?

Right after I create a new Frame object to attach future JPanels to, the references to the object "j" aren't recognized.

package engine;

import javax.swing.*;

public class GamePanel extends JFrame{

    final int HEIGHT=700, WIDTH=500;

    JFrame j= new JFrame("LittleRPG");
    j.setSize(HEIGHT, WIDTH);
}

the j.setSize(); isn't accepted and an error appears (this applies to all object references after the initial construction of them). I need help identifying why; fresh eyes always help. -Thank you

You dont need to create separate object of JFrame to set size because you already extended the GamePanel Class From JFrame. So, You can directly set it in the constructor GamePanel as your code look like:

package engine;

import javax.swing.*;

public class GamePanel extends JFrame
{

    final int HEIGHT=700, WIDTH=500;

    GamePanel ()
    {
      setSize(HEIGHT, WIDTH);
    }

} 

Your setSize(HEIGHT, WIDTH); method has to be inside of a constructor or another method. Like @Vikas Suryawanshi said, you could just call the methods of JFrame, you dont need to create a new Object of it.

The answers of @Tupfer and @Vikas are correct. Still you want to do it using the object of Jframe then

package engine;

import javax.swing.*;
import java.awt.Color;

public class GamePanel extends JPanel{

   final int HEIGHT=700, WIDTH=500;

   public static void main(String[] args){
       JFrame j= new JFrame("LittleRPG");
       j.setSize(HEIGHT, WIDTH);
       j.getContentPane().add(new GamePanel());
       j.setVisible(true);
       j.setLocationRelativeTo(null);
       j.setBackground(Color.BLUE);
       j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
}

Also you do not need to extend JFrame

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM