Jonathan Holloway
Jonathan Holloway

Reputation: 63734

How can I best implement a Fade Button Effect in Swing?

I have a JButton which, when pressed, changes background color from active to normal:

final Color activeButtonColor = new Color(159, 188, 191);
final Color normalButtonColor = new Color(47, 55, 56);

I want to fade the active button color back to the normal button color when a specific task has finished executing. I'm using SwingWorker and wondered if anybody could suggest an efficient way to do this please?

button.addActionListener(new ActionListener() {
  public void actionPerformed(final ActionEvent event) {

    new SwingWorker<Object, Object>() {

      protected Object doInBackground() throws Exception {
        button.setBackground(activeButtonColor);
        for (int note = 60; note < 120; note++) {
          midiController.sendMidiMessage(1, note, 83);
          midiController.stopMidiMessage(note, 83);
        }
        Thread.sleep(200);
        return null;
      }

      protected void done() {
        try {
          Object result = get();

          // Fade back
        } catch (Exception ex) {
          ex.printStackTrace();
          if (ex instanceof java.lang.InterruptedException)
            return;
        }
      }
    }.execute();
  }
});

EDIT: Just to be clear, I'm looking for an efficient way to fade the RGB values for activeButtonColor back to normalButtonColor, without having to create a huge number of Color objects. Is it possible? Or do I just have to limit the number of fade steps to be more efficient?

Upvotes: 2

Views: 1219

Answers (2)

Paul Brinkley
Paul Brinkley

Reputation: 6363

Color objects should be fairly lightweight; they're basically just four floats plus a handful of pointers to pre-existing objects. If you really want to save on Color object instantiation, and you're sure the start and end colors above will not change, you could precompute the Color objects for the fade sequence, but I'm quite sure you could compute them on the fly as well, and suffer no consequences.

Upvotes: 0

John Ellinwood
John Ellinwood

Reputation: 14531

Create a method that takes 3 arguments, a button, a from color and to color. Inside the method, create a swingworker to run in the background that does the fade of the colors.

Then on your actionlistener where you do your work, before you do anything, call the fade method from active to normal. When its done, call the fade method from normal to active.

You'll end up with 3 total swingworkers being used in this situation. One for your work, one for the first fade and one for the last fade.

Upvotes: 1

Related Questions