/* * NumberActionGB.java demos a GridBagLayout with Action listeners for each button. */ import java.awt.*; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class NumberActionGB extends JPanel implements ActionListener{ public NumberActionGB(){ this.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; //c.fill = GridBagConstraints.VERTICAL; JButton j1 = new JButton("1"); j1.setActionCommand("1"); j1.addActionListener(this); c.weightx = 0.5; c.gridx = 0; c.gridy = 0; this.add(j1, c); j1 = new JButton("2"); j1.setActionCommand("2"); j1.addActionListener(this); c.weightx = 0.5; c.gridx = 1; c.gridy = 0; this.add(j1, c); j1 = new JButton("3"); j1.setActionCommand("3"); j1.addActionListener(this); c.weightx = 0.5; c.gridx = 2; c.gridy = 0; this.add(j1, c); j1 = new JButton("4"); j1.setActionCommand("4"); j1.addActionListener(this); c.weightx = 0.1; c.gridx = 0; c.gridy = 1; this.add(j1, c); j1 = new JButton("5"); j1.setActionCommand("5"); j1.addActionListener(this); c.weightx = 0.5; c.gridx = 1; c.gridy = 1; this.add(j1, c); j1 = new JButton("6"); j1.setActionCommand("6"); j1.addActionListener(this); c.weightx = 0.5; c.gridx = 2; c.gridy = 1; this.add(j1, c); } 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("NumberActionGB"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane. //addComponentsToPane(frame.getContentPane()); NumberActionGB newContentPane = new NumberActionGB(); 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(); } }); } }