Java Tutorial/Swing/JToolBar — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 15:33, 31 мая 2010

A Complete JToolBar Usage Example

import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
public class ToolBarSample {
  public static void main(final String args[]) {
    JFrame frame = new JFrame("JToolBar Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JToolBar toolbar = new JToolBar();
    toolbar.setRollover(true);
    
    JButton button = new JButton("button");
    toolbar.add(button);
    toolbar.addSeparator();
    
    toolbar.add(new JButton("button 2"));
    
    toolbar.add(new JComboBox(new String[]{"A","B","C"}));
    
    Container contentPane = frame.getContentPane();
    contentPane.add(toolbar, BorderLayout.NORTH);
    JTextArea textArea = new JTextArea();
    JScrollPane pane = new JScrollPane(textArea);
    contentPane.add(pane, BorderLayout.CENTER);
    frame.setSize(350, 150);
    frame.setVisible(true);
  }
}





Adding separator for JToolBar

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;
public class AddingJToolBarSepraratorJFrame {
  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JToolBar toolBar = new JToolBar("Still draggable");
    toolBar.setFloatable(false);
    toolBar.setRollover(true);
    toolBar.add(new JButton("New"));
    toolBar.addSeparator();
    toolBar.add(new JButton("Open"));
    frame.add(toolBar, "North");
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Add various buttons to the toolbar

import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
public class Main {
  public static void main(String[] argv) throws Exception {
    JToolBar toolbar = new JToolBar();
    ImageIcon icon = new ImageIcon("icon.gif");
    Action action = new AbstractAction("Button Label", icon) {
      public void actionPerformed(ActionEvent evt) {
      }
    };
    JButton c1 = new JButton(action);
    c1.setText(null);
    c1.setMargin(new Insets(0, 0, 0, 0));
    toolbar.add(c1);
    JToggleButton c2 = new JToggleButton(action);
    c2.setText(null);
    c2.setMargin(new Insets(0, 0, 0, 0));
    toolbar.add(c2);
    JComboBox c3 = new JComboBox(new String[] { "A", "B", "C" });
    c3.setPrototypeDisplayValue("XXXXXXXX"); // Set a desired width
    c3.setMaximumSize(c3.getMinimumSize());
    toolbar.add(c3);
  }
}





Create a vertical toolbar

import javax.swing.JToolBar;
public class Main {
  public static void main(String[] argv) throws Exception {
    JToolBar toolbar = new JToolBar(null, JToolBar.VERTICAL);
    // Get current orientation
    int orient = toolbar.getOrientation();
  }
}





Customizing JToolBar Look and Feel

Property StringObject TypeToolBar.actionMapActionMapToolBar.ancestorInputMapInputMapToolBar.backgroundColorToolBar.borderBorderToolBar.borderColorColorToolBar.darkShadowColorToolBar.dockingBackgroundColorToolBar.dockingForegroundColorToolBar.floatingBackgroundColorToolBar.floatingForegroundColorToolBar.fontFontToolBar.foregroundColorToolBar.handleIconIconToolBar.highlightColorToolBar.isRolloverBooleanToolBar.lightColorToolBar.nonrolloverBorderBorderToolBar.rolloverBorderBorderToolBar.separatorSizeDimensionToolBar.shadowColorToolBarSeparatorUIStringToolBarUIString


Customizing Tool Bars

  1. Using setFloatable(false) to make a tool bar immovable.
  2. Using setRollover(true) to make the edges of the buttons invisible when mouse pointer is out.
  3. Adding a separator to a tool bar.
  4. Adding a non-button component to a tool bar.



import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;
public class AddintJToolBarToJFrame {
  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JToolBar toolBar = new JToolBar("Still draggable");
    toolBar.setFloatable(false);
    toolBar.setRollover(true);
    toolBar.add(new JButton("New"));
    frame.add(toolBar, "North");
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Determining When a Floatable JToolBar Container Changes Orientation

import javax.swing.JToolBar;
public class Main {
  public static void main(String[] argv) throws Exception {
    JToolBar toolbar = new JToolBar();
    toolbar.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
      public void propertyChange(java.beans.PropertyChangeEvent evt) {
        String propName = evt.getPropertyName();
        if ("orientation".equals(propName)) {
          Integer oldValue = (Integer) evt.getOldValue();
          Integer newValue = (Integer) evt.getNewValue();
          if (newValue.intValue() == JToolBar.HORIZONTAL) {
            System.out.println("horizontal orientation");
          } else {
            System.out.println("vertical orientation");
          }
        }
      }
    });
  }
}





Highlighting Buttons in a JToolbar Container While Under the Cursor

import javax.swing.JToolBar;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal toolbar
    JToolBar toolbar = new JToolBar();
    // Get current rollover mode
    boolean b = toolbar.isRollover();
    // Enable rollover mode
    toolbar.setRollover(true);
  }
}





JToolbar: Toolbars provide a quick access to the most frequently used commands.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
public class SimpleToolbar {
  public static void main(String[] args) {
    JFrame f = new JFrame();
    JMenuBar menubar = new JMenuBar();
    JMenu file = new JMenu("File");
    menubar.add(file);
    f.setJMenuBar(menubar);
    JToolBar toolbar = new JToolBar();
    ImageIcon icon = new ImageIcon("exit.png");
    JButton exit = new JButton(icon);
    toolbar.add(exit);
    exit.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        System.exit(0);
      }
    });
    f.add(toolbar, BorderLayout.NORTH);
    f.setSize(300, 200);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
}





