Chinaunix首页 | 论坛 | 博客
  • 博客访问: 901011
  • 博文数量: 96
  • 博客积分: 10681
  • 博客等级: 上将
  • 技术积分: 2449
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-16 17:52
文章分类

全部博文(96)

文章存档

2011年(30)

2009年(36)

2008年(30)

分类: Java

2011-04-07 13:00:28

6.1.8 JCheckBoxMenuItem类

Swing的JCheckBoxMenuItem组件的行为类似于我们将一个JCheckBox作为一个JMenuItem放置在菜单上。菜单项的数据模型是ToggleButtonModel,我们在第5章进行了描述。他可以使得菜单项具有选中或是未选中状态,同时显示合适的状态图标。因为数据模型是ToggleButtonModel,当JCheckBoxMenuItem位于一个ButtonGroup中时,该组中只有一个JCheckBoxMenuItem可以被选中。然而,这并不是JCheckBoxMenuItem的通常使用方法,并且很可能会迷惑用户。如果我们需要这种行为,我们可以使用JRadioButtonMenuItem,如本章稍后所述。

创建JCheckBoxMenuItem组件

JCheckBoxMenuItem有七个构造函数。这些构造函数可以允许我们初始化文本标签,图标以及初始状态。

  1. public JCheckBoxMenuItem()
  2. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(); public JCheckBoxMenuItem(String text)
  3. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Boy"); public JCheckBoxMenuItem(Icon icon)
  4. Icon boyIcon = new ImageIcon("boy-r.jpg");
  5. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(boyIcon); public JCheckBoxMenuItem(String text, Icon icon)
  6. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Boy", boyIcon); public JCheckBoxMenuItem(String text, boolean state)
  7. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Girl", true); public JCheckBoxMenuItem(String text, Icon icon, boolean state)
  8. Icon girlIcon = new ImageIcon("girl-r.jpg");
  9. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Girl", girlIcon, true); public JCheckBoxMenuItem(Action action)
  10. Action action = ...;
  11. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(action);

与JCheckBox不同,图标是标签的一部分,而并不是一个单独的设备来表明某项是否被选中。如果在其构造函数中并没有传递文本标签或是图标,菜单项标签部分则会被设置其空的默认值。默认情况下,JCheckBoxMenuItem初始时未选中。

JCheckBoxMenuItem属性

JCheckBoxMenuItem的大部分属性都是由JCheckBoxMenuItem的多个超类继承来的。表6-11列出了JCheckBoxMenuItem所列出的四个属性。

JCheckBoxMenuItem属性

属性名
数据类型

访问性

accessibleContext
AccessibleContext

只读

selectedObjects
Object[]

只读

state
boolean

读写

UIClassID
String

只读

处理JCheckBoxMenuItem选中事件

对于JCheckBoxMenuItem而言,我们可以关联多个事件变体:

  1. JMenuItem中的MenuDragMouseListener与MenuKeyListener
  2. AbstractButton中的ActionListener,ChangeListener与ItemListener
  3. JComponent中的AncestorListener与VetoableChangeListener
  4. Container中的ContainerListener与PropertyChangeListener
  5. Component中的ComponentListener,FocusListener,HierarchyBoundsListener,HierarchyListener,InputMenthodListener,KeyListener,MouseListener,MouseMotionListener以及MouseWheelListener

尽管我们可以监听18种没的事件类型,但是最有趣的还是ActionEvent与ItemEvent,如下所述。

使用ActionListener监听JCheckBoxMenuItem事件

将ActionListener关联到JCheckBoxMenuItem可以使得我们确定菜单何时被选中。监听器会被通知选中事件,但是并不会得到新状态的通知。要确定选中状态,我们必须获取事件源模型并查询选中状态,如下面的示例ActionListener源码所示。这个监听器会依据当前的选中状态修改复选框的文本与图标标签。

  1. ActionListener aListener = new ActionListener() {
  2.    public void actionPerformed(ActionEvent event) {
  3.      Icon girlIcon = new ImageIcon("girl-r.jpg");
  4.      Icon boyIcon = new ImageIcon("boy-r.jpg");
  5.      AbstractButton aButton = (AbstractButton)event.getSource();
  6.      boolean selected = aButton.getModel().isSelected();
  7.      String newLabel;
  8.      Icon newIcon;
  9.      if (selected) {
  10.        newLabel = "Girl";
  11.        newIcon = girlIcon;
  12.      } else {
  13.        newLabel = "Boy";
  14.        newIcon = boyIcon;
  15.      }
  16.      aButton.setText(newLabel);
  17.      aButton.setIcon(newIcon);
  18.    }
  19. };

