Credits

Sunday, August 29, 2010

Passing Parameters to Java Frames

Here is another sample program which I took and revised from the other post.  The program includes the use of flow layout for the container (frame or panel), so, components can be  equally centered   across the container.

This  program also passes through a parameter to another frame.
[+/-] show/hide



/*adding of components to frame without a panel*/
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.*;
public class GUIQuizEvent extends JFrame implements ActionListener{
// private LayoutManager FlowLayout;
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("Write your message here.",4,15);
JButton send = new JButton("Send");

public GUIQuizEvent(){
setSize(220,210);
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 recipient= toField.getText();
messageFrame secFrame=new messageFrame(recipient);
secFrame.setVisible(true);
}
public static void main (String args[]){
GUIQuizEvent myFrame=new GUIQuizEvent();
}
}

class messageFrame extends JFrame{
messageFrame(String To){
super("Confirmation Message");
setSize(250,100);
setLayout(new FlowLayout());
JLabel msg1= new JLabel("Your message to "+To);
JLabel msg2= new JLabel("was successfully sent.");
add(msg1);
add(msg2);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}}

AddThis