Credits

Tuesday, August 31, 2010

More Action Events in Java

When we make a business application, it is only typical that we get messages from certain actions like a  login event.

Below is another program with action events that allow us to have a login form which requires a password and username. A valid entry of "STI" will allow you to seen a welcome message otherwise you will see a deny form.

The program makes use of string function equals ( ) to validate the string input.

[+/-] show/hide



/*adding of components to frame without a panel*/
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.*;
public class GUILoginEvent extends JFrame implements ActionListener{

JLabel loginLbl= new JLabel ("Login ");
JLabel pwLbl= new JLabel ("Password");
JTextField loginField=new JTextField(15);
JTextField pwField = new JTextField(15);

JButton loginBtn = new JButton("Login");
JButton cancelBtn = new JButton("Cancel");


public GUILoginEvent(){
super("Login Form");
setSize(280,180);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

FlowLayout flo=new FlowLayout();
loginBtn.addActionListener(this);
cancelBtn.addActionListener(this);
setLayout(flo);
add(loginLbl);

add(loginField);
add(pwLbl);

add(pwField);
add(loginBtn);
add(cancelBtn);
setVisible(true);
}

public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
boolean flag = false;
if (source==loginBtn)
{if (loginField.getText().equals("STI") && pwField.getText().equals("STI"))
flag = true;
msgForm myMessage = new msgForm(flag);}

else if (source==cancelBtn)
System.exit(0);


}

public static void main (String args[]){
GUILoginEvent myFrame=new GUILoginEvent();
}

}

class msgForm extends JFrame {
JLabel msg = new JLabel(" ",JLabel.CENTER);


public msgForm(boolean myflag){
super("Details");
setSize(200,100);

FlowLayout xflo=new FlowLayout();
if (myflag==true)
msg.setText("Welcome!");
else
msg.setText("Invalid login/password.");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
add(msg);
setVisible(true);

}
}

AddThis