This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes size of JButtons Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Swing / AWT / SWT
Reply Bookmark "size of JButtons" Watch "size of JButtons" New topic
Author

size of JButtons

Craig Parsons
Ranch Hand

Joined: Jan 28, 2004
Posts: 40
I have added a JButton to a JPanel then added that JPanel to the South part of a boarderlayout. My button runs the entire length of my borderlayout. I have tried setPreferredSize() and it does change the height of the button but the length is still the same. I need to make the length of the button smaller. Any ideas?
Thanks,
Pete Boton
Greenhorn

Joined: Jan 28, 2004
Posts: 1
It sounds like you're on the right track.
What layout manager are you using for your JPanel? It sounds like you're using BorderLayout. BorderLayout respects the preferred height for the north and south components, but always stretches them to the edges of the container.
The default for JPanel is FlowLayout, which is probably what you want to use here. It is one of the few layout managers that actually respects both dimensions of preferred sizes.
Here's some code for you. It creates a JButton and displays it in the south panel according to its preferred size. Of course, this code needs more, including a way to shut down the application, but it should get you off to a good start.
Good luck!
Pete Boton
JFastTrack.com

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Gui1 extends JFrame
{
private JButton okButton = new JButton("OK");
private JPanel southPanel = new JPanel(new FlowLayout());
public static void main(String args[])
{
new Gui1().setVisible(true);
}
private Gui1()
{
setLayout(new BorderLayout());
southPanel.add(okButton);
add(southPanel, BorderLayout.SOUTH);
setSize(300, 200);
}
}
Craig Parsons
Ranch Hand

Joined: Jan 28, 2004
Posts: 40
Works like a charm. The best part is I even understand it.
Thanks for your help!
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: size of JButtons
 
Similar Threads
JFileChooser difficult problem
facing problem in event handling
how to add images dynamically to jpanel?
JButton in JPanel
Blank Frame or Panel