使用 Swing 计时器:造成混乱

2024-07-04

只是希望字母的颜色随着一点停顿而改变(停顿可能会根据单词给出的时间和单词的长度而变化)。

下面的代码对我来说工作得很好。但我认为我的逻辑混乱了。我可以理解,但我的队友应该很容易理解。

Code:

import java.awt.Color;
import java.lang.reflect.InvocationTargetException;
import java.awt.Toolkit;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;

public class Reminder 
{
    static   JFrame frame;
    Toolkit toolkit;
    Timer timer;
    int point=0,temp=0,hil=0,point2=0;long time1=0,time2=0;
    static   StyledDocument doc;
    static   JTextPane textpane;
    String[] arr={"Tes"," hiiii"," what"," happpn"};
    int i=0;
    int[] a=new int[5];

    public Reminder() 
    {
        a[0]=1000;
        a[1]=900;
        a[2]=300;
        a[3]=1500;
        a[4]=1700;

        ActionListener actionListener = new ActionListener() 
        {
            public void actionPerformed(ActionEvent actionEvent) 
            {
                point =arr[i].length();
                temp=point+1;
                time1=System.currentTimeMillis();
                new Thread(new t1()).start();
            }
        };

        timer = new Timer(a[i], actionListener);
        timer.setInitialDelay(0);
        timer.start();
    }

    public  class t1 implements Runnable
    {     /* true idea to use current time is beacuse i want to check and make 
sure that the time taken since the timer started, and the present time should
not  exceed the time given in the array in any case*/   
        public void run() 
        {
            try
            {
                time2=System.currentTimeMillis();
                while(time2-time1<=a[i]-200){Thread.sleep((long) (a[i] / (arr[i].length() * 4)));
                if(hil<=temp-1)
                {
                    doc.setCharacterAttributes(point2,hil, textpane.getStyle("Red"), true);}
                    hil++;
                    time2=System.currentTimeMillis();
                }
                doc.setCharacterAttributes(point2,point+1, textpane.getStyle("Red"), true);
                point2+=point;hil=0;i++;
                timer.setDelay(a[i]);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void newcompo()
    {
        JPanel panel = new JPanel();
        doc = (StyledDocument) new DefaultStyledDocument();
        textpane = new JTextPane(doc);
        textpane.setText("Test hiiii what happpn");
        javax.swing.text.Style style = textpane.addStyle("Red", null);
        StyleConstants.setForeground(style, Color.RED);
        panel.add(textpane);
        frame.add(panel);
        frame.pack();
    }

    public static void main(String args[]) throws InterruptedException
                                                                ,    InvocationTargetException 
    {
          SwingUtilities.invokeAndWait(new Runnable() 
          {
            @Override
            public void run() 
            {
                frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                frame.setVisible(true);

                newcompo();
                Reminder aa=  new Reminder();
            }
        });
    }
}

有什么建议吗?我怎样才能简化?

更新错误

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class KaraokeTest {

private int[] timingsArray = {1000, 900, 300, 1500};//word/letters timings
private String[] individualWordsToHighlight = {"Tes", " hiiii", " what", " happpn"};//each individual word/letters to highlight
private int count = 0;
private final JTextPane jtp = new JTextPane();
private final JButton startButton = new JButton("Start");
private final JFrame frame = new JFrame();

public KaraokeTest() {
    initComponents();
}

private void initComponents() {
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);

    for (String s : individualWordsToHighlight) {
        String tmp = jtp.getText();
        jtp.setText(tmp + s);
    }
    jtp.setEditable(false);

    startButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            startButton.setEnabled(false);
            count = 0;

            //create Arrays of individual letters and their timings
            final ArrayList<String> chars = new ArrayList<>();
            final ArrayList<Integer> charsTiming = new ArrayList<>();

            for (String s : individualWordsToHighlight) {
                for (int i = 0; i < s.length(); i++) {
                    chars.add(String.valueOf(s.charAt(i)));
                    System.out.println(String.valueOf(s.charAt(i)));
                }
            }

            for (int x = 0; x < timingsArray.length; x++) {
                for (int i = 0; i < individualWordsToHighlight[x].length(); i++) {
                    charsTiming.add(timingsArray[x] / individualWordsToHighlight[x].length());
                    System.out.println(timingsArray[x] / individualWordsToHighlight[x].length());
                }
            }

            new Timer(1, new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (count < charsTiming.size()) {
                        highlightNextWord();
                        //restart timer with new timings
                        ((Timer) ae.getSource()).setInitialDelay(charsTiming.get(count));
                        ((Timer) ae.getSource()).restart();
                    } else {//we are at the end of the array
                        reset();
                        ((Timer) ae.getSource()).stop();//stop the timer
                    }
                    count++;//increment counter
                }
            }).start();
        }
    });

    frame.add(jtp, BorderLayout.CENTER);
    frame.add(startButton, BorderLayout.SOUTH);

    frame.pack();
    frame.setVisible(true);
}

