Can't change size of block in BorderLayout

veinhorn picture veinhorn · Apr 27, 2013 · Viewed 19.4k times · Source

I created simple app with Border Layout and added into it two buttons and JTable. I use JSplitPane between button2 and JTable. I would like redefine default size of block where is situated button1. How can I to solve this task?

Here is my code:

package test;

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

public class Sample {

    public Sample() {
        JFrame app = new JFrame("Sample");
        app.setSize(new Dimension(800,600));

        JPanel panel = new JPanel();
        app.add(panel);

        BorderLayout borderlayout = new BorderLayout();
        panel.setLayout(borderlayout);

        JButton but1 = new JButton("1");
        JButton but2 = new JButton("2");
        but2.setMinimumSize(new Dimension(250,0));
        String[] colNames = {"Name","Number","Scores"};
        Object[][] data = {
                { "Mark",11,12},
                {"Tommy",23,34},
                {"John",34,45}
        };
        JTable table = new JTable(data, colNames);

        JScrollPane scrollpane = new JScrollPane(table);
        JSplitPane jsplitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,but2,scrollpane);

        panel.add(but1,BorderLayout.NORTH);
        panel.add(jsplitpane,BorderLayout.CENTER);

        app.setVisible(true);
    }

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

enter image description here

Answer

Reimeus picture Reimeus · Apr 27, 2013

Components in the BorderLayout.PAGE_START location have the height of their preferred sizes respected. Therefore, you can override the preferred size of JButton but1

JButton but1 = new JButton("1") {
   public Dimension getPreferredSize() {
      return new Dimension(100, 80);
   };
};