e816. 创建工具栏
A 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 监听组合框中选择不同的项
If the toolbar is to be floatable (see e818 防止工具栏可移动), 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);
| Related Examples |
浙公网安备 33010602011771号