swing - short-time highlight of a component

Deadly 提交于 2019-12-11 03:21:56

问题


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.


回答1:


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();



回答2:


I recommend a swing Timer (javax.swing.Timer). (do NOT use the Timer class in Java.util)

This is where you make the timer:

Timer t = new Timer(loopTime,actionListener)//loopTime is unimportant for your use of this
t.setInitialDelay(pause)//put the length of time between starting the timer and the color being reverted to normal
t.setRepeats(false);//by default, timer class runs on loop.
t.start();//runs the timer

It probably makes sense to hold on to a reference to the timer, and then just call t.start when you need it.

You need to implement an action listener to handle the timer events. I can edit this if you don't know how to do that, but as you are already doing stuff with Swing I figure it shouldn't be a problem.



来源:https://stackoverflow.com/questions/11396859/swing-short-time-highlight-of-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!