设计一个独立的监听器类ToolBarListener ,实现接口ActionListener ,重写actionPerformed方法。
getSource()方法是指从哪个组件发出的事件源。
通过ActionEvent.getSource()获取事件是哪个按钮发出来的,根据不同的按钮,发出切换不同的功能面板。
1.创建监听器把所有按钮的监听器都整合到一起方便维护:
public class ToolBarListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
MainPanel p = MainPanel.instance;
JButton b = (JButton) e.getSource();
if (b == p.bReport)
p.workingPanel.show(ReportPanel.instance);
if (b == p.bCategory)
p.workingPanel.show(CategoryPanel.instance);
if (b == p.bSpend)
p.workingPanel.show(SpendPanel.instance);
if (b == p.bRecord)
p.workingPanel.show(RecordPanel.instance);
if (b == p.bConfig)
p.workingPanel.show(ConfigPanel.instance);
if (b == p.bBackup)
p.workingPanel.show(BackupPanel.instance);
if (b == p.bRecover)
p.workingPanel.show(RecoverPanel.instance);
}
}
2.实例化一个ToolBarListener 监听器,工具栏上的按钮,都加上这么一个监听器对象即可。(从 addListener()开始)
package gui.panel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import gui.listener.ToolBarListener;
import util.CenterPanel;
import util.GUIUtil;
public class MainPanel extends JPanel {
static {
GUIUtil.useLNF();
}
public static MainPanel instance = new MainPanel();
public JToolBar tb = new JToolBar();
public JButton bSpend = new JButton();
public JButton bRecord = new JButton();
public JButton bCategory = new JButton();
public JButton bReport = new JButton();
public JButton bConfig = new JButton();
public JButton bBackup = new JButton();
public JButton bRecover = new JButton();
public CenterPanel workingPanel;
private MainPanel() {
GUIUtil.setImageIcon(bSpend, "home.png", "消费一览");
GUIUtil.setImageIcon(bRecord, "record.png", "记一笔");
GUIUtil.setImageIcon(bCategory, "category2.png", "消费分类");
GUIUtil.setImageIcon(bReport, "report.png", "月消费报表");
GUIUtil.setImageIcon(bConfig, "config.png", "设置");
GUIUtil.setImageIcon(bBackup, "backup.png", "备份");
GUIUtil.setImageIcon(bRecover, "restore.png", "恢复");
tb.add(bSpend);
tb.add(bRecord);
tb.add(bCategory);
tb.add(bReport);
tb.add(bConfig);
tb.add(bBackup);
tb.add(bRecover);
tb.setFloatable(false);
workingPanel = new CenterPanel(0.8);
setLayout(new BorderLayout());
add(tb, BorderLayout.NORTH);
add(workingPanel, BorderLayout.CENTER);
addListener();
}
private void addListener() {
ToolBarListener listener = new ToolBarListener();
bSpend.addActionListener(listener);
bRecord.addActionListener(listener);
bCategory.addActionListener(listener);
bReport.addActionListener(listener);
bConfig.addActionListener(listener);
bBackup.addActionListener(listener);
bRecover.addActionListener(listener);
}
public static void main(String[] args) {
GUIUtil.showPanel(MainPanel.instance, 1);
}
}