Skip to content

Instantly share code, notes, and snippets.

@rishi93
Last active November 11, 2015 09:07
Show Gist options
  • Save rishi93/3e87302ba353e2fdaf3c to your computer and use it in GitHub Desktop.
Save rishi93/3e87302ba353e2fdaf3c to your computer and use it in GitHub Desktop.
Swing Buttons with Action Listener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
class MyFrame extends JFrame
{
public MyFrame()
{
this.setTitle("Example Application");
this.setSize(400,100);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
}
}
class Clicker implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
if(cmd == "hi")
{
System.out.println("Hi !");
}
else if(cmd == "bye")
{
System.out.println("Bye !");
}
}
}
class MyApp
{
public MyApp()
{
MyFrame myframe = new MyFrame();
JButton hibutton = new JButton("Hi!");
hibutton.setActionCommand("hi");
hibutton.addActionListener(new Clicker());
hibutton.setToolTipText("Prints Hi!");
JButton byebutton = new JButton("Bye!");
byebutton.setActionCommand("bye");
byebutton.addActionListener(new Clicker());
byebutton.setToolTipText("Prints Bye!");
JLabel mylabel = new JLabel("Hello World!");
myframe.add(mylabel);
myframe.add(hibutton);
myframe.add(byebutton);
myframe.setVisible(true);
}
}
public class test
{
public static void main(String args[])
{
MyApp myapp = new MyApp();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment