![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e816. Creating a JToolbar ContainerA toolbar can be either horizontal or vertical. When the orientation is horizontal, the objects in the toolbar are displayed left-to-right. When the orientation is vertical, the objects in the toolbar are displayed top-to-bottom. This orientation is automatically changed when the toolbar is moved to the top or side of a container.// 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 ComponentIf 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);
e818. Preventing a JToolbar Container from Floating e819. Highlighting Buttons in a JToolbar Container While Under the Cursor © 2002 Addison-Wesley. |