使用ItemListener监听JCheckBoxMenuItem事件

如果我们使用ItemListener监听JCheckBoxMenuItem选中事件,我们并不需要查询事件源以确定选中状态,事件已经带有这些信息了。依据这个状态,我们可以进行正确的响应。使用ItemListener重新创建ActionListener的行为只需要对前面所列出的源代码进行简单的修改,如下所示:

  1. ItemListener iListener = new ItemListener() {
  2.    public void itemStateChanged(ItemEvent event) {
  3.      Icon girlIcon = new ImageIcon("girl-r.jpg");
  4.      Icon boyIcon = new ImageIcon("boy-r.jpg");
  5.      AbstractButton aButton = (AbstractButton)event.getSource();
  6.      int state = event.getStateChange();
  7.      String newLabel;
  8.      Icon newIcon;
  9.      if (state == ItemEvent.SELECTED) {
  10.        newLabel = "Girl";
  11.        newIcon = girlIcon;
  12.      } else {
  13.        newLabel = "Boy";
  14.        newIcon = boyIcon;
  15.      }
  16.      aButton.setText(newLabel);
  17.      aButton.setIcon(newIcon);
  18.    }
  19. };

自定义JCheckBoxMenuItem观感

图6-3显示了预安装的观感类型集合下JCheckBoxMenuItem的外观。

表6-12列出了JCheckBoxMenuItem的UIResource相关的属性。JCheckBoxMenuItem组件具有19个不同的属性。

JCheckBoxMenuItem UIResource元素

属性字符串

对象类型

CheckBoxMenuItem.acceleratorFont

Font

CheckBoxMenuItem.acceleratorForeground

Color

CheckBoxMenuItem.acceleratorSelectionForeground

Color

CheckBoxMenuItem.actionMap

ActionMap

CheckBoxMenuItem.arrowIcon

Icon

CheckBoxMenuItem.background

Color

CheckBoxMenuItem.border

Border

CheckBoxMenuItem.borderPainted

Boolean

CheckBoxMenuItem.checkIcon

Icon

CheckBoxMenuItem.commandSound

String

CheckBoxMenuItem.disabledForeground

Color

CheckBoxMenuItem.font

Font

CheckBoxMenuItem.foreground

Color

CheckBoxMenuItem.gradient

List

CheckBoxMenuItem.margin

Insets

CheckBoxMenuItem.opaue

Boolean

CheckBoxMenuItem.selectionBackground

Color

CheckBoxMenuItem.selectionForeground

Color

CheckBoxMenuItemUI

String

 

与CheckboxMenuItem.checkIcon属性键值相关联的Icon是显示在JCheckBoxMenuItem上的图标。如果我们不喜欢默认图标,我们可以使用下面的代码行进行修改,在这里假定已经定义并创建了新图标:

UIManager.put("CheckBoxMenuItem.checkIcon", someIcon);

为了使得新图标可以显示合适的选中图像,Icon实现必须其paintIcon()方法内检测关联的菜单组件状态。第4章所创建的DiamondIcon对于这个图标并不起作用,因为他并不检测其状态组件。相反,状态是在构造是确定的。列表6-4列出了一个可以使用的图标类。

  1. package net.ariel.ch06; import java.awt.Color;
  2. import java.awt.Component;
  3. import java.awt.Graphics;
  4. import java.awt.Polygon; import javax.swing.AbstractButton;
  5. import javax.swing.Icon; public class DiamondAbstractButtonStateIcon implements Icon { private final int width = 10;
  6.     private final int height = 10;
  7.     private Color color;
  8.     private Polygon polygon; public DiamondAbstractButtonStateIcon(Color color) {
  9.         this.color = color;
  10.         initPolygon();
  11.     } private void initPolygon() {
  12.         polygon = new Polygon();
  13.         int halfWidth = width/2;
  14.         int halfHeight = height/2;
  15.         polygon.addPoint(0, halfHeight);
  16.         polygon.addPoint(halfWidth, 0);
  17.         polygon.addPoint(width, halfHeight);
  18.         polygon.addPoint(halfWidth, height);
  19.     }
  20.     @Override
  21.     public int getIconHeight() {
  22.         // TODO Auto-generated method stub
  23.         return height;
  24.     } @Override
  25.     public int getIconWidth() {
  26.         // TODO Auto-generated method stub
  27.         return height;
  28.     } @Override
  29.     public void paintIcon(Component component, Graphics g, int x, int y) {
  30.         // TODO Auto-generated method stub boolean selected = false;
  31.         g.setColor(color);
  32.         g.translate(x, y);
  33.         if(component instanceof AbstractButton) {
  34.             AbstractButton abstractButton = (AbstractButton)component;
  35.             selected = abstractButton.isSelected();
  36.         }
  37.         if(selected) {
  38.             g.fillPolygon(polygon);
  39.         }
  40.         else {
  41.             g.drawPolygon(polygon);
  42.         }
  43.         g.translate(-x, -y);
  44.     } }
  6.1.9 JRadioButtonMenuItem类

JRadioButtonMenuItem组件具有所有的Swing组件中最长的名字。其作用类似于JRadioButton,但是位于菜单中。当与其他的JRadioButtonMenuItem组件共同放在一个ButtonGroup中时,每次只有一个组件可以被选中。与JRadioButton类似,JRadioButtonMenuItem的按钮模型是JToggleButton.ToggleButtonModel。

创建JRadioButtonMenuItem组件

JRadioButtonMenuItem具有七个构造函数。这些构造函数允许我们初始化文本标签,图标以及初始状态。

  1. public JCheckBoxMenuItem()
  2. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem();
  3. public JCheckBoxMenuItem(String text)
  4. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Boy");
  5. public JCheckBoxMenuItem(Icon icon)
  6. Icon boyIcon = new ImageIcon("boy-r.jpg");
  7. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(boyIcon);
  8. public JCheckBoxMenuItem(String text, Icon icon)
  9. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Boy", boyIcon);
  10. public JCheckBoxMenuItem(String text, boolean state)
  11. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Girl", true);
  12. public JCheckBoxMenuItem(String text, Icon icon, boolean state)
  13. Icon girlIcon = new ImageIcon("girl-r.jpg");
  14. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem("Girl", girlIcon, true);
  15. public JCheckBoxMenuItem(Action action)
  16. Action action = ...;
  17. JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem(action);

与JCheckBoxMenuItem组件类似,JRadioButtonMenuItem的图标也是标签的一部分。这与JRadioButton不同,在JRadioButton中图标可以表明单选按钮是否被选中。如果在构造函数中并没有传递文本标签或是图标,则项目标签部分则为空。在默认情况下,JRadioButtonMenuItem初始时未选中。如果我们创建一个选中的JRadioButtonMenuItem并将其添加到ButtonGroup中,如果在按钮组中已有一个被选中的项目时,则按钮组会取消新创建的菜单项的选中状态。

处理JRadioButtonMenuItem的选中事件

JRadioButtonMenuItem共享与JCheckBoxMenuItem相同的18个不同的事件/监听器对。要监听选中事件,关联ActionListener是通常的方法。另外,我们也许希望将相同的监听器关联到ButtonGroup中所有的JRadioButtonMenuItem对象之上,毕竟他们由于某种原因分为一组。如果我们使用相同的监听器,监听器可以依据当前的选中而执行某些通常的操作。在其他情况下,如图6-1所示,JRadioButtonMenuItem选项的选中并不进行任何操作。

配置JRadioButtonMenuItem属性

与JCheckBoxMenuItem类似,大部分的JRadioButtonMenuItem属性都是继承的。表6-13中的两个属性覆盖了超类的行为。

JRadioButtonMenuItem属性

属性名
数据类型

访问性

accessibleContext
AccessibleContext

只读

UIClassID
String

只读

自定义JRadioButtonMenuItem观感

图6-3显示了预安装的观感类型集合下的JRadioButtonMenuItem的外观。

