栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将动作侦听器设置为3个按钮

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将动作侦听器设置为3个按钮

您正在寻找的是一条

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    }}

这也意味着,你可以重复使用

ActionListener
的东西像
JMenuItem
S,只要他们有相同的
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
属性获得该引用)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570953.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号