Thursday, September 9, 2010

Integration of Common GUI Java Components

GUI components like buttons, labels, text fields, radio buttons, check boxes, scrollpane and others can be all put to use.

A program below illustrates the use of commonly used components with item and action events to respond to combo box selection and a button click.

[+/-] show/hide


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

JLabel nameLabel= new JLabel("Name",SwingConstants.LEFT);
JLabel courseLabel= new JLabel ("Course:",SwingConstants.LEFT);
JLabel addressLabel= new JLabel ("Address:",SwingConstants.LEFT);
JLabel genderLabel= new JLabel ("Gender:",SwingConstants.LEFT);
JLabel statusLabel= new JLabel ("Civil Status:",SwingConstants.LEFT);
JTextArea addressArea = new JTextArea (2,15);
JTextField nameField=new JTextField(15);
JTextField courseField = new JTextField(15);
String[] status = {"Single","Widow","Married"};
JComboBox statusBox = new JComboBox(status);
JTextField statusField = new JTextField(8);
JRadioButton female = new JRadioButton("Female");
JRadioButton male = new JRadioButton("Male");
ButtonGroup gender = new ButtonGroup();

JButton save = new JButton("Save");
JButton cancel = new JButton("Cancel");

public GUIStudInfoQuiz(){

setSize(250,250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

FlowLayout flo=new FlowLayout();


setLayout(flo);
add(nameLabel);
add(nameField);
add(courseLabel);
add(courseField);
add(addressLabel);
add(addressArea);
add(genderLabel);
statusBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)statusBox.getSelectedItem();
statusField.setText(str);
}
});
add(statusBox);
add(statusField);
add(statusLabel);

add(male);
add(female);
gender.add(male);
gender.add(female);

save.addActionListener(this);
cancel.addActionListener(this);

add(save);
add(cancel);

setVisible(true);
}

public void actionPerformed(ActionEvent evt) {

Object source = evt.getSource();
if (source==save)
JOptionPane.showMessageDialog(null,"File saved.");
else
System.exit(0);


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

No comments:

AddThis