private void reset() {
    startButton.setEnabled(true);
    jtp.setText("");
    for (String s : individualWordsToHighlight) {
        String tmp = jtp.getText();
        jtp.setText(tmp + s);
    }
    JOptionPane.showMessageDialog(frame, "Done");
}

private void highlightNextWord() {
    //we still have words to highlight
    int sp = 0;
    for (int i = 0; i < count + 1; i++) {//get count for number of letters in words (we add 1 because counter is only incrementd after this method is called)
        sp += 1;
    }
    //highlight words
    Style style = jtp.addStyle("RED", null);
    StyleConstants.setForeground(style, Color.RED);
    ((StyledDocument) jtp.getDocument()).setCharacterAttributes(0, sp, style, true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new KaraokeTest();
        }
    });
}
}

给我例外:

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - illegal start of type
    at KaraokeTest$1.actionPerformed(KaraokeTest.java:47)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6263)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
    at java.awt.Component.processEvent(Component.java:6028)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.java:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

好的,这是代码的清理版本,它应该大致执行相同的操作:

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Reminder {
    private static final String TEXT = "Test hiiii what happpn";
    private static final String[] WORDS = TEXT.split(" ");
    private JFrame frame;
    private Timer timer;
    private StyledDocument doc;
    private JTextPane textpane;
    private List<Integer> times = Arrays.asList(1000, 900, 300, 1500);

    private int stringIndex = 0;
    private int index = 0;

    public void startColoring() {
        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                doc.setCharacterAttributes(stringIndex, 1, textpane.getStyle("Red"), true);
                stringIndex++;
                try {
                    if (stringIndex >= doc.getLength() || doc.getText(stringIndex, 1).equals(" ")) {
                        index++;
                    }
                    if (index < times.size()) {
                        double delay = times.get(index).doubleValue();
                        timer.setDelay((int) (delay / WORDS[index].length()));
                    } else {
                        timer.stop();
                        System.err.println("Timer stopped");
                    }
                } catch (BadLocationException e) {
                    e.printStackTrace();
                }
            }
        };
        timer = new Timer(times.get(index), actionListener);
        timer.setInitialDelay(0);
        timer.start();
    }

    public void initUI() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        doc = new DefaultStyledDocument();
        textpane = new JTextPane(doc);
        textpane.setText(TEXT);
        javax.swing.text.Style style = textpane.addStyle("Red", null);
        StyleConstants.setForeground(style, Color.RED);
        panel.add(textpane);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) throws InterruptedException, InvocationTargetException {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                Reminder reminder = new Reminder();
                reminder.initUI();
                reminder.startColoring();
            }
        });
    }
}

帮助其他人阅读和理解您的代码的一些技巧:

  • 使用连贯且适当的缩进(我个人尝试遵守默认的 Sun Java 约定)
  • 遵循Java编码约定(常量大写,类名大写开头,变量和方法小写开头,使用驼峰式命名)
  • 使用有意义的变量和方法名称
  • 类成员应该一一声明(不要使用int i, j, k; )
  • 每行使用一条指令(避免诸如if(something) doSomething(); else {doSomethingElse1(); doSomethingElse2();}在一行上)
  • 避免不必要的使用static关键字(常量除外)
  • 尽量避免过多地耦合代码(尝试对其余代码的执行方式做出最低限度的假设)
  • 在代码中添加 javadoc 和注释,这始终是一个很好的做法,并且对您和其他人都有很大的帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Swing 计时器:造成混乱 的相关文章

