GridBagLayout panels alignment

后端 未结 7 1592
北荒
北荒 2020-12-07 01:38

I have a little issue with the GridBag Layout Manager. I am trying to display 9 panels like this:

\"Ideal

7条回答
  •  悲哀的现实
    2020-12-07 02:08

    The accepted answer is appealing, but it causes section 4 to widen faster than the flanking panels as the frame is resized. This variation places panels 8 & 9 in a separate sub-panel of a BoxLayout.

    image

    import java.awt.*;
    import javax.swing.*;
    
    /** @see https://stackoverflow.com/q/14755487/261156 */
    public class GridBagDemo implements Runnable {
    
        private JPanel panel;
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new GridBagDemo());
        }
    
        @Override
        public void run() {
            JFrame frame = new JFrame("GridBag");
            frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
            panel = new JPanel(new GridBagLayout());
            add(1, 0, 0, 1, 2);
            add(2, 1, 0, 1, 1);
            add(3, 1, 1, 1, 1);
            add(4, 2, 0, 1, 2);
            add(5, 3, 0, 1, 1);
            add(6, 3, 1, 1, 1);
            add(7, 4, 0, 1, 2);
            frame.add(panel);
            panel = new JPanel(new GridBagLayout());
            add(8, 0, 0, 1, 1);
            add(9, 1, 0, 1, 1);
            frame.add(panel);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        private void add(int i, int x, int y, int w, int h) {
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = x;
            gbc.gridy = y;
            gbc.gridwidth = w;
            gbc.gridheight = h;
            gbc.weightx = .1;
            gbc.weighty = .1;
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.fill = GridBagConstraints.BOTH;
            JPanel p = new JPanel();
            p.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
            p.add(new JLabel("Panel " + i));
            p.setBackground(Color.getHSBColor((i - 1) / 9f, 0.75f, 0.95f));
            panel.add(p, gbc);
        }
    }
    

提交回复
热议问题