Skip to content

Instantly share code, notes, and snippets.

@sfcgeorge
Created June 2, 2015 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfcgeorge/83027af0338c7c34adf8 to your computer and use it in GitHub Desktop.
Save sfcgeorge/83027af0338c7c34adf8 to your computer and use it in GitHub Desktop.
Different ways to add an ActionListener to a JButton.
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Buttons {
public static void main(String[] args) {
new JFrame("Different ways of creating JButtons") {{
getContentPane().setLayout(new FlowLayout());
JButton b1 = new JButton("Click");
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Tickles!");
}
}
b1.addActionListener(new MyActionListener());
add(b1);
JButton b2 = new JButton("Click");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Tickles!");
}
});
add(b2);
add(new JButton("Click") {{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Tickles!");
}
});
}});
add(new JButton("Click") {{
addActionListener(e -> System.out.println("Tickles!"));
}});
pack();
setVisible(true);
}};
}
}
@arju15
Copy link

arju15 commented Oct 15, 2018

thanks.

@tomeandrew
Copy link

good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment