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 create a separate class * for our listeners. * * @author Samuel A. Rebelsky * @version 1.0 of October 2004 */ public class ButtonsThree extends JFrame { /** All the buttons in the program. */ JButton[] buttons; /** The number of buttons in the program. */ int numButtons; private ButtonsThree(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(new MyListener(buttons[pos], this)); pane.add(buttons[pos]); } // inner for } // outer for //Display the window. this.pack(); this.setVisible(true); } // ButtonsThree(String) 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 ButtonsThree("3x2", 3, 2); new ButtonsThree("4x1", 4, 1); } }); } // main(String[]) } // class ButtonsThree class MyListener implements ActionListener { /** The number of the button we're listening to. */ JButton button; /** The frame that contains that button. */ ButtonsThree owner; /** Guess. */ public MyListener(JButton _button, ButtonsThree _owner) { this.button = _button; this.owner = _owner; } // MyListener(int, ButtonsThree) public void actionPerformed(ActionEvent ae) { JButton target = owner.buttons[(Integer.parseInt(this.button.getText()) + 2) % owner.numButtons]; target.setText(Integer.toString((Integer.parseInt(target.getText()) + Integer.parseInt(button.getText())) % owner.numButtons)); } // actionPerformed(ae) } // class MyListener