Credits

Sunday, August 29, 2010

Calling Java's GUI Frames

Java can call several frames and by creating an instance of these  frames, we can call and even pass parameters for a more interactive system. An action  event on the button invokes the action method to display the second frame.

The program below illustrates the use of these frames and directly adding of components to the frame.

[+/-] show/hide


/*adding of components to frame without a panel*/
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.*;
public class GUIEventSeatWork extends JFrame implements ActionListener{
JLabel toLabel= new JLabel("To : ",SwingConstants.LEFT);
JLabel fromLabel= new JLabel ("From:",SwingConstants.LEFT);
JLabel messageLabel = new JLabel (" Message:",JLabel.LEFT);
JTextField toField=new JTextField(15);
JTextField fromField = new JTextField(15);
JTextArea msgArea= new JTextArea(4,15);
JButton send = new JButton("Send");

public GUIEventSeatWork(){
super("Email Form");
setSize(220,280);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
msgArea.setLineWrap(true);
msgArea.setWrapStyleWord(true);
JScrollPane scrollpane=new JScrollPane(msgArea);
FlowLayout flo=new FlowLayout();
send.addActionListener(this);
setLayout(flo);
add(toLabel);
add(toField);
add(fromLabel);
add(fromField);
add(messageLabel);
add(scrollpane);
add(send);
setVisible(true);
}

public void actionPerformed(ActionEvent evt) {
String toName=toField.getText();
String fromName=fromField.getText();
String msgText=msgArea.getText();
msgForm myMessage = new msgForm(toName,fromName,msgText);
myMessage.setVisible(true);

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

class msgForm extends JFrame {
JLabel to = new JLabel();
JLabel from = new JLabel();
JTextArea msg = new JTextArea();
JPanel msgpane= new JPanel();
public msgForm(String toLbl,String fromLbl,String msgTxt){
super("Details");
setSize(150,200);
FlowLayout xflo=new FlowLayout();
msgpane.setLayout(xflo);

setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
to.setText ("\nTo : "+toLbl);
from.setText("\nFrom : "+fromLbl);
msg.setText ("\nMessage: "+msgTxt);

msgpane.add(to);
msgpane.add(from);
msgpane.add(msg);
add(msgpane);

}
}

AddThis