java何种情况使用ItemListener和ActionListener

ActionListener

They are used with buttons or menu. So that whenever you click them it notifies the ActionEvent which in turn invokes the actionPreformed(ActionEvent e) function to perform the specified task.

ItemListeners
These are used with checkboxes, radio buttons, combo boxes kinds of stuff. 

但是也有人说

For a JMenuItem, instead of a listener, you should use an Action (which is a more capable form of ActionListener):

Action saveAction = new AbstractAction("Save") {
    @Override
    public void actionPerformed(ActionEvent event) {
        saveDocument();
    }
};
saveAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S);
saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));

saveMenuItem = new JMenuItem(saveAction);

For JCheckBoxMenuItems and JRadioButtonMenuItems, just as with regular JMenuItems, the Action’s actionPerformed method is called when the user activates the menu item. You can check the new state from within your Action: 

Action showStatusAction = new AbstractAction("Show Status") {
    @Override
    public void actionPerformed(ActionEvent event) {
        boolean selected = (Boolean) getValue(SELECTED_KEY);
        statusBar.setVisible(selected);
    }
};
showStatusAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_W);
showStatusAction.putValue(Action.SELECTED_KEY, true);

showStatusMenuItem = new JCheckBoxMenuItem(showStatusAction);

If you insist on using listeners directly, ItemListener indicates selection state, so it can be used to monitor the state of JCheckBoxMenuItems and JRadioButtonMenuItems. For all other JMenuItems, use ActionListener.

The above actually applies to all descendants of AbstractButton as well as JMenuItem and its descendant classes:

  • For JButtons, use an Action.
  • For JToggleButtons, JCheckBoxes, and JRadioButtons, use an Action and check its SELECTED_KEY value.
  • If you aren’t willing to use Actions, use ActionListener for JButtons, and use ItemListener for JToggleButtons, JCheckBoxes, and JRadioButtons.

My understanding is that there is no reason to use a ChangeListener with a standard JMenuItem or button, as a ChangeEvent is mainly intended to indicate to renderers that the component needs to be repainted.

https://stackoverflow.com/questions/53123562/itemlistener-vs-changelistener-vs-actionlistener

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值