Search code examples
javaswinglayoutjframejbutton

JButton Layout set


In my code, My okButton is in bad appear, so large and long, How fix this problem?

public class d7Table extends JFrame {

public JTable table;
public JButton okButton;

public d7Table() {

        table = new JTable(myTableModel(res));
        okButton = new JButton("Ok");

    add(new JScrollPane(table), BorderLayout.CENTER);
    add(okButton, BorderLayout.PAGE_END);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(800, 600);
    this.setLocation(300, 60);
    this.setVisible(true);
}

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

I remove Irrelevant codes. enter image description here


Solution

  • You've added the button to the SOUTH position of a BorderLayout. This is the default behaviour of BorderLayout.

    To fix it, create another JPanel, add your button to it, then add the panel to the SOUTH position instead

    Take a look at

    The approach mentioned above is commonly known as compound layouts, as you use a series of containers with different layout managers to achieve the desired effect.

    JPanel buttonPane = new JPanel(); // FlowLayout by default
    JButton okayButton = new JButton("Ok");
    buttonPanel.add(okayButton);
    add(okayButton, BorderLayout.SOUTH);