Skip to content

Instantly share code, notes, and snippets.

@jimmykurian
Created March 13, 2012 05:24
Show Gist options
  • Save jimmykurian/2026977 to your computer and use it in GitHub Desktop.
Save jimmykurian/2026977 to your computer and use it in GitHub Desktop.
A Java program that has two buttons, each of which prints a message “I was clicked n time!” whenever the button is clicked. Each button has a separate click count.
//ButtonViewer.java - Jimmy Kurian
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonViewer
{
private static final int FRAME_WIDTH = 100;
private static final int FRAME_HEIGHT = 100;
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button1 = new JButton("Click me!");
panel.add(button1);
JButton button2 = new JButton("Click me!");
panel.add(button2);
frame.add(panel);
ActionListener listener = new ClickListener();
button1.addActionListener(listener);
ActionListener listener2 = new ClickListener();
button2.addActionListener(listener2);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//ClickListener.java - Jimmy Kurian
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ClickListener implements ActionListener
{
private int numClicks = 0;
public void actionPerformed(ActionEvent event)
{
numClicks++;
System.out.println("I was clicked " + numClicks + " times.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment