Wednesday, April 28, 2010

week 11

today's material :
- event listener
listener is needed to make a button do something when clicked
using method addActionListener

here's the code...
learn from this and the java api...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class EventListener extends JFrame implements ActionListener{

JButton ok;
JButton cancel;
JButton add;
JTextField text;
JTextArea area;
String content;

public EventListener(){
setSize(640, 480);
setTitle("Simple Frame");
setDefaultCloseOperation(EXIT_ON_CLOSE);

setVisible(true);

ok = new JButton("OK");
ok.addActionListener(this);

cancel = new JButton("Cancel");
cancel.addActionListener(this);

add = new JButton("Add to List");
add.addActionListener(this);

text = new JTextField(15);
area = new JTextArea();

JPanel pnlSouth = new JPanel(new GridLayout(2, 1));
JPanel pnlNorth = new JPanel(new FlowLayout());

JPanel pnl1 = new JPanel(new FlowLayout());
JPanel pnl2 = new JPanel(new FlowLayout());

pnlNorth.add(new Label("Customer List"));
pnlNorth.setBackground(Color.LIGHT_GRAY);

pnlSouth.add(pnl1);
pnlSouth.add(pnl2);
pnlSouth.setBackground(Color.LIGHT_GRAY);

pnl1.add(text);
pnl1.add(add);

pnl2.add(ok);
pnl2.add(cancel);

getContentPane().add(pnlNorth , BorderLayout.NORTH);
getContentPane().add(pnlSouth , BorderLayout.SOUTH);
getContentPane().add(area);
}


public static void main(String[] args) {
EventListener frame = new EventListener();
}

public void actionPerformed(ActionEvent e) {
if(e.getSource() == ok){
JOptionPane.showMessageDialog(this, "Button OK Clicked");
}
if(e.getSource() == cancel){
JOptionPane.showMessageDialog(this, "Button Cancel Clicked");
}
if(e.getSource() == add){
content = content + "\n" + text.getText();
area.setText(content);
}
}
}


thats all..............

No comments:

Post a Comment