How to change the size of the JButton?

1.2k views Asked by At

Here is my code. The button is the same size as the FlowLayout. How can I make the button smaller?

public class javalearning extends JFrame{{

    FlowLayout f = new FlowLayout();
    this.setSize(600,600);

    JFrame j = new JFrame();
    this.setTitle("this is a tittle");

        JButton button = new JButton();
        button.setText("Button");
        this.add(button);
        button.setBounds(10, 10, 10, 10);

        this.setVisible(true);  
    }
}
4

There are 4 answers

1
Mubin On

FlowLayout will lay out Components left-to-right (or right-to-left) wrapping them if required. If you wish to explicitly set the size of each JButton you should use setPreferredSize rather than setSize or setBounds as layout managers typically make use of the minimum, preferred and maximum sizes when performing a layout.

3
Elliott Frisch On

I think you forget to setLayout, it works fine when I do. Don't use setBounds and put it in a javalearning constructor and I also suggest you setDefaultCloseOperation like

public javalearning() {
    FlowLayout f = new FlowLayout();
    this.setLayout(f);
    this.setSize(600, 600);
    this.setTitle("this is a tittle");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton();
    button.setText("Button");
    this.add(button);
    // button.setBounds(10, 10, 10, 10);

    this.setVisible(true);
}

public static void main(String[] args) {
    javalearning m = new javalearning();
}

Finally, by convention, Java class names start with a capital letter and are camel case. Something like JavaLearning would follow that convention.

1
MadProgrammer On

You never set the layout manager (FlowLayout) to the frame, therefore the JFrame is still using it's default layout manager of BorderLayout...

Try using something more like...

FlowLayout f = new FlowLayout();
setLayout(f);
this.setTitle("this is a tittle");

JButton button = new JButton();
button.setText("Button");
this.add(button);

this.pack();
this.setVisible(true);  

instead...

Take a closer look at Laying Out Components Within a Container for more details

0
Mohammadreza Khatami On
button.setBounds(x, y, height, width);

you can give height and width less than 10! also you can use GridLayout for smaller buttons in one button with for loop