您正在寻找的是一个if-then-else if-then
声明。
基本上,ActionListener
像你一直在做的那样添加所有三个按钮......
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
JButton pauseButton = new JButton("Pause");
startButton.addActionListener(this);
stopButton.addActionListener(this);
pauseButton.addActionListener(this);
然后提供if-else-if
一系列条件来测试每个可能的事件(您期望)
public void actionPerformed(ActionEvent e) {
Calendar aCalendar = Calendar.getInstance();
if (e.getSource() == startButton){
start = aCalendar.getTimeInMillis();
aJLabel.setText("Stopwatch is running...");
} else if (e.getSource() == stopButton) {
aJLabel.setText("Elapsed time is: " +
(double) (aCalendar.getTimeInMillis() - start) / 1000 );
} else if (e.getSource() == pauseButton) {
// Do pause stuff
}
}
仔细查看if-then 和 if-then-else 语句以获取更多详细信息
与其尝试使用对按钮的引用,不如考虑使用 的actionCommand
属性AcionEvent
,这意味着您不需要能够引用原始按钮...
public void actionPerformed(ActionEvent e) {
Calendar aCalendar = Calendar.getInstance();
if ("Start".equals(e.getActionCommand())){
start = aCalendar.getTimeInMillis();
aJLabel.setText("Stopwatch is running...");
} else if ("Stop".equals(e.getActionCommand())) {
aJLabel.setText("Elapsed time is: " +
(double) (aCalendar.getTimeInMillis() - start) / 1000 );
} else if ("Pause".equals(e.getActionCommand())) {
// Do pause stuff
}
}
这也意味着您可以重复使用 s 之类的ActionListener
东西JMenuItem
,只要它们具有相同的actionCommand
...
现在,话虽如此,我鼓励你不要遵循这种范式。通常,我会鼓励您使用Action
s API,但这对于您现在的能力来说可能有点太高级了,相反,我会鼓励您利用Java 的匿名类支持,例如... .
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
start = aCalendar.getTimeInMillis();
aJLabel.setText("Stopwatch is running...");
}
});
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
aJLabel.setText("Elapsed time is: "
+ (double) (aCalendar.getTimeInMillis() - start) / 1000);
}
});
pauseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Do pause stuff
}
});
这将每个按钮的责任隔离到一个单独的按钮上ActionListener
,这样可以更轻松地查看正在发生的事情,并在需要时修改它们而不必担心或影响其他按钮。
它还不需要维护对按钮的引用(因为它可以通过ActionEvent
getSource
属性获得)