[英]Add a different ActionListener to anonymously referenced JButtons in a JToolBar
I'm trying to add four JButtons to a JToolBar, each with a different ActionListener. 我试图将四个JButton添加到JToolBar中,每个JButton具有不同的ActionListener。
I'm wondering if there is a way to add an ActionListener to an anonymously referenced JButton, or if I have to specifically define each button and add each listener. 我想知道是否有一种方法可以将ActionListener添加到匿名引用的JButton中,或者是否必须专门定义每个按钮并添加每个侦听器。
Currently, this is what the code looks like: 当前,代码如下所示:
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"));
I was wondering if there was a way to add an ActionListener into the tools.add(new JButton("foo"));
我想知道是否有一种方法可以将ActionListener添加到tools.add(new JButton("foo"));
line in the same manner as Thread t = new FooRunnableClass().start();
行与Thread t = new FooRunnableClass().start();
or if I would have to define each button, add the ActionListener to each button, then add each button to tools. 或者,如果我必须定义每个按钮,则将ActionListener添加到每个按钮,然后将每个按钮添加到工具。
You could define a addButtonToToolbar
method to help you out (assuming you are using Java 8 or newer): 您可以定义一个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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.