java 按钮组_java – Swing:链接切换按钮和按钮组,以及相应的菜单项

How to Use Actions所述,Action接口是一种有效的方法“如果您有两个或更多个执行相同功能的组件”.特别是,Action将允许您的按钮和菜单项使用相同的代码.

附录:下面的示例显示了JMenu和JToolBar如何可以为多个文件中的每一个共享相同的Action.

import java.awt.BorderLayout;

import java.awt.EventQueue;

import java.awt.event.ActionEvent;

import java.io.File;

import javax.swing.AbstractAction;

import javax.swing.Action;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JToolBar;

/** @see https://stackoverflow.com/questions/4038605 */

public class FileMenu {

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

new FileMenu().create();

}

});

}

void create() {

File userDir = new File(System.getProperty("user.dir"));

File[] files = userDir.listFiles();

JMenu menu = new JMenu("Recent Files");

JToolBar toolBar = new JToolBar(JToolBar.VERTICAL);

JLabel label = new JLabel(" ",JLabel.CENTER);

for (File f : files) {

if (f.isFile() && !f.isHidden()) {

RecentFile rf = new RecentFile(f,label);

menu.add(new JMenuItem(rf.getAction()));

toolBar.add(rf.getAction());

}

}

JMenuBar menuBar = new JMenuBar();

menuBar.add(menu);

JFrame f = new JFrame("FileMenu");

f.setJMenuBar(menuBar);

f.add(toolBar,BorderLayout.CENTER);

f.add(label,BorderLayout.SOUTH);

f.pack();

f.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);

f.setLocationRelativeTo(null);

f.setVisible(true);

}

}

class RecentFile extends AbstractAction {

private final File file;

private final JLabel label;

public RecentFile(final File file,final JLabel label) {

this.file = file;

this.label = label;

this.putValue(Action.NAME,file.getName());

this.putValue(Action.SHORT_DESCRIPTION,file.getAbsolutePath());

}

public void actionPerformed(ActionEvent e) {

label.setText(file.getName());

}

public Action getAction() {

return this;

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值