highlighting words in java

highlight, java, swing, text

Solution

+1 to StanislavL answer.

Did a short example hope it helps.

Here I create my words and their timings:

int[] timings = {2000, 1000, 4000};
String[] words = new String[]{"Hello", "java", "whoooooh"};

After start button is clicked:

after 2000 miliseconds:

After 1000:

After 4000miliseconds:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.BadLocationException;
import javax.swing.text.DefaultHighlighter;

public class KaraokeTest {

    private int[] timings = {2000, 1000, 4000};
    private String[] words = new String[]{"Hello", "java", "whoooooh"};
    private DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);
    private int count = 0;
    private boolean fisrTime = true;
    private JFrame frame;
    private JTextPane jtp;
    JButton startButton;

    public KaraokeTest() {
        initComponents();
    }

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

        jtp = new JTextPane();

        for (String s : words) {
            String tmp = jtp.getText();
            if (tmp.equals("")) {
                jtp.setText(s);
            } else {
                jtp.setText(tmp + " " + s);
            }
        }

        startButton = new JButton("Start");
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                startKaraoke();
            }
        });

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

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

    private void startKaraoke() {
        if (fisrTime) {
            startButton.setEnabled(false);
            fisrTime = false;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {

                Timer t = createAndStartTimer(timings[count], count);

                while (t.isRunning()) {//wait for timer to be done
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }

                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        count++;
                        if (count == timings.length) {
                            JOptionPane.showMessageDialog(frame, "Done");
                            startButton.setEnabled(true);
                            count = 0;
                        } else {
                            startKaraoke();
                        }
                    }
                });

            }
        }).start();
    }

    private Timer createAndStartTimer(int delay, final int count) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                int sp = 0;
                for (int i = 0; i < count; i++) {
                    sp += words[i].length() + 1;
                }
                try {
                    jtp.getHighlighter().addHighlight(sp, sp + words[count].length(), highlightPainter);
                } catch (BadLocationException ex) {
                    ex.printStackTrace();
                }
            }
        });

        Timer t = new Timer(delay, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                jtp.getHighlighter().removeAllHighlights();
            }
        });
        t.setRepeats(false);
        t.start();
        return t;
    }

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

UPDATE:

Fixed the above code to be able to highlight individual characters within the sentence for a specified amount of time:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.BadLocationException;
import javax.swing.text.DefaultHighlighter;

public class KaraokeTest {

    private int[] timings = {2000, 1000, 4000, 2000, 3000};//char timings
    private String[] words = {"H", "e", "l", "l", "o"};//each indiviaul word
    private String sentence = "Hello";//entire string for writing to JSCrollPane
    private DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);
    private int count = 0;
    private boolean fisrTime = true;
    private JFrame frame;
    private JTextPane jtp;
    JButton startButton;

    public KaraokeTest() {
        initComponents();
    }

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

        jtp = new JTextPane();

        jtp.setText(sentence);

        startButton = new JButton("Start");
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                startKaraoke();
            }
        });

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

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

    private void startKaraoke() {
        if (fisrTime) {
            startButton.setEnabled(false);
            fisrTime = false;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {

                Timer t = createAndStartTimer(timings[count], count);

                while (t.isRunning()) {//wait for timer to be done
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }

                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        count++;
                        if (count == timings.length) {
                            JOptionPane.showMessageDialog(frame, "Done");
                            startButton.setEnabled(true);
                            count = 0;
                            fisrTime = true;
                        } else {
                            startKaraoke();
                        }
                    }
                });

            }
        }).start();
    }

    private Timer createAndStartTimer(int delay, final int count) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                int sp = 0;
                for (int i = 0; i < count; i++) {
                    sp += words[i].length();
                }
                try {
                    jtp.getHighlighter().addHighlight(sp, sp + words[count].length(), highlightPainter);
                } catch (BadLocationException ex) {
                    ex.printStackTrace();
                }
            }
        });
        Timer t = new Timer(delay, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                jtp.getHighlighter().removeAllHighlights();
            }
        });
        t.setRepeats(false);
        t.start();
        return t;
    }

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

Problem

I wanted to highlight the words,for a specific time (just like in karaoke apps). each word will have a specific time for highlighting.i am able to take timings,but getting no where .How to highlight a word for a perticular duration.searched alot on stackoverflow and google,but dead end. and can i take help of java script or html?? please help me out. here is a piece of code how i am taking timing: ``` millis mil=new millis(); if(true){ if(flag==1) flag=0; else flag=1; if(flag==0) value=mil.done(flag,start); start=value; if(flag==1) value=mil.done(flag,start);//function to calculate duration }System.out.println("val:"+(value-3086610)); // System.out.println("gyjghjghjghj"+(System.nanoTime()-start2)); String s = textArea.getText(); char[] words=s.toCharArray(); for(i=last;words[i]!=' '&&words[i]!='\n';i++,last=i) { } try {//System.out.println(acount); hilit.addHighlight(first, last, painter); last++; first=last; } catch (BadLocationException ex) { Logger.getLogger(newh.class.getName()).log(Level.SEVERE, null, ex); } ``` this is how i am able to time each word. thank you.

Original source