import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ArraysOfGraphicalObjects extends JFrame implements ActionListener { public static void main(String[] args) { new ArraysOfGraphicalObjects(); } // Constructor public ArraysOfGraphicalObjects() { // Set up the JFrame that has been automatically created by the 'JFrame' class setLayout(null); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(335, 195); setTitle("Arrays of Graphical Objects"); getContentPane().setBackground(Color.BLACK); setLocationRelativeTo(null); // Create an array of eight JButtons; note that in addition to JButtons, arrays // can be created for all types of graphical objects JButton[] buttons = new JButton[8]; for (int i = 0; i < 8; i++) { // Use the array element number (position) of each JButton in its caption buttons[i] = new JButton("I am JButton #" + (i + 1)); // Use the array element positions of the JButtons to arrange the JButtons // on the JFrame buttons[i].setLocation(10 + 160 * (i / 4), (i % 4) * 40 + 10); // If the 'setActionCommand' method has not been used, the 'getActionCommand' // method will return the caption (text) of the JButton; to make for easier // identification and processing of the buttons when they are clicked, the // 'setActionCommand' method is used here to set the text of each button to // its element position (plus one) in the array of JButtons buttons[i].setActionCommand(Integer.toString(i + 1)); buttons[i].setSize(150, 30); buttons[i].setFocusable(false); buttons[i].addActionListener(this); buttons[i].setVisible(true); add(buttons[i]); } setVisible(true); } public void actionPerformed(ActionEvent event) { System.out.println(event.getActionCommand()); } }