表6-14显示了JRadioButtonMenuItem的UIResource相关的属性集合。对于JRadioButtonMenuItem组件而言,共有19个不同的属性。

JRadioButtonMenuItem UIResource元素

属性字符串

对象类型

RadioButtonMenuItem.acceleratorFont

Font

RadioButtonMenuItem.acceleratorForeground

Color

RadioButtonMenuItem.acceleratorSelectionForeground

Color

RadioButtonMenuItem.actionMap

ActionMap

RadioButtonMenuItem.arrowIcon

Icon

RadioButtonMenuItem.background

Color

RadioButtonMenuItem.border

Border

RadioButtonMenuItem.borderPainted

Boolean

RadioButtonMenuItem.checkIcon

Icon

RadioButtonMenuItem.commandSound

String

RadioButtonMenuItem.disabledForeground

Color

RadioButtonMenuItem.font

Font

RadioButtonMenuItem.foreground

Color

RadioButtonMenuItem.gradient

List

RadioButtonMenuItem.margin

Insets

RadioButtonMenuItem.opaque

Boolean

RadioButtonMenuItem.selectionBackground

Color

RadioButtonMenuItem.selectionForeground

Color

RadioButtonMenuItemUI

String

完整的JRadioButtonMenuItem使用示例

为了助于我们理解JRadioButtonMenuItem的使用,列表6-5中的程序演示了如何将所有的内容组合在一起,包括监听菜单上的所有菜单项的选中,使用ActionListener或是ItemListener。程序的输出如图6-8所示。

swing_6_8

  1. /**
  2.  *
  3.  */
  4. package net.ariel.ch06; import java.awt.EventQueue;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.awt.event.ItemEvent;
  8. import java.awt.event.ItemListener;
  9. import java.awt.event.KeyEvent; import javax.swing.AbstractButton;
  10. import javax.swing.ButtonGroup;
  11. import javax.swing.Icon;
  12. import javax.swing.ImageIcon;
  13. import javax.swing.JFrame;
  14. import javax.swing.JMenu;
  15. import javax.swing.JMenuBar;
  16. import javax.swing.JRadioButtonMenuItem; /**
  17.  * @author mylxiaoyi
  18.  *
  19.  */
  20. public class RadioButtonSample { static Icon threeIcon = new ImageIcon("3.gif");
  21.     static Icon fourIcon = new ImageIcon("4.gif");
  22.     static Icon fiveIcon = new ImageIcon("5.gif");
  23.     static Icon sixIcon = new ImageIcon("6.gif"); public static class ButtonActionListener implements ActionListener {
  24.         public void actionPerformed(ActionEvent event) {
  25.             AbstractButton aButton = (AbstractButton)event.getSource();
  26.             boolean selected = aButton.getModel().isSelected();
  27.             System.out.println(event.getActionCommand()+" - selected? "+selected);
  28.         }
  29.     } public static class ButtonItemListener implements ItemListener {
  30.         public void itemStateChanged(ItemEvent event) {
  31.             AbstractButton aButton = (AbstractButton)event.getSource();
  32.             int state = event.getStateChange();
  33.             String selected = ((state == event.SELECTED)?"selected":"not selected");
  34.             System.out.println(aButton.getText()+" - selected? "+selected);
  35.         }
  36.     }
  37.     /**
  38.      * @param args
  39.      */
  40.     public static void main(String[] args) {
  41.         // TODO Auto-generated method stub Runnable runner = new Runnable() {
  42.             public void run() {
  43.                 final ActionListener actionListener = new ButtonActionListener();
  44.                 final ItemListener itemListener = new ButtonItemListener(); JFrame frame = new JFrame("Radio Menu Example");
  45.                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar();
  46.                 JMenu menu = new JMenu("Menu");
  47.                 ButtonGroup buttonGroup = new ButtonGroup();
  48.                 menu.setMnemonic(KeyEvent.VK_M); JRadioButtonMenuItem emptyMenuItem = new JRadioButtonMenuItem();
  49.                 emptyMenuItem.setActionCommand("Empty");
  50.                 emptyMenuItem.addActionListener(actionListener);
  51.                 buttonGroup.add(emptyMenuItem);
  52.                 menu.add(emptyMenuItem); JRadioButtonMenuItem oneMenuItem = new JRadioButtonMenuItem("Partridge");
  53.                 oneMenuItem.addActionListener(actionListener);
  54.                 buttonGroup.add(oneMenuItem);
  55.                 menu.add(oneMenuItem); JRadioButtonMenuItem twoMenuItem = new JRadioButtonMenuItem("Turtle Dove", true);
  56.                 twoMenuItem.addActionListener(actionListener);
  57.                 buttonGroup.add(twoMenuItem);
  58.                 menu.add(twoMenuItem); JRadioButtonMenuItem threeMenuItem = new JRadioButtonMenuItem("French Hens", threeIcon);
  59.                 threeMenuItem.addItemListener(itemListener);
  60.                 buttonGroup.add(threeMenuItem);
  61.                 menu.add(threeMenuItem); JRadioButtonMenuItem fourMenuItem = new JRadioButtonMenuItem("Calling Birds", fourIcon, true);
  62.                 fourMenuItem.addActionListener(actionListener);
  63.                 buttonGroup.add(fourMenuItem);
  64.                 menu.add(fourMenuItem); JRadioButtonMenuItem fiveMenuItem = new JRadioButtonMenuItem(fiveIcon);
  65.                 fiveMenuItem.addActionListener(actionListener);
  66.                 fiveMenuItem.setActionCommand("Rings");
  67.                 buttonGroup.add(fiveMenuItem);
  68.                 menu.add(fiveMenuItem); JRadioButtonMenuItem sixMenuItem = new JRadioButtonMenuItem(sixIcon, true);
  69.                 sixMenuItem.addActionListener(actionListener);
  70.                 sixMenuItem.setActionCommand("Geese");
  71.                 buttonGroup.add(sixMenuItem);
  72.                 menu.add(sixMenuItem); menuBar.add(menu); frame.setJMenuBar(menuBar);
  73.                 frame.setSize(350, 250);
  74.                 frame.setVisible(true);
  75.             }
  76.         };
  77.         EventQueue.invokeLater(runner);
  78.     } }

