package example6_1_MultipleListeners; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MultipleListenerGui extends JFrame /* implements ActionListener*/ { private class HandleDogButton implements ActionListener { public void actionPerformed(ActionEvent e) { label.setText("woof2"); } } private final JLabel label; private final JButton dogButton; private final JButton ponyButton; public static void main(String[] ignored) { new MultipleListenerGui(); } public MultipleListenerGui() { setTitle("Multiple Listener GUI"); setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); dogButton = createDogButton(); add(dogButton); ponyButton = createPonyButton(); add(ponyButton); label = createLabel(); add(label); pack(); setVisible(true); } private JButton createDogButton() { JButton b = new JButton("Pony"); // b.addActionListener(this); return b; } private JButton createPonyButton() { JButton b = new JButton("Dog"); // b.addActionListener(new ActionListener(){ // public void actionPerformed(ActionEvent e) { // label.setText("woof"); // } // }); //named inner class b.addActionListener(new HandleDogButton()); return b; } private JLabel createLabel() { JLabel label = new JLabel(); label.setText("This text determines the initial size of the label"); Dimension size = label.getPreferredSize(); label.setText(""); System.out.println("Preferred Size: " + size); label.setPreferredSize(size); System.out.println("New preferred Size: " + label.getPreferredSize()); return label; } // @Override // public void actionPerformed(ActionEvent e) { // System.out.println("actionPerformed called"); // e.getActionCommand(); // e.getSource(); // if(e.getSource() == dogButton) { // label.setText("Woof!"); // } else if(e.getSource() == ponyButton) { // label.setText("Neyyy!"); // } else { // System.out.println("Warning: Unknown source: "+e.getSource()); // } // if(e.getActionCommand().equals("Dog")) { // ponyButton.setText("Pony"); // ponyButton.setActionCommand("Pony"); // } else if (e.getActionCommand().equals("Pony")) { // ponyButton.setText("Dog"); // ponyButton.setActionCommand("Dog"); // } else { // System.out.println("Warning: Unknown command: "+e.getActionCommand()); // } // } }