시소당
// Create a horizontal toolbar
JToolBar toolbar = new JToolBar();
// Create a vertical toolbar
toolbar = new JToolBar(null, JToolBar.VERTICAL);
// Get current orientation
int orient = toolbar.getOrientation();
The following code adds various buttons to the toolbar:
// Get icon
ImageIcon icon = new ImageIcon("icon.gif");
// Create an action with an icon
Action action = new AbstractAction("Button Label", icon) {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
// Add a button to the toolbar; remove the label and margin before adding
JButton c1 = new JButton(action);
c1.setText(null);
c1.setMargin(new Insets(0, 0, 0, 0));
toolbar.add(c1);
// Add a toggle button; remove the label and margin before adding
JToggleButton c2 = new JToggleButton(action);
c2.setText(null);
c2.setMargin(new Insets(0, 0, 0, 0));
toolbar.add(c2);
// Add a combobox
JComboBox c3 = new JComboBox(new String[]{"A", "B", "C"});
c3.setPrototypeDisplayValue("XXXXXXXX"); // Set a desired width
c3.setMaximumSize(c3.getMinimumSize());
toolbar.add(c3);
// See also e765 Listening for Changes to the Selected Item in a JComboBox Component
If the toolbar is to be floatable (see e818 Preventing a JToolbar Container from Floating), it must be added to a container with a BorderLayout.
// Add the toolbar to a frame
JFrame frame = new JFrame();
frame.getContentPane().add(toolbar, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);