6.1.10 创建定制的MenuElement组件:MenuElement接口

所有可选择的菜单组件的共同之处在于他们都实现了MenuElement接口。JSeparator没有实现这个接口,但这并没有关系,因为他并不是可选择的。MenuElement接口的目的就是使得MenuSelectionManager在用户在程序菜单结构周围移动时通知不同的菜单元素。

如下面的接口定义所示,MenuElement接口由五个方法构成:

  1. public interface MenuElement {
  2.   public Component getComponent();
  3.   public MenuElement[] getSubElements();
  4.   public void menuSelectionChanged(boolean isInclude);
  5.   public void processKeyEvent(KeyEvent event, MenuElement path[],
  6.     MenuSelectionManager mgr);
  7.   public void processMouseEvent(MouseEvent event, MenuElement path[],
  8.     MenuSelectionManager mgr);
  9. }

getComponent()方法返回菜单的渲染组件。这通常是菜单组件本身,尽管这并不是必须的。getSubElements()方法返回元素内所包含的菜单元素数组。如果这个菜单元素并不是子菜单的顶部,这个方法会返回一个零长度的MenuElement对象数组,而不是null。

当菜单项被放入菜单选择管理器的选择路径或是由菜单选择管理器的选择路径移除时会调用menuSelectionChanged()方法。

processKeyEvent()与processMouseEvent()两个方法用于处理菜单上所生成的按键事件或是鼠标事件。我们的菜单项如何处理事件依赖于组件所支持的内容。例如,除非我们支持快捷键,我们可能希望只有当我们的菜单项位于当前的选择路径时才响应按键事件。

为了演示MenuElement接口,列表6-6创建了一个名为JToggleButtonMenuItem的新菜单组件。这个组件的行为类似于JToggleButton,尽管他可以放在菜单上。保证当菜单项被选中时菜单响应并且当位于当前的选择路径时组件可以进行不同显示是很重要的。

注意:尽管我们可以在菜单中添加任何组件,如果组件没有实现MenuElement接口,则当鼠标略过组件或是当组件被选中时,该组件并不能进行正确的响应。

  1. /**
  2.  *
  3.  */
  4. package net.ariel.ch06; import java.awt.Color;
  5. import java.awt.Component;
  6. import java.awt.Point;
  7. import java.awt.event.KeyEvent;
  8. import java.awt.event.MouseEvent; import javax.swing.Action;
  9. import javax.swing.ButtonModel;
  10. import javax.swing.JToggleButton;
  11. import javax.swing.MenuElement;
  12. import javax.swing.MenuSelectionManager;
  13. import javax.swing.event.MouseInputListener; /**
  14.  * @author mylxiaoyi
  15.  *
  16.  */
  17. public class JToggleButtonMenuItem extends JToggleButton implements MenuElement { Color savedForeground = null;
  18.     private static MenuElement NO_SUB_ELEMENTS[] = new MenuElement[0]; public JToggleButtonMenuItem() {
  19.         init();
  20.     } public JToggleButtonMenuItem(String label) {
  21.         super(label);
  22.         init();
  23.     } public JToggleButtonMenuItem(Action action) {
  24.         super(action);
  25.         init();
  26.     } private void init() {
  27.         updateUI();
  28.         setRequestFocusEnabled(false); // Borrows heavily from BasicMenuUI
  29.         MouseInputListener mouseInputListener = new MouseInputListener() {
  30.             // If mouse release over this menu item, activate it
  31.             public void mouseReleased(MouseEvent event) {
  32.                 MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager();
  33.                 Point point = event.getPoint();
  34.                 if((point.x >= 0) && (point.x < getWidth()) && (point.y >= 0) && (point.y < getHeight())) {
  35.                     menuSelectionManager.clearSelectedPath();
  36.                     // Component automatically handles "selection" at this point
  37.                     // doClick(0); // not necessary
  38.                 }
  39.                 else {
  40.                     menuSelectionManager.processMouseEvent(event);
  41.                 }
  42.             } @Override
  43.             public void mouseClicked(MouseEvent event) {
  44.                 // TODO Auto-generated method stub } // if mouse moves over menu item, add to selection path, so it becomes armed
  45.             @Override
  46.             public void mouseEntered(MouseEvent event) {
  47.                 // TODO Auto-generated method stub
  48.                 MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager();
  49.                 menuSelectionManager.setSelectedPath(getPath());
  50.             } // when mouse moves away from menu item, disarm it and select something else
  51.             @Override
  52.             public void mouseExited(MouseEvent event) {
  53.                 // TODO Auto-generated method stub
  54.                 MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager();
  55.                 MenuElement path[] = menuSelectionManager.getSelectedPath();
  56.                 if(path.length > 1) {
  57.                     MenuElement[] newPath = new MenuElement[path.length-1];
  58.                     for(int i=0, c=path.length-1; i<c; i++) {
  59.                         newPath[i] = path[i];
  60.                     }
  61.                     menuSelectionManager.setSelectedPath(newPath);
  62.                 }
  63.             } @Override
  64.             public void mousePressed(MouseEvent event) {
  65.                 // TODO Auto-generated method stub } // pass along drag events
  66.             @Override
  67.             public void mouseDragged(MouseEvent event) {
  68.                 // TODO Auto-generated method stub
  69.                 MenuSelectionManager.defaultManager().processMouseEvent(event);
  70.             } @Override
  71.             public void mouseMoved(MouseEvent event) {
  72.                 // TODO Auto-generated method stub }
  73.         };
  74.         addMouseListener(mouseInputListener);
  75.         addMouseMotionListener(mouseInputListener);
  76.     }
  77.     /* (non-Javadoc)
  78.      * @see javax.swing.MenuElement#getComponent()
  79.      */
  80.     @Override
  81.     public Component getComponent() {
  82.         // TODO Auto-generated method stub
  83.         return this;
  84.     } /* (non-Javadoc)
  85.      * @see javax.swing.MenuElement#getSubElements()
  86.      */
  87.     @Override
  88.     public MenuElement[] getSubElements() {
  89.         // TODO Auto-generated method stub
  90.         return NO_SUB_ELEMENTS;
  91.     } /* (non-Javadoc)
  92.      * @see javax.swing.MenuElement#menuSelectionChanged(boolean)
  93.      */
  94.     @Override
  95.     public void menuSelectionChanged(boolean isIncluded) {
  96.         // TODO Auto-generated method stub
  97.         ButtonModel model = getModel();
  98.         // only change armed state if different
  99.         if(model.isArmed() != isIncluded) {
  100.             model.setArmed(isIncluded);
  101.         } if(isIncluded) {
  102.             savedForeground = getForeground();
  103.             if(!savedForeground.equals(Color.BLUE)) {
  104.                 setForeground(Color.BLUE);
  105.             }
  106.             else {
  107.                 // in case foreground blue, use something different
  108.                 setForeground(Color.BLUE);
  109.             }
  110.         }
  111.         else {
  112.             setForeground(savedForeground);
  113.             // if null, get foreground from installed look and feel
  114.             if(savedForeground == null) {
  115.                 updateUI();
  116.             }
  117.         }
  118.     } /* (non-Javadoc)
  119.      * @see javax.swing.MenuElement#processKeyEvent(java.awt.event.KeyEvent, javax.swing.MenuElement[], javax.swing.MenuSelectionManager)
  120.      */
  121.     @Override
  122.     public void processKeyEvent(KeyEvent event, MenuElement[] path,
  123.             MenuSelectionManager manager) {
  124.         // TODO Auto-generated method stub
  125.         // if user presses space while menu item armed, select it
  126.         if(getModel().isArmed()) {
  127.             int keyChar = event.getKeyChar();
  128.             if(keyChar == KeyEvent.VK_SPACE) {
  129.                 manager.clearSelectedPath();
  130.                 System.out.println("Selected: JToggleButtonMenuItem, by KeyEvent");
  131.                 doClick(0); // inheried from AbstractButton
  132.             }
  133.         }
  134.     } /* (non-Javadoc)
  135.      * @see javax.swing.MenuElement#processMouseEvent(java.awt.event.MouseEvent, javax.swing.MenuElement[], javax.swing.MenuSelectionManager)
  136.      */
  137.     @Override
  138.     public void processMouseEvent(MouseEvent event, MenuElement[] path,
  139.             MenuSelectionManager manager) {
  140.         // TODO Auto-generated method stub
  141.         // for when mose dragged over menu and button released
  142.         if(event.getID() == MouseEvent.MOUSE_RELEASED) {
  143.             manager.clearSelectedPath();
  144.             System.out.println("Selected: JToggleButtonMenuItem, by MouseEvent");
  145.             doClick(0);
  146.         }
  147.     } // borrows heavily from BasicMenuItemUI.getPath()
  148.     private MenuElement[] getPath() {
  149.         MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager();
  150.         MenuElement oldPath[] = menuSelectionManager.getSelectedPath();
  151.         MenuElement newPath[];
  152.         int oldPathLength = oldPath.length;
  153.         if(oldPathLength == 0)
  154.             return new MenuElement[0];
  155.         Component parent = getParent();
  156.         if(oldPath[oldPathLength-1].getComponent() == parent) {
  157.             // going deeper under the parent menu
  158.             newPath = new MenuElement[oldPathLength+1];
  159.             System.arraycopy(oldPath, 0, newPath, 0, oldPathLength);
  160.             newPath[oldPathLength] = this;
  161.         }
  162.         else {
  163.             // sibling/child menu item currently selected
  164.             int newPathPosition;
  165.             for(newPathPosition = oldPath.length-1; newPathPosition >= 0; newPathPosition--) {
  166.                 if(oldPath[newPathPosition].getComponent() == parent) {
  167.                     break;
  168.                 }
  169.             }
  170.             newPath = new MenuElement[newPathPosition+2];
  171.             System.arraycopy(oldPath, 0, newPath, 0, newPathPosition+1);
  172.             newPath[newPathPosition+1] = this;
  173.         }
  174.         return newPath;
  175.     }
  176. }

一旦我们创建了JToggleButtonMenuItem类,我们就可以像使用其他的菜单项一样来使用:

  1. JToggleButtonMenuItem toggleItem = new JToggleButtonMenuItem("Balloon Help");
  2. editMenu.add(toggleItem);
阅读(3493) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~