控制台程序。

工具栏在应用程序窗口中通常位于内容面板顶部的菜单栏下,包含直接访问菜单选项的按钮。在Sketcher程序中可以为最常用的菜单项添加工具栏。

工具栏是javax.swing.JToolBar类定义的Swing组件。想SketcherFrame类定义中添加如下域,可以为这个类添加一个用于工具栏的成员:

private JToolBar toolBar = new JToolBar();

为了把工具栏添加到应用程序窗口中,需要在SkecherFrame构造函数已有代码的后面添加如下语句:

getContentPane().add(toolBar,BorderLayout.NORTH);

对图标的引用一般存储在javax.swing.Icon类型的变量中,javax.swing.Icon是接口,其中声明的方法getHeight()和getWidth()分别用来返回图标的高度和宽度(以像素为单位)。Icon接口还声明了paint()方法,用来在组件上绘制图标图像。javax.swing.ImageIcon类实现了Icon接口,使用这个类在程序中通过包含定义图标图像数据的文件来创建图标对象。

ImageIcon类有多个构造函数,这里使用的构造函数仅仅接收一个String参数,这个参数指定了包含图标图像的文件的路径。传送为参数的String对象可以只是文件名,此时文件应位于Sketcher执行时的当前目录下。

在自定义包中指定图标文件的路径:

  1. // Defines application wide constants
  2. package Constants;
  3. import java.awt.Color;
  4. import javax.swing.*;
  5.  
  6. public class SketcherConstants {
  7. // Path for images
  8. public final static String imagePath = "E:/JavaProject/BeginningJava/Images/";
  9.  
  10. // Toolbar icons
  11. public final static Icon NEW24 = new ImageIcon(imagePath + "New24.gif");
  12. public final static Icon OPEN24 = new ImageIcon(imagePath + "Open24.gif");
  13. public final static Icon SAVE24 = new ImageIcon(imagePath + "Save24.gif");
  14. public final static Icon SAVEAS24 = new ImageIcon(imagePath + "SaveAs24.gif");
  15. public final static Icon PRINT24 = new ImageIcon(imagePath + "Print24.gif");
  16.  
  17. // Element type definitions
  18. public final static int LINE = 101;
  19. public final static int RECTANGLE = 102;
  20. public final static int CIRCLE = 103;
  21. public final static int CURVE = 104;
  22.  
  23. // Initial conditions
  24. public final static int DEFAULT_ELEMENT_TYPE = LINE;
  25. public final static Color DEFAULT_ELEMENT_COLOR = Color.BLUE;
  26. }
  1. // Frame for the Sketcher application
  2. import javax.swing.*;
  3. import javax.swing.border.*;
  4. import java.awt.event.*;
  5. import java.awt.*;
  6.  
  7. import static java.awt.event.InputEvent.*;
  8. import static java.awt.AWTEvent.*;
  9. import static java.awt.Color.*;
  10. import static Constants.SketcherConstants.*;
  11. import static javax.swing.Action.*;
  12.  
  13. @SuppressWarnings("serial")
  14. public class SketcherFrame extends JFrame {
  15. // Constructor
  16. public SketcherFrame(String title) {
  17. setTitle(title); // Set the window title
  18. setJMenuBar(menuBar); // Add the menu bar to the window
  19. setDefaultCloseOperation(EXIT_ON_CLOSE); // Default is exit the application
  20.  
  21. createFileMenu(); // Create the File menu
  22. createElementMenu(); // Create the element menu
  23. createColorMenu(); // Create the element menu
  24. createToolbar();
  25. toolBar.setRollover(true);
  26. getContentPane().add(toolBar, BorderLayout.NORTH);
  27. }
  28.  
  29. // Create File menu item actions
  30. private void createFileMenuActions() {
  31. newAction = new FileAction("New", 'N', CTRL_DOWN_MASK);
  32. openAction = new FileAction("Open", 'O', CTRL_DOWN_MASK);
  33. closeAction = new FileAction("Close");
  34. saveAction = new FileAction("Save", 'S', CTRL_DOWN_MASK);
  35. saveAsAction = new FileAction("Save As...");
  36. printAction = new FileAction("Print", 'P', CTRL_DOWN_MASK);
  37. exitAction = new FileAction("Exit", 'X', CTRL_DOWN_MASK);
  38.  
  39. // Initialize the array
  40. FileAction[] actions = {openAction, closeAction, saveAction, saveAsAction, printAction, exitAction};
  41. fileActions = actions;
  42.  
  43. // Add toolbar icons
  44. newAction.putValue(LARGE_ICON_KEY, NEW24);
  45. openAction.putValue(LARGE_ICON_KEY, OPEN24);
  46. saveAction.putValue(LARGE_ICON_KEY, SAVE24);
  47. saveAsAction.putValue(LARGE_ICON_KEY, SAVEAS24);
  48. printAction.putValue(LARGE_ICON_KEY, PRINT24);
  49. }
  50.  
  51. // Create the File menu
  52. private void createFileMenu() {
  53. JMenu fileMenu = new JMenu("File"); // Create File menu
  54. fileMenu.setMnemonic('F'); // Create shortcut
  55. createFileMenuActions(); // Create Actions for File menu item
  56.  
  57. // Construct the file drop-down menu
  58. fileMenu.add(newAction); // New Sketch menu item
  59. fileMenu.add(openAction); // Open sketch menu item
  60. fileMenu.add(closeAction); // Close sketch menu item
  61. fileMenu.addSeparator(); // Add separator
  62. fileMenu.add(saveAction); // Save sketch to file
  63. fileMenu.add(saveAsAction); // Save As menu item
  64. fileMenu.addSeparator(); // Add separator
  65. fileMenu.add(printAction); // Print sketch menu item
  66. fileMenu.addSeparator(); // Add separator
  67. fileMenu.add(exitAction); // Print sketch menu item
  68. menuBar.add(fileMenu); // Add the file menu
  69. }
  70.  
  71. // Create Element menu actions
  72. private void createElementTypeActions() {
  73. lineAction = new TypeAction("Line", LINE, 'L', CTRL_DOWN_MASK);
  74. rectangleAction = new TypeAction("Rectangle", RECTANGLE, 'R', CTRL_DOWN_MASK);
  75. circleAction = new TypeAction("Circle", CIRCLE,'C', CTRL_DOWN_MASK);
  76. curveAction = new TypeAction("Curve", CURVE,'U', CTRL_DOWN_MASK);
  77.  
  78. // Initialize the array
  79. TypeAction[] actions = {lineAction, rectangleAction, circleAction, curveAction};
  80. typeActions = actions;
  81. }
  82.  
  83. // Create the Elements menu
  84. private void createElementMenu() {
  85. createElementTypeActions();
  86. JMenu elementMenu = new JMenu("Elements"); // Create Elements menu
  87. elementMenu.setMnemonic('E'); // Create shortcut
  88. createRadioButtonDropDown(elementMenu, typeActions, lineAction);
  89. menuBar.add(elementMenu); // Add the element menu
  90. }
  91.  
  92. // Create Color menu actions
  93. private void createElementColorActions() {
  94. redAction = new ColorAction("Red", RED, 'R', CTRL_DOWN_MASK|ALT_DOWN_MASK);
  95. yellowAction = new ColorAction("Yellow", YELLOW, 'Y', CTRL_DOWN_MASK|ALT_DOWN_MASK);
  96. greenAction = new ColorAction("Green", GREEN, 'G', CTRL_DOWN_MASK|ALT_DOWN_MASK);
  97. blueAction = new ColorAction("Blue", BLUE, 'B', CTRL_DOWN_MASK|ALT_DOWN_MASK);
  98.  
  99. // Initialize the array
  100. ColorAction[] actions = {redAction, greenAction, blueAction, yellowAction};
  101. colorActions = actions;
  102. }
  103.  
  104. // Create the Color menu
  105. private void createColorMenu() {
  106. createElementColorActions();
  107. JMenu colorMenu = new JMenu("Color"); // Create Elements menu
  108. colorMenu.setMnemonic('C'); // Create shortcut
  109. createRadioButtonDropDown(colorMenu, colorActions, blueAction);
  110. menuBar.add(colorMenu); // Add the color menu
  111. }
  112.  
  113. // Menu creation helper
  114. private void createRadioButtonDropDown(JMenu menu, Action[] actions, Action selected) {
  115. ButtonGroup group = new ButtonGroup();
  116. JRadioButtonMenuItem item = null;
  117. for(Action action : actions) {
  118. group.add(menu.add(item = new JRadioButtonMenuItem(action)));
  119. if(action == selected) {
  120. item.setSelected(true); // This is default selected
  121. }
  122. }
  123. }
  124.  
  125. // Create toolbar buttons on the toolbar
  126. private void createToolbar() {
  127. for(FileAction action: fileActions){
  128. if(action != exitAction && action != closeAction)
  129. addToolbarButton(action); // Add the toolbar button
  130. }
  131. }
  132.  
  133. // Create and add a toolbar button
  134. private void addToolbarButton(Action action) {
  135. JButton button = new JButton(action); // Create from Action
  136. button.setBorder(BorderFactory.createCompoundBorder( // Add button border
  137. new EmptyBorder(2,5,5,2), // Outside border
  138. BorderFactory.createRaisedBevelBorder())); // Inside border
  139. button.setHideActionText(true); // No label on the button
  140. toolBar.add(button); // Add the toolbar button
  141. }
  142.  
  143. // Inner class defining Action objects for File menu items
  144. class FileAction extends AbstractAction {
  145. // Create action with a name
  146. FileAction(String name) {
  147. super(name);
  148. }
  149.  
  150. // Create action with a name and accelerator
  151. FileAction(String name, char ch, int modifiers) {
  152. super(name);
  153. putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers));
  154.  
  155. // Now find the character to underline
  156. int index = name.toUpperCase().indexOf(ch);
  157. if(index != -1) {
  158. putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
  159. }
  160. }
  161.  
  162. // Event handler
  163. public void actionPerformed(ActionEvent e) {
  164. // You will add action code here eventually...
  165. }
  166. }
  167.  
  168. // Inner class defining Action objects for Element type menu items
  169. class TypeAction extends AbstractAction {
  170. // Create action with just a name property
  171. TypeAction(String name, int typeID) {
  172. super(name);
  173. this.typeID = typeID;
  174. }
  175.  
  176. // Create action with a name and an accelerator
  177. private TypeAction(String name,int typeID, char ch, int modifiers) {
  178. this(name, typeID);
  179. putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers));
  180.  
  181. // Now find the character to underline
  182. int index = name.toUpperCase().indexOf(ch);
  183. if(index != -1) {
  184. putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
  185. }
  186. }
  187.  
  188. public void actionPerformed(ActionEvent e) {
  189. elementType = typeID;
  190. }
  191.  
  192. private int typeID;
  193. }
  194.  
  195. // Handles color menu items
  196. class ColorAction extends AbstractAction {
  197. // Create an action with a name and a color
  198. public ColorAction(String name, Color color) {
  199. super(name);
  200. this.color = color;
  201. }
  202.  
  203. // Create an action with a name, a color, and an accelerator
  204. public ColorAction(String name, Color color, char ch, int modifiers) {
  205. this(name, color);
  206. putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers));
  207.  
  208. // Now find the character to underline
  209. int index = name.toUpperCase().indexOf(ch);
  210. if(index != -1) {
  211. putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
  212. }
  213. }
  214.  
  215. public void actionPerformed(ActionEvent e) {
  216. elementColor = color;
  217. }
  218.  
  219. private Color color;
  220. }
  221.  
  222. // File actions
  223. private FileAction newAction, openAction, closeAction, saveAction, saveAsAction, printAction, exitAction;
  224. private FileAction[] fileActions; // File actions as an array
  225.  
  226. // Element type actions
  227. private TypeAction lineAction, rectangleAction, circleAction, curveAction;
  228. private TypeAction[] typeActions; // Type actions as an array
  229.  
  230. // Element color actions
  231. private ColorAction redAction, yellowAction,greenAction, blueAction;
  232. private ColorAction[] colorActions; // Color actions as an array
  233.  
  234. private JMenuBar menuBar = new JMenuBar(); // Window menu bar
  235. private Color elementColor = DEFAULT_ELEMENT_COLOR; // Current element color
  236. private int elementType = DEFAULT_ELEMENT_TYPE; // Current element type
  237. private JToolBar toolBar = new JToolBar(); // Window toolbar
  238. }
  1. // Sketching application
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5.  
  6. public class Sketcher {
  7. public static void main(String[] args) {
  8. theApp = new Sketcher(); // Create the application object
  9. SwingUtilities.invokeLater(new Runnable() {
  10. public void run() {
  11. theApp.createGUI(); // Call GUI creator
  12. }
  13. });
  14. }
  15.  
  16. // Method to create the application GUI
  17. private void createGUI() {
  18. window = new SketcherFrame("Sketcher"); // Create the app window
  19. Toolkit theKit = window.getToolkit(); // Get the window toolkit
  20. Dimension wndSize = theKit.getScreenSize(); // Get screen size
  21.  
  22. // Set the position to screen center & size to half screen size
  23. window.setSize(wndSize.width/2, wndSize.height/2); // Set window size
  24. window.setLocationRelativeTo(null); // Center window
  25.  
  26. window.addWindowListener(new WindowHandler()); // Add window listener
  27. window.setVisible(true);
  28. }
  29.  
  30. // Handler class for window events
  31. class WindowHandler extends WindowAdapter {
  32. // Handler for window closing event
  33. @Override
  34. public void windowClosing(WindowEvent e) {
  35. // Code to be added here...
  36. }
  37. }
  38.  
  39. private SketcherFrame window; // The application window
  40. private static Sketcher theApp; // The application object
  41. }

