FlowLayout on top of GridLayout not working

前端 未结 2 1630
梦谈多话
梦谈多话 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);
          }
      });
      
    0 讨论(0)
  • 2020-11-29 14:03

    This problem is pretty well documented if you do some research - it seems all the panels (besides the CENTER one) aren't recalculated when resized. See How do I make this FlowLayout wrap within its JSplitPane? and http://www.velocityreviews.com/forums/t608472-wrap-flowlayout.html

    But for a really quick fix, try changing your main method to this... (basically using a BoxLayout as your main container)

    public static void main(String[] args) 
    {
        TempProject frame = new TempProject();
        Box mainPanel = Box.createVerticalBox();
        frame.setContentPane(mainPanel);
        mainPanel.add(panel);
        mainPanel.add(panel2);
        mainPanel.add(panel3);
        frame.pack();
        frame.setVisible(true);
    }
    
    0 讨论(0)
提交回复
热议问题