Preventing a JToolbar Container from Floating

import javax.swing.JToolBar;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal toolbar
    JToolBar toolbar = new JToolBar();
    // Get current floatability
    boolean b = toolbar.isFloatable();
    // Disable floatability
    toolbar.setFloatable(false);
  }
}





Swing ToolBar with Image button

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;
public class SwingBar extends JFrame {
  Container frameContainer;
  JToolBar toolBar = new JToolBar();
  String[] iconFiles = { "new.gif", "open.gif", "save.gif", "cut.gif", "copy.gif", "paste.gif" };
  String[] buttonLabels = { "New", "Open", "Save", "Cut", "Copy", "Paste" };
  ImageIcon[] icons = new ImageIcon[iconFiles.length];
  JButton[] buttons = new JButton[buttonLabels.length];
  JMenuBar menuBar = new JMenuBar();
  JMenu fileMenu = new JMenu("File");
  JMenuItem fileExit = new JMenuItem("Exit");
  public SwingBar() {
    fileMenu.add(fileExit);
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);
    frameContainer = getContentPane();
    frameContainer.setLayout(new BorderLayout());
    for (int i = 0; i < buttonLabels.length; ++i) {
      icons[i] = new ImageIcon(iconFiles[i]);
      buttons[i] = new JButton(icons[i]);
      buttons[i].setToolTipText(buttonLabels[i]);
      if (i == 3)
        toolBar.addSeparator();
      toolBar.add(buttons[i]);
    }
    frameContainer.add("North", toolBar);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    fileExit.addActionListener(new MenuItemHandler());
    setSize(500, 500);
    setVisible(true);
  }
  public static void main(String[] args) {
    SwingBar app = new SwingBar();
  }
  public class MenuItemHandler implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String cmd = e.getActionCommand();
      if (cmd.equals("Exit"))
        System.exit(0);
    }
  }
}





This class represents a separator for the toolbar buttons.

/*
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
/**
 * This class represents a separator for the toolbar buttons.
 *
 * @author 
 * @version $Id: JToolbarSeparator.java 475477 2006-11-15 22:44:28Z cam $
 */
public class JToolbarSeparator extends JComponent {
    /**
     * Creates a new JToolbarSeparator object.
     */
    public JToolbarSeparator() {
        setMaximumSize(new Dimension(15, Integer.MAX_VALUE));
    }
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension size = getSize();
        int pos = size.width / 2;
        g.setColor(Color.gray);
        g.drawLine(pos, 3, pos, size.height - 5);
        g.drawLine(pos, 2, pos + 1, 2);
        g.setColor(Color.white);
        g.drawLine(pos + 1, 3, pos + 1, size.height - 5);
        g.drawLine(pos, size.height - 4, pos + 1, size.height - 4);
    }
}





ToolBar button

//The contents of this file are subject to the Mozilla Public License Version 1.1
//(the "License"); you may not use this file except in compliance with the 
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2006.
//
//All Rights Reserved.

import java.awt.Insets;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
/**
 * ToolBar button.
 * 
 * @author Frederik Dietz
 */
@SuppressWarnings("serial")
public class ToolBarButton extends JButton {
  public ToolBarButton(String text, Icon icon) {
    super(text, icon);
    
    initButton();
  }
  
  public ToolBarButton() {
    super();
    initButton();
  }
  
  public ToolBarButton(Action action) {
    super(action);
    initButton();
  }
  private void initButton() {
    setRolloverEnabled(true);
    setRequestFocusEnabled(false);
    setMargin(new Insets(1, 1, 1, 1));
    putClientProperty("JToolBar.isRollover", Boolean.TRUE);
  }
  public boolean isFocusTraversable() {
    return isRequestFocusEnabled();
  }
  /**
   * @see javax.swing.JButton#updateUI()
   */
  public void updateUI() {
    super.updateUI();
    setRolloverEnabled(true);
    putClientProperty("JToolBar.isRollover", Boolean.TRUE);
  }
}





Toolbar with CheckBox

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
public class ToolBarwithCheckBox extends JFrame {
  public static void main(String[] args) {
    ToolBarwithCheckBox that = new ToolBarwithCheckBox();
    that.setVisible(true);
  }
  public ToolBarwithCheckBox() {
    setSize(450, 350);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().add(new ToolbarPanel(), BorderLayout.SOUTH);
  }
}
class ToolbarPanel extends JPanel {
  public ToolbarPanel() {
    setLayout(new BorderLayout());
    JToolBar toolbar = new JToolBar();
    for (int i = 1; i < 4; i++) {
      JCheckBox cbox = new JCheckBox("Checkbox #" + i);
      toolbar.add(cbox);
      cbox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          JCheckBox source = (JCheckBox) (e.getSource());
          System.out.println("Toolbar " + source.getText());
        }
      });
    }
    add(toolbar, BorderLayout.NORTH);
  }
}