【发布时间】:2020-06-20 17:16:22
【问题描述】:
我有以下图形用户界面:
如您所见,带有绿色和黄色边框的面板具有相同的格式。 2 个标签和一个按钮。我使用以下函数创建了它们,我使用 for 子句调用其他函数来创建其中几个面板:
private JPanel subject (int id, String name, int credits, boolean optional) {
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
if (optional) {
main.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.YELLOW, 1), "("+id+")"));
} else {
main.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.GREEN, 1), "("+id+")"));
}
JPanel namePanel = new JPanel();
namePanel.setLayout(new FlowLayout());
namePanel.add(new JLabel(name));
JPanel creditsPanel = new JPanel();
creditsPanel.setLayout(new FlowLayout());
creditsPanel.add(new JLabel(credits + " credits"));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(new JButton("Add to favorites")); //Here I add the button to the main panel
main.add(namePanel);
main.add(creditsPanel);
main.add(buttonPanel);
return main; //I return the panel to add it to the frame
}
正在创建面板中的JButtons,但未指定名称。
如何为创建的每个面板上的每个按钮添加动作侦听器?
我是否应该为函数中的按钮创建一个参考名称才能做到这一点?
请注意,所有按钮都做类似的事情,但并不完全相同。
【问题讨论】:
-
如果你想为你的按钮添加一个监听器,那么匿名创建它可能不是要走的路。 或者,创建一个工厂方法来创建您的
JButton实例并将Listener传递给工厂(连同按钮标签)。
标签: java swing user-interface jbutton actionlistener