下面列出了怎么用javax.swing.JToolBar的API类实例代码及写法,或者点击链接到github查看源代码。
private void addActions(JToolBar tb, Action[] actions) {
tb.removeAll();
boolean visible = false;
if (actions != null) {
for (Action a : actions) {
if (a != null) {
JButton btn = tb.add(a);
btn.setBorder(new javax.swing.border.EmptyBorder(0, 2, 0, 2));
btn.setBorderPainted(false);
btn.setContentAreaFilled(false);
btn.setRolloverEnabled(false);
btn.setOpaque(false);
btn.setFocusable(false);
visible = true;
} else {
tb.add(new JSeparator(JSeparator.VERTICAL));
}
}
}
tb.setVisible(visible);
}
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
if (PREFERRED_HEIGHT == -1) {
GenericToolbar tb = new GenericToolbar();
tb.setBorder(getBorder());
tb.setBorderPainted(isBorderPainted());
tb.setRollover(isRollover());
tb.setFloatable(isFloatable());
Icon icon = Icons.getIcon(GeneralIcons.SAVE);
tb.add(new JButton("Button", icon)); // NOI18N
tb.add(new JToggleButton("Button", icon)); // NOI18N
tb.add(new JTextField("Text")); // NOI18N
JComboBox c = new JComboBox();
c.setEditor(new BasicComboBoxEditor());
c.setRenderer(new BasicComboBoxRenderer());
tb.add(c);
tb.addSeparator();
PREFERRED_HEIGHT = tb.getSuperPreferredSize().height;
}
dim.height = getParent() instanceof JToolBar ? 1 :
Math.max(dim.height, PREFERRED_HEIGHT);
return dim;
}
private JPanel getTreeInPanel(String labelText, JTree tree) {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setBorder(BorderFactory.createEtchedBorder());
JLabel label = new JLabel(labelText);
label.setFont(new Font("Default", Font.BOLD, 12));
toolBar.add(new javax.swing.Box.Filler(new java.awt.Dimension(10, 0),
new java.awt.Dimension(10, 0),
new java.awt.Dimension(10, 32767)));
toolBar.add(label);
toolBar.add(new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(32767, 32767)));
toolBar.add(getPrevoiusTestCaseButton());
toolBar.add(getEditTagButton());
toolBar.setPreferredSize(new java.awt.Dimension(toolBar.getPreferredSize().width, 30));
panel.add(toolBar, BorderLayout.NORTH);
panel.add(TreeSearch.installFor(tree), BorderLayout.CENTER);
return panel;
}
/**
* Method addSelectionToolButton must have been invoked prior to this on the
* JToolBar.
*
* @param toolBar
* @param editor
* @param tool
* @param toolTipText
* @param labels
* @return
*/
private JToggleButton addToolButton(JToolBar toolBar,
DrawingEditor editor,
Tool tool,
String toolTipText,
ImageIcon iconBase) {
JToggleButton toggleButton = new JToggleButton();
toggleButton.setIcon(iconBase);
toggleButton.setText(null);
toggleButton.setToolTipText(toolTipText);
toggleButton.addItemListener(new ToolButtonListener(tool, editor));
// toggleButton.setFocusable(false);
ToolListener toolHandler = (ToolListener) toolBar.getClientProperty("toolHandler");
tool.addToolListener(toolHandler);
ButtonGroup group = (ButtonGroup) toolBar.getClientProperty("toolButtonGroup");
group.add(toggleButton);
toolBar.add(toggleButton);
return toggleButton;
}
private static List<Component> components(Container aContainer) {
List<Component> l = new ArrayList();
for (int i = 0; i < aContainer.getComponentCount(); i++) {
Component c = aContainer.getComponent(i);
if (c instanceof JPanel || c instanceof JToolBar)
l.addAll(components((Container)c));
else if (c instanceof JScrollPane)
l.addAll(components((Container)((JScrollPane)c).getViewport()));
// else if (c instanceof JRootPane)
// l.addAll(components((Container)((JRootPane)c).getContentPane()));
else if (focusable(c)) l.add(c);
}
return l;
}
private JToolBar createButtonsToolBar(final ConsoleModel model) {
final JToolBar buttonsToolBar = new JToolBar(SwingConstants.HORIZONTAL);
buttonsToolBar.setFloatable(false);
buttonsToolBar.setLayout(new FlowLayout());
buttonsToolBar.add(
SwingAction.of("Enumerate Threads", () -> ConsoleModel.enumerateThreadsAction(this)));
buttonsToolBar.add(SwingAction.of("Memory", () -> ConsoleModel.memoryAction(this)));
buttonsToolBar.add(SwingAction.of("Properties", () -> ConsoleModel.propertiesAction(this)));
buttonsToolBar.add(
SwingAction.of("Copy to clipboard", () -> model.copyToClipboardAction(this)));
buttonsToolBar.add(SwingAction.of("Clear", () -> ConsoleModel.clearAction(this)));
buttonsToolBar.add(
JComboBoxBuilder.builder(String.class)
.selectedItem(ConsoleModel.getCurrentLogLevel())
.items(ConsoleModel.getLogLevelOptions())
.itemSelectedAction(ConsoleModel::setLogLevel)
.toolTipText("Increase or decrease log messages printed to console")
.build());
return buttonsToolBar;
}
private static void createUI() throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
frame = new JFrame();
bar = new JToolBar();
bar.add(createButton(1));
bar.add(createButton(2));
bar.add(Box.createHorizontalGlue());
bar.add(createButton(3));
frame.add(bar, BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setVisible(true);
}
});
}
private void updateStyle(JToolBar c) {
SynthContext context = getContext(
c, Region.TOOL_BAR_CONTENT, null, ENABLED);
contentStyle = SynthLookAndFeel.updateStyle(context, this);
context.dispose();
context = getContext(c, Region.TOOL_BAR_DRAG_WINDOW, null, ENABLED);
dragWindowStyle = SynthLookAndFeel.updateStyle(context, this);
context.dispose();
context = getContext(c, ENABLED);
SynthStyle oldStyle = style;
style = SynthLookAndFeel.updateStyle(context, this);
if (oldStyle != style) {
handleIcon =
style.getIcon(context, "ToolBar.handleIcon");
if (oldStyle != null) {
uninstallKeyboardActions();
installKeyboardActions();
}
}
context.dispose();
}
/**
* Wraps an existing action, used as a delegate
*/
protected EntityAction (Collection<Action> entityActions,
JMenu menu,
JToolBar toolBar,
Action delegate)
{
this(
entityActions,
menu,
toolBar,
(String) delegate.getValue(Action.NAME),
(String) delegate.getValue(Action.SHORT_DESCRIPTION),
(String) delegate.getValue(Action.ACCELERATOR_KEY),
(Icon) delegate.getValue(Action.SMALL_ICON));
this.delegate = delegate;
}
/**
* Package private method which returns either BorderLayout.NORTH,
* BorderLayout.SOUTH, BorderLayout.EAST, or BorderLayout.WEST depending
* on the location of the toolbar in its parent. The toolbar might be
* in PAGE_START, PAGE_END, CENTER, or some other position, but will be
* resolved to either NORTH,SOUTH,EAST, or WEST based on where the toolbar
* actually IS, with CENTER being NORTH.
*
* This code is used to determine where the border line should be drawn
* by the custom toolbar states, and also used by NimbusIcon to determine
* whether the handle icon needs to be shifted to look correct.
*
* Toollbars are unfortunately odd in the way these things are handled,
* and so this code exists to unify the logic related to toolbars so it can
* be shared among the static files such as NimbusIcon and generated files
* such as the ToolBar state classes.
*/
static Object resolveToolbarConstraint(JToolBar toolbar) {
//NOTE: we don't worry about component orientation or PAGE_END etc
//because the BasicToolBarUI always uses an absolute position of
//NORTH/SOUTH/EAST/WEST.
if (toolbar != null) {
Container parent = toolbar.getParent();
if (parent != null) {
LayoutManager m = parent.getLayout();
if (m instanceof BorderLayout) {
BorderLayout b = (BorderLayout)m;
Object con = b.getConstraints(toolbar);
if (con == SOUTH || con == EAST || con == WEST) {
return con;
}
return NORTH;
}
}
}
return NORTH;
}
/**
* Creates a new display panel.
*
* @param content the content ({@code null} not permitted).
* @param toolbar toolbar?
* @param popupMenu popup menu?
*/
public DisplayPanel3D(Panel3D content, boolean toolbar, boolean popupMenu) {
super(new BorderLayout());
this.content = content;
add(this.content);
if (toolbar) {
JToolBar tb = createToolBar(content);
add(tb, BorderLayout.EAST);
}
if (popupMenu) {
this.popup = createPopupMenu(ExportFormat.values());
}
this.content.addMouseListener(this);
}
/**
* Initialization. This method has to be called once after construction.
*/
public void init() {
toolBar.setFloatable(false);
Border border = BorderFactory.createMatteBorder(0, 0, 1, 0, toolBar.getBackground().darker());
toolBar.setBorder(border);
List<ToolBarService> list = new ArrayList<>();
list.addAll(toolBarServices);
Collections.sort(list, new ToolBarOrderComparator<>());
for (ToolBarService toolBarService : list) {
JToolBar component = toolBarService.getToolBar();
component.setFloatable(false);
toolBar.add(component);
}
}
/**
* Package private method which returns either BorderLayout.NORTH,
* BorderLayout.SOUTH, BorderLayout.EAST, or BorderLayout.WEST depending
* on the location of the toolbar in its parent. The toolbar might be
* in PAGE_START, PAGE_END, CENTER, or some other position, but will be
* resolved to either NORTH,SOUTH,EAST, or WEST based on where the toolbar
* actually IS, with CENTER being NORTH.
*
* This code is used to determine where the border line should be drawn
* by the custom toolbar states, and also used by NimbusIcon to determine
* whether the handle icon needs to be shifted to look correct.
*
* Toollbars are unfortunately odd in the way these things are handled,
* and so this code exists to unify the logic related to toolbars so it can
* be shared among the static files such as NimbusIcon and generated files
* such as the ToolBar state classes.
*/
static Object resolveToolbarConstraint(JToolBar toolbar) {
//NOTE: we don't worry about component orientation or PAGE_END etc
//because the BasicToolBarUI always uses an absolute position of
//NORTH/SOUTH/EAST/WEST.
if (toolbar != null) {
Container parent = toolbar.getParent();
if (parent != null) {
LayoutManager m = parent.getLayout();
if (m instanceof BorderLayout) {
BorderLayout b = (BorderLayout)m;
Object con = b.getConstraints(toolbar);
if (con == SOUTH || con == EAST || con == WEST) {
return con;
}
return NORTH;
}
}
}
return NORTH;
}
private void initUI() {
JPanel pLeft = new JPanel();
pLeft.setLayout(new BorderLayout(0, 0));
JToolBar toolBar1 = new JToolBar();
toolBar1.setFloatable(false);
toolBar1.setOrientation(SwingConstants.VERTICAL);
initToolBar1(toolBar1);
pLeft.add(toolBar1, BorderLayout.WEST);
left = createContactsUI();
left.onLoadContacts(false);
pLeft.add(left, BorderLayout.CENTER);
setLeftComponent(pLeft);
JPanel pRight = new JPanel();
pRight.setLayout(new BorderLayout(0, 0));
tabbedChat = new ClosableTabHost(this);
pRight.add(tabbedChat, BorderLayout.CENTER);
setRightComponent(pRight);
setResizeWeight(0.3);
setDividerLocation(250);
}
/**
* Package private method which returns either BorderLayout.NORTH,
* BorderLayout.SOUTH, BorderLayout.EAST, or BorderLayout.WEST depending
* on the location of the toolbar in its parent. The toolbar might be
* in PAGE_START, PAGE_END, CENTER, or some other position, but will be
* resolved to either NORTH,SOUTH,EAST, or WEST based on where the toolbar
* actually IS, with CENTER being NORTH.
*
* This code is used to determine where the border line should be drawn
* by the custom toolbar states, and also used by NimbusIcon to determine
* whether the handle icon needs to be shifted to look correct.
*
* Toollbars are unfortunately odd in the way these things are handled,
* and so this code exists to unify the logic related to toolbars so it can
* be shared among the static files such as NimbusIcon and generated files
* such as the ToolBar state classes.
*/
static Object resolveToolbarConstraint(JToolBar toolbar) {
//NOTE: we don't worry about component orientation or PAGE_END etc
//because the BasicToolBarUI always uses an absolute position of
//NORTH/SOUTH/EAST/WEST.
if (toolbar != null) {
Container parent = toolbar.getParent();
if (parent != null) {
LayoutManager m = parent.getLayout();
if (m instanceof BorderLayout) {
BorderLayout b = (BorderLayout)m;
Object con = b.getConstraints(toolbar);
if (con == SOUTH || con == EAST || con == WEST) {
return con;
}
return NORTH;
}
}
}
return NORTH;
}
private JToolBar createFilterToolBar() {
final FiltersDescriptor filtersDesc = FiltersDescriptor.getInstance();
// configure toolbar
final JToolBar toolbar = new NoBorderToolBar();
toolbar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
toolbar.setFloatable(false);
//toolbar.setRollover(true);
toolbar.setBorderPainted(false);
toolbar.setOpaque(false);
if( "Aqua".equals(UIManager.getLookAndFeel().getID()) ) { //NOI18N
toolbar.setBackground(UIManager.getColor("NbExplorerView.background")); //NOI18N
}
createFilterToolBarUI(toolbar, filtersDesc);
filtersDesc.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createFilterToolBarUI(toolbar, filtersDesc);
}
});
}
});
return toolbar;
}
/**
* Processes incoming message for the inspected page.
*
* @param messageTxt message to process.
*/
private void processMessage(final String messageTxt) {
if (messageTxt == null) {
synchronized (LOCK) {
uninitSelectionMode(pageContext.lookup(JToolBar.class));
if (pageModel == getPage()) {
inspectPage(Lookup.EMPTY);
}
}
} else {
try {
JSONObject message = (JSONObject)JSONValue.parseWithException(messageTxt);
Object type = message.get(MESSAGE_TYPE);
// Message about selection mode modification
if (MESSAGE_SELECTION_MODE.equals(type)) {
boolean selectionMode = (Boolean)message.get(MESSAGE_SELECTION_MODE_ATTR);
pageModel.setSelectionMode(selectionMode);
}
} catch (ParseException ex) {
Logger.getLogger(PageInspectorImpl.class.getName())
.log(Level.INFO, "Ignoring message that is not in JSON format: {0}", messageTxt); // NOI18N
}
}
}
@Override
public void paintBorder(Component component, Graphics gr, int x, int y, int w, int h) {
Graphics2D g = (Graphics2D) gr;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
if ((component instanceof JToolBar) /* && ((((JToolBar) component).getUI()) instanceof PaletteToolBarUI) */) {
JToolBar c = (JToolBar) component;
if (c.isFloatable()) {
int borderColor = 0x80ff0000;
float[] stops = ENABLED_STOPS;
Color[] stopColors = ENABLED_STOP_COLORS;
g.setColor(new Color(borderColor, true));
LinearGradientPaint lgp = new LinearGradientPaint(
new Point2D.Float(1, 1), new Point2D.Float(19, 1),
stops, stopColors,
MultipleGradientPaint.CycleMethod.REPEAT);
g.setPaint(lgp);
g.fillRect(1, 1, 7 - 2, h - 2);
ImageIcon icon = new ImageIcon(getClass().getResource("/org/opentcs/guing/res/symbols/toolbar/border.jpg"));
if (c.getComponentCount() != 0 && !(c.getComponents()[0] instanceof JLabel)) {
JLabel label = new JLabel(icon);
label.setFocusable(false);
c.add(label, 0);
label.getParent().setBackground(label.getBackground());
label.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
}
}
}
protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) {
this.toolbar = (JToolBar) c;
switch (state) {
case BORDER_ENABLED:
paintBorder(g, width, height);
break;
}
}
/**
* Small helper function for adding buttons to the toolbar.
*
* @param toolBar
* @param action Action associated with the new button.
* @param defaultIconPath Path to the default icon for the button.
* @param rolloverIconPath Path to the roll-over icon for the button.
* @param pressedIconPath Path to the pressed icon for the button.
*
* @return The created button.
*/
// ESCA-JAVA0138:
private static JButton createAndAddIconToToolbar(final JToolBar toolBar,
final AbstractAction action, final String defaultIconPath, final String rolloverIconPath,
final String pressedIconPath) {
final JButton button = toolBar.add(CActionProxy.proxy(action));
button.setBorder(new EmptyBorder(0, 0, 0, 0));
button.setIcon(new ImageIcon(CMain.class.getResource(defaultIconPath)));
button.setRolloverIcon(new ImageIcon(CMain.class.getResource(rolloverIconPath)));
button.setPressedIcon(new ImageIcon(CMain.class.getResource(pressedIconPath)));
return button;
}
private Component createToolBar() {
JToolBar bar = new JToolBar();
bar.setFloatable(false);
for (Action action : getActions())
if (action == null)
bar.addSeparator();
else
bar.add(action).setFocusable(false);
return bar;
}
/**
* Adds a zoom combo box to the toolbar
*
* @param toolBar the JToolBar to add the button to
* @param action the action that the ZoomComboBox performs
* @param view application view
*/
private void addZoomComboBox(JToolBar toolBar, Action action, String[] zoomExamples, PipeApplicationView view) {
Dimension zoomComboBoxDimension = new Dimension(65, 28);
JComboBox<String> zoomComboBox = new JComboBox<>(zoomExamples);
zoomComboBox.setEditable(true);
zoomComboBox.setSelectedItem("100%");
zoomComboBox.setMaximumRowCount(zoomExamples.length);
zoomComboBox.setMaximumSize(zoomComboBoxDimension);
zoomComboBox.setMinimumSize(zoomComboBoxDimension);
zoomComboBox.setPreferredSize(zoomComboBoxDimension);
zoomComboBox.setAction(action);
view.registerZoom(zoomComboBox);
toolBar.add(zoomComboBox);
}
private void addRunProgress(JToolBar mainToolBar, Insets margin) {
progressBar = new JProgressBar( 0, 100 );
progressBar.setPreferredSize( new Dimension( 120, controlRealTime.getPreferredSize().height ) );
progressBar.setValue( 0 );
progressBar.setStringPainted( true );
progressBar.setToolTipText(formatToolTip("Run Progress",
"Percent of the present simulation run that has been completed."));
mainToolBar.add( progressBar );
}
/**
* Creates and displays the UI, including the map, for this application.
*
* @return the UI component.
*/
public JComponent createUI() {
// application content
JComponent contentPane = createContentPane();
// UI panel
final JToolBar addGraphicsPanel = createToolBar();
contentPane.add(addGraphicsPanel, BorderLayout.NORTH);
// map
map = createMap();
contentPane.add(map);
return contentPane;
}
private void addFunction(final Function f, JMenu menu, JToolBar toolbar) {
Action action = new AbstractAction(f.getName()) {
@Override
public void actionPerformed(ActionEvent e) {
f.execute();
}
};
toolbar.add(action);
menu.add(action);
}
private void initPanel() {
setBorder(new EmptyBorder(1, 2, 1, 2));
// configure toolbar
toolbar = new NoBorderToolBar(JToolBar.HORIZONTAL);
toolbar.setFloatable(false);
toolbar.setRollover(true);
toolbar.setBorderPainted(false);
toolbar.setBorder(BorderFactory.createEmptyBorder());
toolbar.setOpaque(false);
toolbar.setFocusable(false);
add(toolbar);
}
public DropdownButton(String text, Icon icon, boolean toolbar) {
setOpaque(false);
if (toolbar) {
JToolBar tb = new GenericToolbar() {
public void doLayout() {
for (Component c : getComponents())
c.setBounds(0, 0, getWidth(), getHeight());
}
public void paint(Graphics g) {
paintChildren(g);
}
};
tb.setFloatable(false);
tb.setFocusable(false);
container = tb;
add(container);
} else {
container = this;
}
button = new Button(text, icon);
container.add(button);
popup = new Popup();
container.add(popup);
KeyStroke down = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
container.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(down, POPUP_ACTION);
container.getActionMap().put(POPUP_ACTION, new AbstractAction() {
public void actionPerformed(ActionEvent e) { displayPopup(); }
});
}
private Component createToolBar() {
JToolBar bar = new JToolBar();
bar.add(undo);
bar.add(redo);
bar.addSeparator();
bar.add(addRow);
bar.add(removeRows);
bar.addSeparator();
bar.add(openNewWindow);
bar.addSeparator();
bar.add(saveAs);
return bar;
}
/** Return AbstractButtonOperator representing index-th toolbar button within
* the Source Editor.
* @param index index of toolbar button to find
* @return AbstractButtonOperator instance of found toolbar button
*/
public AbstractButtonOperator getToolbarButton(int index) {
// finds JToolbar
ComponentChooser chooser = new ComponentChooser() {
@Override
public boolean checkComponent(Component comp) {
return comp instanceof JToolBar;
}
@Override
public String getDescription() {
return "javax.swing.JToolBar";
}
};
Container toolbar = (Container) findComponent((Container) findParentTopComponent().getSource(), chooser);
if (toolbar == null) {
throw new JemmyException("Toolbar not present.");
}
// if "quick browse" combo box is present, skip first button (MetalComboBoxButton usualy)
Component combo = JComboBoxOperator.findJComboBox(toolbar,
ComponentSearcher.getTrueChooser("JComboBox"));
if (combo != null) {
index++;
}
return new AbstractButtonOperator(AbstractButtonOperator.waitAbstractButton(toolbar,
ComponentSearcher.getTrueChooser("AbstractButton"), index));
}
/**
* {@inheritDoc}
*/
@Override
public void propertyChange(PropertyChangeEvent e) {
if (SynthLookAndFeel.shouldUpdateStyle(e)) {
updateStyle((JToolBar)e.getSource());
}
}