【问题标题】:Add a different ActionListener to anonymously referenced JButtons in a JToolBar向 JToolBar 中匿名引用的 JButton 添加不同的 ActionListener
【发布时间】:2015-07-11 16:59:21
【问题描述】:

我正在尝试向 JToolBar 添加四个 JButton,每个都有不同的 ActionListener。

我想知道是否有办法将 ActionListener 添加到匿名引用的 JButton,或者我是否必须专门定义每个按钮并添加每个侦听器。

目前,代码如下所示:

JToolBar tools = new JToolBar();
tools.setFloatable(false);
gui.add(tools, BorderLayout.PAGE_START);// adds tools to JPanel gui made in another method

// add buttons to toolbar
tools.add(new JButton("New"));
tools.add(new JButton("Save"));
tools.add(new JButton("Restore"));
tools.addSeparator();
tools.add(new JButton("Quit"));

我想知道是否有办法以与 Thread t = new FooRunnableClass().start(); 相同的方式将 ActionListener 添加到 tools.add(new JButton("foo")); 行中,或者我是否必须定义每个按钮,将 ActionListener 添加到每个按钮,然后添加每个按钮到工具。

【问题讨论】:

  • 考虑使用 AbstractActions 而不是 ActionListeners,从而通过 setAction(...) 或 JButton 的构造函数设置 JButton 的 Action。
  • if I would have to define each button, add the ActionListener to each button, - 您需要对按钮的引用(无论您使用 addActionListener() 还是 setAction() 方法),所以是的,这将是最简单的方法。
  • 在这里同意@HovercraftFullOfEels。顺便说一句 - Action 可以直接是 added to a JToolBar

标签: java swing awt jbutton jtoolbar


【解决方案1】:

您可以定义一个 addButtonToToolbar 方法来帮助您(假设您使用的是 Java 8 或更高版本):

JToolBar tools = new JToolBar();
tools.setFloatable(false);
// adds tools to JPanel gui made in another method
gui.add(tools, BorderLayout.PAGE_START);

addButtonToToolbar(tools, "New", e -> System.out.println("Pressed New"));
addButtonToToolbar(tools, "Save", e -> System.out.println("Pressed Save"));
addButtonToToolbar(tools, "Restore", e -> System.out.println("Pressed Restore"));
tools.addSeparator();
addButtonToToolbar(tools, "Quit", e -> System.out.println("Pressed Quit"));


private void addButtonToToolbar(final JToolBar toolBar, final String buttonText,
                                final ActionListener actionListener) {
    final JButton button = new JButton(buttonText);
    button.addActionListener(actionListener);
    toolBar.add(button);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多