FlowLayout on top of GridLayout not working

纵饮孤独 提交于 2019-11-27 02:14:49

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);
        }
    });
    
Nick Rippe

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!