Credits

Sunday, August 29, 2010

Java's Action Events

 Graphical User Interface (GUI) is highly preferred over the traditional method since it is much way easier and when you make any application,  a GUI interface using frames  and other components can make your user appreciate more your works.

But, interaction can only happen when events are applied on GUI components like buttons, windows, text fields, list and others.

However, an appropriate listener must be integrated along with these components. The program below shows the use of event on buttons with action listener to invoke the event method.
[+/-] show/hide


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonActionEventv2 extends JFrame implements ActionListener
{
JButton redButton = new JButton("Red");
JButton greenButton = new JButton("Green");
JButton blueButton = new JButton("Blue");
JPanel pane=new JPanel();
public ButtonActionEventv2(){

setTitle("Button Action Event Frame");
setSize(300,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

redButton.addActionListener(this);
pane.add(redButton);

greenButton.addActionListener(this);
pane.add(greenButton);
blueButton.addActionListener(this);
pane.add(blueButton);
add(pane);
setVisible(true);
}

public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source==redButton)
pane.setBackground(Color.red);
else if (source==greenButton)
pane.setBackground(Color.green);
else pane.setBackground(Color.blue);

}

public static void main (String[] args){
ButtonActionEventv2 apps = new ButtonActionEventv2();

}
}

AddThis