Skip to content

Instantly share code, notes, and snippets.

@figengungor
Created March 11, 2013 22:16
Show Gist options
  • Select an option

  • Save figengungor/5138386 to your computer and use it in GitHub Desktop.

Select an option

Save figengungor/5138386 to your computer and use it in GitHub Desktop.
Java GUI >> Adding Action Listener to Button
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyGUI extends JFrame {
JPanel jp1,jp2;
JButton jb1,jb2;
public MyGUI(){
setTitle("Background Color Example");
setSize(600,600);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp1 = new JPanel();
jp2 = new JPanel();
jb1 = new JButton();
jb2 = new JButton();
//Adding images onto buttons and adding buttons onto panel jp1
jb1.setIcon(new ImageIcon("C://pn.jpg"));
jp1.add(jb1);
jb2.setIcon(new ImageIcon("C://pn.jpg"));
jp1.add(jb2);
//Adding panels to frame
add(jp1, BorderLayout.SOUTH); //this panel contains buttons and located onto south border
add(jp2); //this panel's background color will be changed with button clicks
//Adding action listeners to buttons
jb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jp2.setBackground(Color.BLUE);
}
});
jb2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jp2.setBackground(Color.GREEN);
}
});
validate(); //if you do not validate, image will not be displayed unless you resize your window
}
public static void main(String [] args) {
new MyGUI()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment