Search code examples
javaswingjbuttonlayout-managerborder-layout

How to set a specific dimension of a Button object in Java Swing?


I have this simple Java Swing test application that show an upper label and under this label a button:

package com.techub.exeute;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

import org.jdesktop.application.SingleFrameApplication;

public class Main extends SingleFrameApplication{
    public static void main(String[] args) {
        Main a = new Main();
        a.startup();
    }

    @Override
    protected void startup() {
        JFrame frame = new JFrame("FrameDemo");
        frame.setMinimumSize(new Dimension(800, 400));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       

        JLabel myLabel = new JLabel("Hello World !!!", SwingConstants.CENTER);
        myLabel.setFont(new Font("Serif", Font.BOLD, 22));
        myLabel.setBackground(Color.RED);
        myLabel.setOpaque(true);
        myLabel.setPreferredSize(new Dimension(100, 80));

        frame.getContentPane().add(myLabel, BorderLayout.NORTH);

        Button myButton = new Button("Click Me !!!");
        myButton.setMaximumSize(new Dimension(50, 25));
        frame.getContentPane().add(myButton, BorderLayout.CENTER);

        //Display the window.
        frame.pack();
        frame.setVisible(true); 
    }
}

The button is in the BorderLayout.CENTER position. The problem is that this button occupies all available space in the CENTER position also if I have set the Maximum Size property with a Dimension object.

What am I wrong? What can I do to create a button having specific dimension?


Solution

  • You're currently telling Java to place the button in the center of your BorderLayout. Java then thinks that you want the entire area filled with this button. If you want to place a normal sized button in the center of your BorderLayout, add the button to a new JPanel and place the JPanel inside BorderLayout.CENTER.

    Doing this, you're telling Java to fill out BorderLayout.CENTER with your JPanel. The elements that you place inside this JPanel will appear normal, because these elements are not getting "stretched" because of your BorderLayout - the JPanel is.