I am pretty new with JPanel and JFrame and probably not working with them the way I should. I'm trying to create Pong game and after creating JFrame and adding JPanel to it, I'm able to resize my JPanel but I don't know how to resize my JFrame to fit it. Game class extends JPanel.
main:
public static void main(String[] args) throws InterruptedException { int height = 500, width =(int) (height*1.56); //height = 500, width = 780; JFrame frame = new JFrame("Pong"); Game game = new Game(); frame.add(game); frame.setVisible(true); game.setSize(width, height); System.out.println(game.getHeight()); System.out.println(game.getWidth()); game.setBackground(Color.BLACK); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); System.out.println(frame.getHeight()); System.out.println(frame.getWidth()); } output:
500 780 39 136 The output should be somthing like:
500 780 *above* 500 *above* 780 EDIT:
public static void main(String[] args) throws InterruptedException { int height = 500, width =(int) (height*1.56); //height = 500, width = 780; JFrame frame = new JFrame("Pong"); Game game = new Game(); frame.add(game); frame.setVisible(true); game.setPreferredSize(new Dimension(width, height)); frame.pack(); System.out.println(game.getHeight()); System.out.println(game.getWidth()); game.setBackground(Color.BLACK); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); System.out.println(frame.getHeight()); System.out.println(frame.getWidth()); } Changing the setSize to setPreferredSize and then call pack() for the JFrame fixed it all.
pack()on the JFrame after adding all components. Never set size either but instead deal with preferred size (preferredSize).