随机推荐

  • dotnet sdk 已安装但无法识别 - Linux Ubuntu/popOS 22.04

    昨天我的 dotnet sdk 工作得很好 今天当我登录到我的电脑时 我更新了系统和 VSCode 然后当我尝试运行时dotnet watch run 我收到此错误 You intended to execute a NET applica
  • 如何忽略`git stash -p`中添加的帅哥

    想象一下这个场景 edit two files git add p add hunks from one file 现在当你跑步时git stash p 它会再次询问您是否要隐藏您刚刚通过选择的帅哥git add p 有没有办法配置 git
  • 如何使用 Ruby 的新 lambda 语法?

    Ruby 有 lambda 语法 所以我可以使用 gt symbol a 0 new gt a lt 5 do puts a a 1 end 这非常有效 但是当我尝试这样做时 match to gt e 404 Hello I am mic
  • i识别人的扫描图像中的眼睛

    我想开发一个 iPhone 应用程序 它应该识别 QR 阅读器扫描的图像中人的眼睛 脸部和肤色 如何在图像中检测眼睛 虽然这可能是可能的 但我只是警告您 无论编程如何 它都会有一定程度的不准确性 任何面部 视网膜检测软件都可能被欺骗 并且考
  • .NET进程监视器

    有没有办法确定特定机器上次运行进程的时间 我可以使用以下内容来确定进程是否正在运行 但如果该进程已停止 则应用程序无法获取该进程 Process process Process GetProcessesByName processName
  • OpenSSL 二进制发行版:版本末尾字符的含义

    我正在使用依赖于 OpenSSL 的 libcurl 因此我也需要与其链接 有适用于 Windows 的二进制发行版here http slproweb com products Win32OpenSSL html 但我不明白版本末尾的字符
  • Android 在 FragmentPagerAdapter 中的 Fragment 中设置 TextView 的文本

    这让我发疯 基本上 我想创建一个ViewPager并添加一些Fragment到它 然后 我想做的就是在其中之一设置一个值Fragment s TextViews 我可以添加Fragment很好 它们连接在一起 但是当我去findViewBy
  • 我们如何被允许使用前向声明的对象或函数,又如何不可以?

    如果我们声明一个对象或函数而不定义它 那么我们如何在声明之前使用它以及如何不允许在声明之前使用它 对于在定义之前使用转发声明的结构标记的类似问题 基本上我们如何允许使用不完整类型 请参阅https stackoverflow com a 4
  • 获取索引处字符的 ANSI 颜色

    我已经开发了couleursNPM包 https github com IonicaBizau couleurs可以设置追加rgb方法String prototype gt console log Hello World rgb 255 0
  • 什么时候不再支持IE6? [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 众所周知 支持 IE6 及其许多有据可查的怪癖是痛苦的 但这是开发和支持基于 Web 的技术的必要部分 我的问题是 有谁知道 IE6 计划何时结束 M
  • 拟合高斯函数

    我有一个直方图 见下文 我试图找到平均值和标准差以及适合我的直方图的曲线的代码 我认为 SciPy 或 matplotlib 中有一些可以提供帮助的东西 但我尝试过的每个示例都不起作用 import matplotlib pyplot as
  • CMake 在调试和发布中仅链接到目标的发布配置

    当包含目标时 是否有另一种方法仅链接目标的发行库target link libraries对于发布和调试配置 I know target link libraries有选项optimize and debug可以这样做 target lin
  • 按类别(术语)过滤 WooCommerce $order 商品

    在这个问题中 我拥有所有的部分 但我似乎无法将它们组合在一起 我有一个 WooCommerce 订单的打印模板 它以正常方式列出产品 它们存储在数组中的顺序 这又是它们放置在购物篮中的顺序等 但是 我们希望它们按类别 术语 分组 所以这意味
  • 使用 SimpleCursorAdapter 更改 Cursor 的值

    我有包含列 名称 时间 UTC 格式 纬度 经度 的数据库表 我使用 ListActivity 和 SimpleCursorAdapter 显示该表 我希望 时间 列以人类可读的格式 2010 年 7 月 13 日 10 40 而不是 UT
  • UpdatePanel 内 FormView 中的 FileUpload

    场景 我有一个 ASP Net 网页 我打算用它来让用户 不是真正的用户 而是基本上的内容管理员 使用 FormView 插入和编辑表中的记录 该 FormView 位于 UpdatePanel 内部 因为我还使用级联下拉列表来让用户选择一
  • MeanBean EqualsMethodTester 和 HashCodeMethodTester 的自定义属性工厂

    是否可以配置自定义工厂来生成值EqualsMethodTester and HashCodeMethodTester课程来自org meanbean test 当我通过适用于的配置时BeanTester to EqualsMethodTes
  • GCP 将自定义域指向特定的 App Engine 服务

    我目前有一个包含四项服务的 Google App Engine 灵活项目 当我使用文档将自定义域映射到我的项目时https cloud google com appengine docs standard python mapping cu
  • 。 vs ::(点与双冒号)用于调用方法[重复]

    这个问题在这里已经有答案了 我正在学习 Ruby令人心酸的 Ruby 指南 http www rubyinside com media poignant guide pdf在一些代码示例中 我遇到了双冒号和点的使用 它们似乎用于相同的目的
  • 如何从 Date 对象中减去月份?

    如何从 VB NET 中的日期对象中减去月份 我努力了 Today AddMonths 1 但是 鉴于今天是 01 Jan 2010 我得到的结果是 01 Dec 2010 我想要的答案是 2009 年 12 月 1 日 在 NET 框架中
  • 使用 Swing 计时器:造成混乱

    只是希望字母的颜色随着一点停顿而改变 停顿可能会根据单词给出的时间和单词的长度而变化 下面的代码对我来说工作得很好 但我认为我的逻辑混乱了 我可以理解 但我的队友应该很容易理解 Code import java awt Color impo