1

I need to write a program in such a way that each button glows and then dims sequentially. I can't use threads because they will glow simultaneously, timers also don't seem to work.

My code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class test extends JApplet
{
    JButton a,b,c;
    JButton board[]=new JButton[3];
    Color color;

    public void makeGUI()
    {
        setLayout(new GridLayout(2,3));
        a=new JButton("a");
        b=new JButton("b");
        c=new JButton("c");

        a.setBackground(Color.red);
        b.setBackground(Color.blue);
        c.setBackground(Color.green);

        add(a);
        add(b);
        add(c);

        board[0]=(JButton)a;
        board[1]=(JButton)b;
        board[2]=(JButton)c;


        glowing();
    }

    public void glowing()
    {
        for(int i=0;i<3;i++)
        {
            glow(i);

            long start = System.currentTimeMillis( );
            while(System.currentTimeMillis( ) - start < 2000){}

            dim(i);
        }
    }

    public void init()
    {
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                public void run()
                {
                    makeGUI();
                }
            });
        }
        catch(Exception exc)
        {
            System.out.println("can't create because of :"+exc);
        }
    }

    public void glow(int x)
    {
        color=board[x].getBackground();
        board[x].setBackground(color.brighter());
    }

    public void dim(int x)
    {
        board[x].setBackground(color);
    }
}

output: The screen stays blank and the buttons pop up together at last.

  • Instead of using `long start = System.currentTimeMillis( ); while(System.currentTimeMillis( ) - start < 2000){}` to cause the pause between glowing and dimming you probably want to use Thread.sleep() - way less cpu intensive – k.krol.27 Jul 12 '17 at 17:31
  • Do you want to like stagger the dimming and glowing? Should only one glow at a time? – k.krol.27 Jul 12 '17 at 17:33
  • 1
    The most pressing issue: you lock up the AWTEventQueue, which means the UI will be locked entirely down until the `glowing`-method has terminated. Relocate this portion of the code to [another thread](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) in order to get a functioning UI –  Jul 12 '17 at 17:39
  • This [example](https://stackoverflow.com/a/2234020/230513) illustrates using a Swing `Timer`. – trashgod Jul 13 '17 at 00:06
  • @k.krol.27 Yes! One should glow at a time. – Novice Coder Jul 13 '17 at 11:34

0 Answers0