FlowLayout on top of GridLayout not working

前端 未结 2 1655
梦谈多话
梦谈多话 2020-11-29 13:16

I\'m trying to create a hangman game and so far it\'s coming along GREAT, but the layout design just doesn\'t seem to fall into place! The alphabet is supposed to end up in

2条回答
  •  余生分开走
    2020-11-29 13:43

    Here are a few suggestions:

    enter image description here

    • 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);
          }
      });
      

提交回复
热议问题