0

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);  
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Javanoob
  • 1
  • 1
  • 2

4 Answers4

4

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
4

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • 1
    Thanks. Actually i just reviewed my code and it seems like i forgot to add the setlayout thingy, so now it works fine. thanks again :) – Javanoob Nov 15 '14 at 23:11
0

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.

Mubin
  • 4,192
  • 3
  • 26
  • 45
  • 1
    [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – MadProgrammer Nov 15 '14 at 22:03
0
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

Mohammadreza Khatami
  • 1,444
  • 2
  • 13
  • 27