Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

size of JButtons  RSS feed

 
Craig Parsons
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Works like a charm. The best part is I even understand it.
Thanks for your help!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!