highlighting the word in java
Asked Answered
U

2

1

I am triying to highlight a word, but only .length()-2 at 1st time,delay and then last 2 words.The first words are highlighted but it is not highlighting the last two words after delay.please help. here is the code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
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 newkarao {

private int[] timings = {600, 1000, 400,50};
private String[] words = new String[]{"Hellojjkhl", "java", "whoooooh","bye"};
private DefaultHighlighter.DefaultHighlightPainter highlightPainter = new       DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);
private int count = 0;
private int xx=0,tlength,spe;
private boolean fisrTime = true;
private JFrame frame;
private JTextPane jtp;
JButton startButton;

public newkarao() {
    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 = null;
            try {
                t = createAndStartTimer(timings[count], count);
            } catch (InterruptedException ex) {
                Logger.getLogger(newkarao.class.getName()).log(Level.SEVERE, null, ex);
            }

            while (t.isRunning()) {//wait for timer to be done
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(newkarao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            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) throws InterruptedException {

    try {
        int sp = 0;
        for (int i = 0; i < count; i++) {
            sp += words[i].length() + 1;
            spe=sp;
        }
   //     int a=timings[xx];xx++;
        System.out.println("jfd");
        tlength=words[count].length();//Thread.currentThread().sleep(5000);
        jtp.getHighlighter().addHighlight(sp, sp + words[count].length()-2, highlightPainter);
        System.out.println(sp + words[count].length()-2);
    } catch (BadLocationException ex) {
        ex.printStackTrace();
    }

    Timer t = new Timer(delay, new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {System.out.println(spe + words[count].length());
                jtp.getHighlighter().addHighlight(spe, spe + words[count].length(), highlightPainter);
                System.out.println("sleep");
               //    Thread.currentThread().sleep(5000);

                jtp.getHighlighter().removeAllHighlights();
            } catch (BadLocationException ex) {
                Logger.getLogger(newkarao.class.getName()).log(Level.SEVERE, null, ex);
            }


        }
    });
    t.setRepeats(false);
    t.start();
    return t;
   }

   public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new newkarao();
        }
    });
   }
 }
Unbridle answered 20/11, 2012 at 17:39 Comment(7)
Please look again at the example I gave in your last question. It did not contain Thread.sleep() on EDT. Thread.sleep was called from another Thread and not EDT. This can cause many UI problemsBev
never to use Thread.currentThread().sleep(5000); in Swing, for why reason is delayed action from Swing Timer and (again) killed by Thread.currentThread().sleep(5000);Superheterodyne
@DavidKroukamp i removed that..still its not working.i removed sleepy thing.Unbridle
@joeyrohan you have changed the code alot since I last saw it, as I said an SSCCE would do. But in your situation go back to the code that was working and implement new features slowly testing after each to make sure all is working as expectedBev
i did the same thing...slowly,i'll give sscceUnbridle
@DavidKroukamp i have pasted the code..please do have a look.please help david.Unbridle
Piece of advice for the next time you post code: respect java naming conventions, provide decent indentation, remove all your System.out debug output, remove all your pieces of code which are commented out, ... . That makes it a lot more readable. Compare your code snippet with the cleaned up version posted by @DavidKroukamp .Till
B
4

I dont think you understand me.

Using my newest example I made this one (note this is updated code from example in last question. Now uses Swing Timers only):

private int[] timings = {2000, 4000, 0, 3000, 2000};//word timings
private String[] words = {"Hel", "lo", " ", "wor", "ld"};//each indiviaul word

private String sentence = "Hello world";//entire string for writing to JSCrollPane

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicBoolean;
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, 4000, 0, 3000, 2000};//word timings
    private String[] words = {"Hel", "lo", " ", "wor", "ld"};//each indiviaul word
    private String sentence = "Hello world";//entire string for writing to JSCrollPane
    private DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
    private int count = 0;
    private boolean fisrTime = true;
    private JFrame frame;
    private JTextPane jtp;
    private JButton startButton;
    private AtomicBoolean done = new AtomicBoolean(false);

    public KaraokeTest() {
        initComponents();
    }

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

        jtp = new JTextPane();

        jtp.setText(sentence);
        jtp.setEditable(false);

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

        createAndStartTimer(timings[count], count);

        Timer t = new Timer(1, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                if (done.get()) {
                    count++;
                    if (count == timings.length) {
                        JOptionPane.showMessageDialog(frame, "Done");
                        startButton.setEnabled(true);
                        count = 0;
                        fisrTime = true;
                        done.getAndSet(false);
                        ((Timer) ae.getSource()).stop();
                    } else {
                        ((Timer) ae.getSource()).stop();
                        startKaraoke();
                    }
                }
            }
        });
        done.getAndSet(false);//to synchronize when the remove highlight timer is done so a clash between adding highlights before the timer is done doesnt occur
        t.start();
    }

    private void createAndStartTimer(int delay, final int count) {
        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();
                done.getAndSet(true);//so that out other timer knows we are done completly and can add new higlights
            }
        });
        t.setRepeats(false);
        t.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new KaraokeTest();
            }
        });
    }
}
Bev answered 20/11, 2012 at 18:54 Comment(7)
I'm probably missing something, but isn't jtp.getHighlighter().addHighlight in createAndStartTimer being called out side the EDT?Slotnick
Can you explain why you took over that weird while( t.isRunning() ) construction. Why not simply integrate the code after the while loop in the ActionListener of the timer (or add an extra ActionListener on the timer). Isn't that one of the reasons for which a Swing timer was developed ... do something on the EDT after a delayTill
@Till +1 yes very true, I did do it a bit round about ( I guess I was tired when writing that code :P) will update again soonBev
@Till updated code to use Timers only. Had to add an AtomicBoolean using Timer#isRunning() was proving some anomalies ( a few times the remove highlighting timer was still busy, a highlight would be added and the remove highlight timer would complete thus erasing the new and old highlight)Bev
@joeyrohan please see my updated post. Hope that clears up your troublesBev
@DavidKroukamp I had more something in mind that the createAndStartTimer method would return a Timer to which you would attach an ActionListenerTill
@DavidKroukamp I added an answer to illustrate what I meantTill
T
2

You can achieve this with one Timer as well by simply adjusting the delay for the Timer. Just took the code from @DavidKroukamp and removed one of the Timer instances

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicBoolean;

public class KaraokeTest {

  private int[] timings = {2000, 4000, 0, 3000, 2000};//word timings
  private String[] words = {"Hel", "lo", " ", "wor", "ld"};//each indiviaul word
  private String sentence = "Hello world";//entire string for writing to JSCrollPane
  private DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
  private boolean fisrTime = true;
  private JFrame frame;
  private JTextPane jtp;
  private JButton startButton;
  private AtomicBoolean done = new AtomicBoolean(false);

  public KaraokeTest() {
    initComponents();
  }

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

    jtp = new JTextPane();

    jtp.setText(sentence);
    jtp.setEditable(false);

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

    Timer t = new Timer( timings[0], new ActionListener() {
      private int currentIndex = 0;
      @Override
      public void actionPerformed( ActionEvent e ) {
        clearHighlights();
        highlightWord( currentIndex );
        currentIndex++;
        if ( currentIndex < timings.length ){
          ( ( Timer ) e.getSource() ).setDelay( timings[currentIndex] );
          ( ( Timer ) e.getSource() ).restart();
        } else {
          ( ( Timer ) e.getSource() ).stop();
        }
      }
    } );
    t.setRepeats( true );

    t.start();
  }

  private void highlightWord( int index ){
    int sp = 0;
    for (int i = 0; i < index; i++) {
      sp += words[i].length();
    }
    try {
      jtp.getHighlighter().addHighlight(sp, sp + words[index].length(), highlightPainter);
    } catch (BadLocationException ex) {
      ex.printStackTrace();
    }
  }
  private void clearHighlights(){
    jtp.getHighlighter().removeAllHighlights();
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        new KaraokeTest();
      }
    });
  }
}
Till answered 20/11, 2012 at 22:53 Comment(2)
I see now what was ment. But there seems to be a few things wrong with the codes functionality when compared to the original.Bev
@DavidKroukamp Possibly. I did not really check the original code. Just posted this answer to illustrate what I meantTill

© 2022 - 2024 — McMap. All rights reserved.