Sajad
Sajad

Reputation: 2363

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

Upvotes: 1

Views: 8082

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347314

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);

Upvotes: 5

Azad
Azad

Reputation: 5055

Because the default layout of JFrame is BorderLayout, and PAGE_END means the bottom of the frame horizontally like this:

enter image description here

You have to change the layout of the frame, but don't do that, just create a panel, and add the components to it then add the panel to the container.

JPanel p = new JPanel();
p.add(okButton);
add(p,BorderLayout.PAGE_END);

Here some links may help you understand more about layout managers that usually used:

Upvotes: 4

Andrew Thompson
Andrew Thompson

Reputation: 168835

import java.awt.*;
import javax.swing.*;

public class TableAndButton extends JFrame {

public JTable table;
public JButton okButton;

public TableAndButton() {
    table = new JTable();
    okButton = new JButton("Ok");

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

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //this.setSize(800, 600);  better to call pack()
    this.pack();
    //this.setLocation(300, 60);  better to..
    this.setLocationByPlatform(true);
    this.setVisible(true);
}

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

Upvotes: 3

Related Questions