How to disallow resizing component with GridBagLayout in Java


To disallow resizing component with GridBagLayout, use the GridBagConstraints NONE constant −

GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.NONE;

The following is an example to disallow resizing component with GridBagLayout −

Example

package my;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Demo Frame");
      JPanel panel = new JPanel();
      GridBagLayout layout = new GridBagLayout();
      panel.setLayout(layout);
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.fill = GridBagConstraints.NONE;
      JLabel label = new JLabel("Rank: ");
      JTextArea text = new JTextArea();
      text.setText("Add rank here...");
      layout.setConstraints(label, gbc);
      panel.add(label);
      layout.setConstraints(text, gbc);
      panel.add(text);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}

Output


Updated on: 30-Jul-2019

599 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements