Spacing between columns of JButtons

后端 未结 1 912
甜味超标
甜味超标 2021-01-20 18:12

I am working on a simple GUI where there is an isle between the first two columns and the next two columns of JButtons. The code looks as follows:

JPanel pan         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-20 18:43

    Use two panels...

    You could use two panels (for the seats) and one of the isle, for example...

    JPanel left = new JPanel(new GridLayout(0, 2));
    JPanel isle = new JPanel();
    JPanel right = new JPanel(new GridLayout(0, 2));
    
    for (int row = 0; row < 10; row++) {
        for (int col = 0; col < 4; col++) {
            JButton btn = new JButton("Row " + row + " seat " + col);
            if (col < 2) {
                left.add(btn);
            } else {
                right.add(btn);
            }
        }
    }
    
    setLayout(new GridLayout(1, 3));
    
    add(left);
    add(isle);
    add(right);
    

    Use a "filler" component...

    You could place a "filler" component between the 2nd and 3rd columns...

    setLayout(new GridLayout(0, 5));
    
    for (int row = 0; row < 10; row++) {
        for (int col = 0; col < 4; col++) {
            JButton btn = new JButton("Row " + row + " seat " + col);
            if (col == 2) {
                add(new JPanel());
            }
            add(btn);
        }
    }
    

    Use GridBagLayout and apply insets to produce a gap...

    setLayout(new GridBagLayout());
    
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    for (int row = 0; row < 10; row++) {
        gbc.insets = new Insets(1, 1, 1, 1);
        for (int col = 0; col < 4; col++) {
            JButton btn = new JButton("Row " + row + " seat " + col);
            if (col == 2) {
                gbc.insets = new Insets(1, 40, 1, 1);
            } else {
                gbc.insets = new Insets(1, 1, 1, 1);
            }
            add(btn, gbc);
            gbc.gridx++;
        }
        gbc.gridy++;
        gbc.gridx = 0;
    }
    

    0 讨论(0)
提交回复
热议问题