Modal Box

Swing in Java

Swing is the mostly used for GUI Application development in java. Swing controls such as JButton , JLabel, JTextField, JComboBox, JTable etc are platform independent and lightweight.

To use swing, javax.swing package is need to be imported and main method is used as in traditional java programs. Container window like JFrame, JPanel etc  may be used to add swing controls.

Example to create a GUI based JFrame as login Form

import javax.swing.*; 
public class LoginForm extends JFrame
{
 LoginForm()
 { 
   setLayout(new Flowlayout()); 
   JLabel l1= new JLabel("LOGIN FORM");
   JLabel l2= new JLabel("User Name");
   JLabel l3= new JLabel("Password");
   JTextField t1= new JTextField(10);
   JPasswordField pass= new JPasswordField(10);
   JButton b1=new JButton("Ok");
   JButton b2=new JButton("Cancel");
   
add(l1); add(l2); add(t1); add(l3); add(pass); add(b1); add(b2); // you can setLayout(null) and then setBounds() method can be call to set the positions. }
public static void main(String[] args) { LoginForm frm=new LoginForm(); frm.setVisible(true); frm.setSize(400,500); } }

Java Program example on JComboBox to display the selected value in text field.

import javax.swing.*; 
import java.awt.event.*;
public class ComboExample extends JFrame implements ItemListener
{
  JTextField t1;
  JComboBox jc1;

ComboExample() { setLayout(new Flowlayout()); JLabel l1= new JLabel("City"); t1= new JTextField(10); jc1= new JComboBox();
jc1.addItem("delhi"); jc1.addItem("mumbai"); jc1.addItem("chennai"); jc1.addItem("kolkata");
add(l1); add(jc1); add(t1); jc1.addItemListener(this); }
public void itemStateChanged(ItemEvent ae) { String city=(String)jc1.getSelectedItem(); t1.setText(city); }
public static void main(String[] args) { ComboExample frm=new ComboExample(); frm.setVisible(true); frm.setSize(400,500); } }

Simlilarly, JTable may be used to display data in the form of rows and columns.

Video/ C Introduction

Watch video in full size
Wordpress Social Share Plugin powered by Ultimatelysocial