Java基础之处理事件——添加工具栏(Sketcher 7 with File toolbar buttons)的更多相关文章

  1. Java基础之处理事件——添加菜单图标(Sketcher 8 with toolbar buttons and menu icons)

    控制台程序. 要为菜单项添加图标以补充工具栏图标,只需要在创建菜单项的Action对象中添加IconImage对象,作为SMALL_ICON键的值即可. // Defines application ...

  2. Java基础之处理事件——添加工具提示(Sketcher 9 with tooltips)

    控制台程序. 在Java中实现对工具提示的支持是非常简单的,秘诀仍在我们一直使用的Action对象中.Action对象拥有存储工具提示文本的内置功能因为文本是通过SHORT_DESCRIPTION键提 ...

  3. build path libraries java基础--Jar包添加到build path方式说明--01

    摘自: http://blog.csdn.net/haolongabc/article/details/7007701 java基础--Jar包添加到build path方式说明--01 前言:这段短 ...

  4. Java 基础(三)| IO流之使用 File 类的正确姿势

    为跳槽面试做准备,今天开始进入 Java 基础的复习.希望基础不好的同学看完这篇文章,能掌握泛型,而基础好的同学权当复习,希望看完这篇文章能够起一点你的青涩记忆. 一.什么是 File 类? java ...

  5. Java基础之处理事件——使用动作Action(Sketcher 6 using Action objects)

    控制台程序. 动作Action是任何实现了javax.swing.Action接口的类的对象.这个接口声明了操作Action对象的方法,例如,存储与动作相关的属性.启用和禁用动作.Action接口扩展 ...

  6. Java基础之处理事件——实现低级事件监听器(Sketcher 2 implementing a low-level listener)

    控制台程序. 定义事件监听器的类必须实现监听器接口.所有的事件监听器接口都扩展了java.util.EventListener接口.这个接口没有声明任何方法,仅仅用于表示监听器对象.使用EventLi ...

  7. Java基础之处理事件——应用程序中的语义事件监听器(Sketcher 5 with element color listeners)

    控制台程序. 为了标识元素的类型,可以为菜单已提供的4中元素定义常量,用作ID.这有助于执行菜单项监听器的操作,还提供了一种标识颜色类型的方式.我们会累积许多应用程序范围的常量,所以把它们定义为可以静 ...

  8. Java基础之处理事件——使用适配器类(Sketcher 3 using an Adapter class)

    控制台程序. 适配器类是指实现了监听器接口的类,但监听器接口中的方法没有内容,所以它们什么也不做.背后的思想是:允许从提供的适配器类派生自己的监听器类,之后再实现那些自己感兴趣的类.其他的空方法会从适 ...

  9. Java基础之处理事件——使窗口处理自己的事件(Skethcer 1 handing its own closing event)

    控制台程序. 为表示事件的常量使用标识符可以直接启用组件对象的特定事件组.调用组件的enableEvent()方法,并把想要启用事件的标识符传送为参数,但这只在不使用监视器的情况下有效.注册监听器会自 ...

