inner ActionListener classThis tutorial will teach you how to use an inner ActionListener class to perform actionPerformed method on JButtons.Check out below articles related to this one.
- Anonymous inner JButton ActionListener class
- Checking event source in actionPerformed ActionListener method
- How to use JButton getActionCommand Method
- How to set JButton Mnemonic key
inner ActionListener class Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<textarea class="java" cols="10" name="code" rows="10">/** * * @author Eric Mutua * Blog.www.techoverload.net */ import javax.swing.JButton; import javax.swing.JFrame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JavaInnerClass extends JFrame { public JButton b1,b2; //Inner class code class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent evt) { if(evt.getSource()==b1) { System.out.println("You clicked Button 1"); } else if(evt.getSource()==b2) System.out.println("You clicked Button 2"); }} //end of inner class JavaInnerClass() { super("Java Class Example"); b1=new JButton("Button 1"); b2=new JButton("Button 2"); b1.setBounds(10, 10, 100, 30); b2.setBounds(120,10, 100, 30); add(b1); add(b2); b1.addActionListener(new ButtonListener()); b2.addActionListener(new ButtonListener()); setSize(300,300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setLayout(null); setVisible(true); } public static void main(String args[]) { new JavaInnerClass(); } } </textarea> |
