Search code examples
javaswingswingworker

swing - short-time highlight of a component


I have a JTable, where a user can select a single row. If that happens, i want to "highlight" another part of the page for a short time to indicate that this is the part of the page that changed after the user interaction.

So my question is: What's the best way to achieve this? At the moment i did it by setting the background color of that panel and starting a SwingWorker which sets the Color back after a short delay. It works as intended, but is it a good idea to use a SwingWorker like that? Are there any drawbacks to that approach? How would you solve this?

Thanks in advance.


Solution

  • I guess a Swing Timer would be a better option as it reuses a single thread for all scheduled events and executes the event code on the main event loop. So, inside your SelectionListener code you do:

    // import javax.swing.Timer;
    
    final Color backup = componentX.getBackground();
    componentX.setBackground(Color.YELLOW);
    final Timer t = new Timer(700, new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        componentX.setBackground(backup);
      }
    });
    t.setRepeats(false);
    t.start();