package rebelsky.swing; import java.awt.Container; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; /** * A fairly simple sample Swing program to illustrate one method of * listening to buttons. In this case, we use the "master" class * as our listener. * * @author Samuel A. Rebelsky * @version 1.0 of October 2004 */ public class ButtonsTwo extends JFrame implements ActionListener { /** All the buttons in the program. */ JButton[] buttons; /** The number of buttons in the program. */ int numButtons; private ButtonsTwo(String _title, int width, int height) { super(_title); //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); // Exit nicely when closing this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Get the useful part of this frame. Container pane = this.getContentPane(); pane.setLayout(new GridLayout(width,height)); // Build and add the buttons this.numButtons = width*height; buttons = new JButton[this.numButtons]; for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { int pos = h*width + w; buttons[pos] = new JButton(Integer.toString(pos)); buttons[pos].addActionListener(this); pane.add(buttons[pos]); } // inner for } // outer for //Display the window. this.pack(); this.setVisible(true); } // ButtonsTwo(String) public void actionPerformed(ActionEvent ae) { JButton b = (JButton) ae.getSource(); JButton target = buttons[(Integer.parseInt(b.getText()) + 2) % numButtons]; target.setText(Integer.toString((Integer.parseInt(target.getText()) + Integer.parseInt(b.getText())) % numButtons)); } // actionPerformed(ae) public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { new ButtonsTwo("3x2", 3, 2); new ButtonsTwo("4x1", 4, 1); } }); } // main(String[]) } // class ButtonsTwo