Credits

Saturday, May 14, 2011

Java's GUI - Event Driven Program

Any system must be,  first and foremost, dynamic, user-friendly, reliable and efficient and Java as a platform and language addresses these basic points.


Graphical User Interface or GUI allows the provision of GUI components like buttons, tables, text  fields to name a few to be responsive to user activity or actions. A typical user activity can be when we click on a login button or press ENTER key on a text field after we write our username and password.


The program below illustrates the use of event - handling methods that respond to button events.


[+/-] 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{
String name;
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;
name= loginField.getText();
if (source==loginBtn)
{if (loginField.getText().equals("STI") && pwField.getText().equals("STI"))
flag = true;
msgForm myMessage = new msgForm(flag,name);}

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, String xname) {
setSize(200,100);

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

}
}

AddThis