You are going to have to move your code around a little because of the fact that you create the buttons dynamically, add them to the form and don't keep a reference to them for later use. So either you will have to do something like create an array of buttons to store references to each button in or access each button through the JFrame which can get tricky.
But below I have made some modifications to your program to show you how essentially this will work with a Timer object. Timer is part of the swing library and is requires nothing extra on your part other than to include event listening.
We create a timer, tell it how often to fire and where it can find an event handler to handle the timer firing event. So we have added an action listener to the class which implements the actionPerformed method. Now each time the timer event fires, it will look to the Buttonss class to handle the event. In turn that class will point the event to the actionPerformed method where we then enable and disable a button once each second.
Since you do end the loop having a reference to number 15 button, I could show you how we can use your button reference to then toggle the button to create a flashing setup.
import java.awt.event.*;
import java.awt.*;
import java.awt.event.*; // Used for actionListening
import javax.swing.*;
public class Buttonss extends JFrame implements ActionListener
{
// Create a timer class (this is part of swing)
Timer t;
Buttonss()
{
// Set the timer up to call this class every 1000 milliseconds
t = new Timer(1000,this);
this.setSize(500,500);
this.setTitle("Buttons");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new GridLayout(4,4));
int n = 4;
Dimension d = new Dimension(20,20);
int count;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
count = i*n+j;
if(count>0)
{
button = new JButton(new Integer(count).toString());
button.setPreferredSize(d);
add(button);
}
}
}
this.setVisible(true);
// Start the timer after the form is fully loaded
t.start();
}
JButton button;
public static void main(String args[]) {
Buttonss b = new Buttonss();
}
// This event handles the timer's ticking, it is part of the Action listener
public void actionPerformed(ActionEvent e) {
// If the source of this event firing was the timer, go to the last button setup and toggle enabled/disabled
// If the button is enabled, disable it. Next time event fires, it will then re-enable it.
if (e.getSource() == t) {
if (button.isEnabled()) { button.setEnabled(false); }
else { button.setEnabled(true); }
}
}
}
If you follow some of the in code comments you will see what I am doing here. It is not too complicated as long as you understand that the timer object is triggering the current class' actionPerformed event.
Hope this helps you out. Enjoy!
"At DIC we be timer class mastering code ninjas... there are 12 numbers on the clock because the ancients thought 12 was the perfect number, that was until they called 1-800-CALL-DIC and discovered that was the perfect number"