/* * NumberAction.java demos a GridLayout with Action listeners for each button. */ import java.awt.*; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class NumberAction extends JPanel implements ActionListener{ public NumberAction(){ this.setLayout(new GridLayout(0,3)); JButton j1 = new JButton("1"); j1.setActionCommand("1"); j1.addActionListener(this); this.add(j1); j1 = new JButton("2"); j1.setActionCommand("2"); j1.addActionListener(this); this.add(j1); j1 = new JButton("3"); j1.setActionCommand("3"); j1.addActionListener(this); this.add(j1); j1 = new JButton("4"); j1.setActionCommand("4"); j1.addActionListener(this); this.add(j1); j1 = new JButton("5"); j1.setActionCommand("5"); j1.addActionListener(this); this.add(j1); j1 = new JButton("6"); j1.setActionCommand("6"); j1.addActionListener(this); this.add(j1); } public void actionPerformed(ActionEvent e){ if ("1".equals(e.getActionCommand())) System.out.println(1); else if ("2".equals(e.getActionCommand())) System.out.println(2); else if ("3".equals(e.getActionCommand())) System.out.println(3); else if ("4".equals(e.getActionCommand())) System.out.println(4); else if ("5".equals(e.getActionCommand())) System.out.println(5); else if ("6".equals(e.getActionCommand())) System.out.println(6); } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("NumberAction"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane. //addComponentsToPane(frame.getContentPane()); NumberAction newContentPane = new NumberAction(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }