Here is an alternative to extending the JComboBox
. It simply locks the preferred & min/max sizes to the preferred size when added to the tool bar.
Another tweak would be to add an EmtpyBorder
to any instanceof
a JLabel
. They seem a bit 'crowded' there.
import java.awt.*;
import javax.swing.*;
public class ToolBarTest extends JFrame
{
private JToolBar toolbar;
private JLabel shapeLabel;
private JComboBox shapeChooser;
private JLabel colorLabel;
private JComboBox colorChooser;
private String colorNames[] = { "Black" , "Blue", "Cyan", "Dark Gray",
"Gray", "Green", "Light Gray", "Magenta", "Orange",
"Pink", "Red", "White", "Yellow", "Custom" };
private String shapeNames[] = { "Line", "Oval", "Rectangle",
"3D Rectangle","Paint Brush", "Rounded Rectangle" };
public ToolBarTest()
{
setLayout( new BorderLayout() );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize( 500, 200 );
add( createToolBar(), BorderLayout.PAGE_START );
setVisible( true );
}
public void addToToolbar( Component component, int row, int column )
{
Dimension d = component.getPreferredSize();
component.setMaximumSize(d);
component.setMinimumSize(d);
component.setPreferredSize(d);
toolbar.add( component );
}// end addToToolbar
public final JToolBar createToolBar()
{
// create the tool bar which holds the items to draw
toolbar = new JToolBar();
shapeLabel = new JLabel( "Shapes: " );
addToToolbar( shapeLabel, 0, 1 );
shapeChooser =
new JComboBox( shapeNames );
shapeChooser.setSelectedIndex( 0 );
addToToolbar( shapeChooser, 0, 2 );
colorLabel = new JLabel( "Colors: " );
addToToolbar( colorLabel, 0, 3 );
colorChooser = new JComboBox( colorNames );
addToToolbar( colorChooser, 0, 4 );
return toolbar;
}// end createToolBar
public static void main( String args[] )
{
new ToolBarTest();
}// end main
}// end class ToolBarTest'