0

我正在尝试将四个 JButton 添加到 JToolBar,每个都有不同的 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"));

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

4

1 回答 1

0

您可以定义一个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);
}
于 2015-05-01T20:03:19.107 回答