I know that there are similar questions on SO like here, but none of them have seemed to fix my problem.
So far, I have two classes: a Game class that extends Canvas
, and a Window class. All the Window class really does is create the JFrame
and the JPanel
's and adds all the necessary components.
One of the components I've been trying to add to the JPanel
is the Game class itself. I've passed in a Game (which is a child class of Canvas) to the Window constructor:
public Window(int width, int height, String title, Game game) {
// ...
}
And, inside the Window constructor, apparently adding the Game to the JFrame
itself works:
public Window(int width, int height, String title, Game game) {
JFrame frame = new JFrame();
// frame.setSize(new Dimension(500,500)); frame.setVisible(true); etc.
frame.add(game);
}
However, when I try to add the Game to the panel, it won't show!
public Window(int width, int height, String title, Game game) {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridBagLayout());
panel.setSize(new Dimension(400,500));
panel.setLocation(0,0);
panel.requestFocus();
panel.setVisible(true);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title);
frame.setVisible(true);
GridBagConstraints gbc = new GridBagConstraints();
panel.add(game, gbc); // doesn't work
frame.add(panel);
}
If you're wondering why I don't just add Game (which again extends Canvas) to the JFrame
itself, it's because I want to add more panels to the frame - and I don't want the panel to be the full size of the window. Adding Game to the panel would make life a whole lot easier because then I can have other panels within the window.