JFrame GridBagLayout component positioning

为君一笑 提交于 2019-12-06 03:28:35
dic19

I am really confused as to how I can get a label to the top middle of the screen, my table in the middle, and my login button to the bottom right.

As you can see GridBagLayout is not the simplest layout manager (too much troubles and not really too much power). To lay out this little amount of components I'd suggest you use a Nested Layout approach:

  • Use BorderLayout to lay out the "main" panel components (label, table and button).
  • Use FlowLayout to center the label inside a top panel and place the button at the right in a bottom panel.

Example

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class Demo {

    private void createAndShowGUI() {

        JLabel label = new JLabel("Title");
        label.setFont(label.getFont().deriveFont(Font.BOLD | Font.ITALIC, 18));
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        topPanel.add(label);

        DefaultTableModel model = new DefaultTableModel(new Object[]{"Column # 1", "Column # 2"}, 0);
        model.addRow(new Object[]{"Property # 1", "Value # 1"});
        model.addRow(new Object[]{"Property # 2", "Value # 2"});
        model.addRow(new Object[]{"Property # 3", "Value # 3"});

        JTable table = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(table);            

        JButton button = new JButton("Log In");
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        bottomPanel.add(button);

        JPanel content = new JPanel(new BorderLayout(8, 8));
        content.add(topPanel, BorderLayout.NORTH);
        content.add(scrollPane, BorderLayout.CENTER);
        content.add(bottomPanel, BorderLayout.SOUTH);

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {                
                new Demo().createAndShowGUI();
            }
        });
    }    
}

Screenshot


In addition

For more complex GUI designs you may want to try one of these third-party layout managers suggested in this answer:

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