随机推荐

  1. P1149 火柴棒等式

    #include <bits/stdc++.h> using namespace std; const int num[] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6} ...

  2. Andrew Ng机器学习公开课笔记–Reinforcement Learning and Control

    网易公开课,第16课 notes,12 前面的supervised learning,对于一个指定的x可以明确告诉你,正确的y是什么 但某些sequential decision making问题,比 ...

  3. ArcGIS for Sever 10.1 服务迁移与恢复

    === 声明:以下内容本是自己写给单位内部同事的参考手册,但是被传到百度文库中.陆续有用户就这方面的问题,通过电话,邮件等方式联系我.首先,感到荣幸.其次是,由于本人当时测试和编写的时候,由于仓促,可 ...

  4. Delphi 中的结构体与结构体指针

    好多程序都给结构体变量设定了一个结构体指针 例如: PAbc = ^TAbc; TAbc = record a: string[10]; b: string[5]; c: string[1]; end ...

  5. 业界有很多MQ产品

    目前业界有很多MQ产品,我们作如下对比: RabbitMQ 是使用Erlang编写的一个开源的消息队列,本身支持很多的协议:AMQP,XMPP, SMTP, STOMP,也正是如此,使的它变的非常重量 ...

  6. Android App罕见错误和优化方案

    本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! 1.App如果被定义一个有参数构造函数,那么需要再定义一个无参数的,如果不则会在某些情况下初始化失败 ...

  7. Python的深拷贝与浅拷贝

    一.前奏:熟悉Python内存管理 在Python中,变量在第一次赋值时自动声明,在创建—也就是赋值的时候,解释器会根据语法和右侧的操作数来决定新对象的类型. 引用计数器:一个内部跟踪变量 引用计数: ...

  8. jdk1.7的collections.sort(List list)排序问题

    1.7使用旧排序: System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); 1.7 ...

  9. 【Android开发学习笔记】【第五课】Activity的生命周期-上

    今天学习Activity当中的七个生命周期函数: 首先得说一个事情,就是在代码当中如果加入了 System.out.println(" ------");之后,如何查看这里面的输出 ...

  10. CSS弹性盒布局

    <html> <head> <meta charset="utf-8"/> <title></title> <st ...