Swing - setSize for JButton not giving expected result
I am just starting to step into Swing and wanted to set up a simple JFrame with a JButton on it. I was not concerned as to where the JButton ended up, as long as it ended up smaller than the actual JFrame. As of now, it is taking the entire Frame.
Code:
import javax.swing.*;
public class FirstRectangle{
public static void showWINDOW(){
JFrame f = new JFrame("TITLE OF JFRAME");
f.setResizable(false);
f.setLocation(300,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton but1 = new JButton("B.A.B.");
f.getContentPane().add(but1);
f.pack();
f.setSize(500,500);
but1.setSize(50,50); // I have tried placing it here and above, right after adding the button. ***** EXPECTED a 50x50 button
f.setVisible(true);
}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
showWINDOW();
}
});
}
}
What am I missing that is causing the button to not resize on Code:
but1.setSize(50,50);
? Is this something that would be solved with layouts? I heard a little about gridBagLayouts and GridBagConstraints the other day, was hoping to avoid that for a few more days.
Re: Swing - setSize for JButton not giving expected result
Perhaps FirstRectangle didn't like that you yelled at it :)
Seriously, you're right. It's all about layouts, and you can't really avoid that. Components get their size (and position) from the layout manger of the container within which they are contained. That makes sense (at least from my pov) - left to themselves they'd be squabbling about who goes where.
Yes, there is a setSize(), but ignore it for now.
The default layout for the container which contains the stuff in a frame is a so-called BorderLayout. Adding to the centre (again the default) makes the thing added take up all the available space. Not what you want. But you can also add things to the "edge" and, in that case they will use preferred width or height (as appropriate).
Try
Code:
whereever.add(whatever, BorderLayout.SOUTH);
BorderLayout is your friend - especially when you consider that the things added can, themselves, be containers. But there are many other layout managers available. See any tutorial (eg google "Java tutorial" for Oracle's)