Here are a few suggestions:
-
Use a
GridLayout
for the top panel; in this case, zero means the number of rows is determined by the specified number of columns and the total number of components in the layout:JPanel north = new JPanel(new GridLayout(0, 9));
-
Here’s an outline of how you can make your center panel have a reasonable initial size; note how you can draw relative to the current size:
JPanel center = new JPanel() { private static final int N = 256; private static final String S = "Todo..."; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int dx = (getWidth() - g.getFontMetrics().stringWidth(S)) / 2; int dy = getHeight() / 2; g.drawString(S, dx, dy); } @Override public Dimension getPreferredSize() { return new Dimension(N, N); } };
-
You can construct your button names like this:
for (int i = 0; i < 26; i++) { String letter = String.valueOf((char) (i + 'A')); buttons[i] = new JButton(letter); north.add(buttons[i]); }
-
Make your panels instance variables and start on the event dispatch thread:
EventQueue.invokeLater(new Runnable() { @Override public void run() { Hangman frame = new Hangman(); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.add(frame.north, BorderLayout.NORTH); frame.add(frame.center, BorderLayout.CENTER); frame.add(frame.south, BorderLayout.SOUTH); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } });