0

Hello I have the following code which shows an empty white JPanel that changes from white to grey when I hover mouse over the JPanel. Here is the code:

package demos;

import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Panel extends JFrame{
    private JPanel panel = new JPanel();
    public Panel(){
        panel.addMouseListener(new MouseListener(){
            @Override
            public void mouseClicked(MouseEvent e) {
            }
            @Override
            public void mouseEntered(MouseEvent e) {
                panel.setBackground(Color.GRAY);
            }
            @Override
            public void mouseExited(MouseEvent e) {
                panel.setBackground(Color.white);
            }
            @Override
            public void mousePressed(MouseEvent e) {
            }
            @Override
            public void mouseReleased(MouseEvent e) {
            }
        });
        this.setSize(400,400);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setContentPane(panel);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new Panel().show();
            }
        });
    }
}

Now my question is.Can i add a transition before changing from one color to another?

Thanks for your time

cssGEEK
  • 994
  • 2
  • 15
  • 38

1 Answers1

1

Now my question is.Can i add a delay efore changing from one color to another?

Yes,

  • First interpolate some colors between the current color and the desired color. A simple linear interpolation will do just fine.
  • Create an ArrayList<Color> and fill it with your interpolated colors, in order.
  • Use a Swing Timer.

  • In the Timers ActionListener:

    • Change the JPanels color with the next color in the ArrayList.
    • Advance an int index variable, the one that you use in the get(...) method on the ArrayList.
    • Call repaint() on the JPanel.
    • Continue doing this until the panel is the color that you want. At this point, stop the Timer.
MasterBlaster
  • 948
  • 2
  • 12
  • 26
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373