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

在do-while循环中更新计时器上的JButton

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

在do-while循环中更新计时器上的JButton

我确实不知道您想在评论中确切知道什么,尽管对上述答案+1,但在我看来,这才是真正的原因。看一下这个示例程序,只需将您的调用添加到中的

move(...)
方法中
timerAction
,似乎可以为您工作。在这里试试这段代码:

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class GridExample{    private static final int SIZE = 36;    private JButton[] buttons;    private int presentPos;    private int desiredPos;    private Timer timer;    private Icon infoIcon =      UIManager.getIcon("OptionPane.informationIcon");    private ActionListener timerAction = new ActionListener()    {        public void actionPerformed(ActionEvent ae)        { buttons[presentPos].setIcon(null); if (desiredPos < presentPos) {     presentPos--;     buttons[presentPos].setIcon(infoIcon); } else if (desiredPos > presentPos) {     presentPos++;     buttons[presentPos].setIcon(infoIcon); } else if (desiredPos == presentPos) {     timer.stop();     buttons[presentPos].setIcon(infoIcon); }        }    };    public GridExample()    {        buttons = new JButton[SIZE];        presentPos = 0;        desiredPos = 0;    }    private void createAndDisplayGUI()    {        Jframe frame = new Jframe("Grid Game");        frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);        JPanel contentPane = new JPanel();        contentPane.setLayout(new GridLayout(6, 6, 5, 5));        for (int i = 0; i < SIZE; i++)        { final int counter = i; buttons[i] = new JButton(); buttons[i].setActionCommand("" + i); buttons[i].addActionListener(new ActionListener() {     public void actionPerformed(ActionEvent ae)     {         desiredPos = Integer.parseInt(   (String) buttons[counter].getActionCommand());         timer.start();        } }); contentPane.add(buttons[i]);        }        buttons[presentPos].setIcon(infoIcon);        frame.setContentPane(contentPane);        frame.pack();        frame.setLocationByPlatform(true);        frame.setVisible(true);        timer = new Timer(1000, timerAction);    }    public static void main(String... args)    {        SwingUtilities.invokeLater(new Runnable()        { public void run() {     new GridExample().createAndDisplayGUI(); }        });    }}


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

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

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