David
David

Reputation: 13

How do I lock the size of the components in a re-sizable frame when using GridLayout?

I want to make the frame resizable but keep the initial size of components in a GridLayout. How do I do this?

Initial Size. This is the size I want to keep:

enter image description here

When the frame is resized, the size of the components changes. I don't want this:

enter image description here

Upvotes: 0

Views: 362

Answers (1)

c0der
c0der

Reputation: 18792

The following is an mcve that demonstrates a solution using GridBagLayout as proposed by MadProgrammer.
Including such mcve in the question makes helping much easier and your chances to get good answers higher.

import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;

public class SwingMain {

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new GridBagLayout()); //place desired content in a GridbagLayout
        frame.add(new TestPane());
        frame.pack();
        frame.setVisible(true);
    }
}

class TestPane extends JPanel{

    TestPane() {

        Border padding = BorderFactory.createEmptyBorder(10, 10, 10, 10);
        setBorder(padding);
        setLayout(new GridLayout(2, 2, 10, 10));
        add(new JLabel("Celsius"));
        add(new JTextField(10));
        add(new JLabel("Fahrenheit"));
        add(new JTextField(10));
    }
}

enter image description here

Upvotes: 1

Related Questions