Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Swing and GUI Components

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Swing

Swing and GUI components


Creation of user-interface screen is an important feature of any
modern computer language.Initially java introduced a package called
abstract window tool kit. This package contains a large no of classes &
interface that supported the creation of GUI components on user interface
screens. As the goal of java developers was to create platform independent
program athe AWT classes made use of the native methods of the resply.
Machines. That is the AWT made use of graphical methods defined for
windows OS for windows machine & graphical method defined for MAC OS for
macintosh machines. As a result, the appearance of the screen was different
for different platform. Therefore to have the same appearance of the screen
called pluggable look & feel in all platform new classes were added in java.
These are packed in swing java2 contains swing. The swing classes are part
of java foundation classes. The swing classes are contained in java extension
package called javax.
The methods in the swing classes do not use the graphical methods
directly, but use them as interface. Methods in swing classes are pure java.
It can be used to create screens with same look & feel of the screens in
different platforms. The methods in swing class are far superior than those in
AWT classes.
The swing classes are subclasses if the java.awt.container and
java.awt.component. The name of swing class starts with letter J. The top
level class of swing is JComponent. GUI components likes button, label ,
checkbox, panel ,text etc. are handled in jcomponent class. This component
can be added on a panel window or a frame window. The frame in swing is
handled in JFrame class. The jcomponent class and AWT class hierarchy is
shown in fig below

object

Java.awt.component

Java.awt.container

Jcomponent Window

Frame

JFrame

Sweety Batavia Page 1


Swing

JComponent
The Jcomponent class is a subclass of container. This class contains a
large no. of subclasses which define components like JButton , JTable.

Jcomponent
Abstract button

JButton
JMenuItem
JToggleButton
JCheckbox
JRadioButton
JComboBox
JInternalFrame
JLabel
JLayeredPane
JList
JMenuBar
JOptionPane
JPanel
JPopupMenu
JProgressBar
JScrollPane
JSeparator
JSlider
JTable
JTableHeader
JTextComponent
JTextArea
JTextField
JPasswordField
JToolBar
JToolTip
JTree

Creating window in Swing


Aconvenient window is created in swing in a top level window. Top
level window is supported by JFrame, JApplet, JDialog & JWindow classes.

Sweety Batavia Page 2


Swing

They are called root containers. These have several panes , JRootPane,
JMenuBar, JLayeredPane , ContentPane and GlassPane.

The most frequently used method to get the content pane is

getContentPane() ---- Returns a container object.

In swing, user interface component like button,checkbox and serring layout


managers must be done on a conterntpane. The components are added to
the contentpane using add() method.

To create a user interface window following steps are to be followed.

• Create a root container using jframe or japplet or jdialog or jwindow


• Get the container using the getContentPane method
• Create components
• Attach the components to a container using add() method

Creating JFrame Window


It is a standard style window. JFrame is a subclass of Frame class. When a
JFrame window is created its size is(0,0) and is invisible.

Constructors of JFrame
• JFrame() -- Creates an invisible window without title
• JFrame(String title) -- Creates an invisible window with a title given by
string title.

Methods in JFrame
• String getTitle() -- Returns a string representing a title of the frame
• void setTitle(String title) -- sets the title of the frame to this string
• void setVisible(Boolean b) -- shows or hides this frame window if b is
true, it shows the window otherwise it hides it.
• void setSize(int width, int height) -- sets the size of the window to the
specified width and height in pixels.
• void setLayout(LayoutManager mgi) -- sets the layout manager for
container
• int getX() -- returns the x component of window
• int getY() -- returns the y component of window
• void setLocation(int x,int y) -- moves the frame window to a new
location on the screen , the top left corner is specified by x and y
• int getHeight() -- returns the current height of the window
• int getWidth() -- returns the current width of the window

Once a JFrame window is created there is no way to close it. The


simplest way is to press ctrl + c in DOS Mode to close the window. The
other way is to capture the windowclosing event , through
windowListener and call system.exit().

Example -- The program creates a blank JFrame window

Sweety Batavia Page 3


Swing

import javax.swing.*;
public class frameex extends JFrame
{
public static void main(String a[])
{
JFrame f = new JFrame("My Frame");
f.setSize(300,300);
f.setVisible(true);
}
}

JFrame generates the window events and these events are handeled in
java.awt.event package

WindowListener interface is having following methods

• voidwindowActivated(WindowEvent we)
• voidwindowClosed(WindowEvent we)
• voidwindowClosing(WindowEvent we)
• voidwindowDeactivated(WindowEvent we)
• voidwindowDeiconified(WindowEvent we)
• voidwindowIconified(WindowEvent we)
• voidwindowOpened(WindowEvent we)

example demonstrating the use of windowclosing method to close


window

frame1.java

import javax.swing.*;
import java.awt.event.*;
public class frame1 extends JFrame implements WindowListener
{
frame1(String a)
{
setTitle(a);
addWindowListener(this);
}
public void windowActivated(WindowEvent e)
{ }
public void windowOpened(WindowEvent e)
{ }
public void windowIconified(WindowEvent e)
{ }
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowClosed(WindowEvent e)
{ }

Sweety Batavia Page 4


Swing

public void windowDeiconified(WindowEvent e)


{ }
public void windowDeactivated(WindowEvent e)
{ }
}

frameevent.java

public class frameevent


{
public static void main(String a[])
{
frame1 f = new frame1("My Frame");
f.setSize(300,300);
f.setVisible(true);
}
}

here we have to define all the methods that is defined in windowListener


interface. It we want to define only selected method then we can use
windowAdapter Class

Example --- Frame1adap.java


import javax.swing.*;
import java.awt.event.*;
public class frame1adap extends JFrame
{
frame1adap(String a)
{
setTitle(a);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}

frameevent1.java
public class frameevent1
{
public static void main(String a[])
{
frame1adap f = new frame1adap("My Frame");
f.setSize(300,300);
f.setVisible(true);
}
}

Sweety Batavia Page 5


Swing

Another way of closing the window is with use of setDefaultCloseOperation()

f. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

JLabel
The JLabel class is a subclass of JComponent. A JLabel object is a compone
for placing text or an icon or both. A JLabel displays a single line of read only
text in a container. The text can be changed by the application and not by
user.

It has the following int typeconstants that indicate the alignment of the label
content.
JLabel.CENTER JLabel.RIGHT JLabel.TOP
JLabel.LEFT JLabel.BOTTOM

Creating JLabel
Constructors
• JLabel() --- Creates an empty label
• JLabel(String s) --- Creates a label with specified string
• JLabel(String s, int alignment) --- creates a label with specified string
and with specified alignment
• JLabel(Icon i) --- creates a label using icon
• JLabel(Icon I, int alignment) --- creates a label using icon and
specified alignment
• JLabel(String s,Icon I, int alignment) --- creates a label using icon
and specified alignment and label is set to specified string

Methods
• Icon getIcon() -- returns the icon of the label
• String getText() -- returns the text
• void setFont(Font f) -- sets the font of the label

Example iconex.java
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class iconex extends JFrame
{
Container c;
iconex(String s)
{
setTitle(s);
c=getContentPane();
c.setLayout(new FlowLayout());
JLabel l1= new JLabel("hi");
JLabel l2= new JLabel("bye",JLabel.RIGHT);
Icon i= new ImageIcon("c:\fruit.jpg");
JLabel l3= new JLabel("fruits",i,JLabel.LEFT);

Sweety Batavia Page 6


Swing

c.add(l1);
c.add(l2);
c.add(l3);

}
public static void main(String a[])
{
JFrame f = new JFrame("My Frame");
f.setSize(300,300);
f.setVisible(true);
}
}

labelapplet.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/*
<applet code="labelapplet" height = 300 width=300>
</applet>
*/
public class labelapplet extends JApplet
{
JLabel l1;
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
l1=new JLabel("Welcome");
c.add(l1);
}
}

JButton
JButton is a concrete subclass of AbstractButton which is a subclass of
JComponent. When a button is clicked an ActionEvent is created. If an
application want to perform some action when button is clicked, it should
implement the interface ActionListener and register the listener receive
events from the button. One of the advanced features of JButton is that an
image can be used as button
Constructors
• JButton -- Creates a button with no label
• JButton(String s) -- creates a button with specified string s as a label
• JButton(Icon i) -- creates a button with the icon I as button
• JButton(String s, Icon i) -- creates a button with icon I as button and s
as the label

Methods

Sweety Batavia Page 7


Swing

• void setText(String label) -- sets the buttons label to the specified string
• String getText() -- returns the label of the button
• void setIcon(Icon i) --
• Icon getIcon() -- returns the icon of the label
• void addActionListener(ActionEvent ae) -- add the specified action
listener to receive action from button

Methods defined in ActionEvent class


• String getActionCommand() -- returns the command name for invoking
ActionEvent object.

Methods in ActionListener Interface


• String actionPerformed(ActionEvent ae) -- this method is executed when
button click event is generated

Example simple frame that having one button and one label when button is
clicked “bye” is displayed on label

Label2.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class label2 extends JFrame implements ActionListener


{
JButton b1;
JLabel l1;
Container c;
label2(String s)
{
c=getContentPane();
c.setLayout(new FlowLayout());
setTitle(s);
b1= new JButton("click");
l1=new JLabel("hi");
b1.addActionListener(this);
c.add(b1);
c.add(l1);
}
public void actionPerformed(ActionEvent ae)
{
l1.setText("bye");
}
}

buttonex.java
public class buttonex
{
public static void main(String a[])
{
Sweety Batavia Page 8
Swing

label2 f= new label2("Labeleg");


f.setSize(300,300);
f.setVisible(true);
}
}

Creating JButton on JApplet with icon


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="buttonapplet" height = 300 width=300>
</applet>
*/
public class buttonapplet extends JApplet implements ActionListener
{
JButton b1;
Icon I;
JLabel l1;
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
l1=new JLabel("Welcome");
i=new ImageICon(“c:\fruits.jpg”);
b1=new JButton(“click”);
c.add(l1);
c.add(b1);
}
public void actionPerformed(ActionEvent ae)
{
l1.setText("bye");
}
}

Example -- the frame contains two buttons an done label when button is
pressed label displays the string associated with button. The
getActionCommand() is called to obtain the string of pressed button
Labelbutton.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class labelbutton extends JFrame implements ActionListener


{
JButton b1,b2;
JLabel l1;
Container c;
labelbutton(String s)
{

Sweety Batavia Page 9


Swing

c=getContentPane();
c.setLayout(new FlowLayout());
setTitle(s);
b1= new JButton("HI..");
b2= new JButton("bye...");
l1=new JLabel();
b1.addActionListener(this);
b2.addActionListener(this);
c.add(b1);
c.add(b2);
c.add(l1);
}
public void actionPerformed(ActionEvent ae)
{
l1.setText(ae.getActionCommand());
}
}
labelbutton2.java
public class labelbutton2
{

public static void main(String a[])


{
labelbutton f= new labelbutton("Labeleg");
f.setSize(300,300);
f.setVisible(true);
}
}

JTextField
The simple type texts are dealt by JTextField , JPasswordField , JTextArea
class. The styled texts are handled in JEditorPane and JTextPane class
JTextfield is a subclass of JText Component which is a subclass of
JComponent. The alignment of the text is defined by the following int type
constants
JTextField.LEFT , JTextField.CENTER , JTextField.RIGHT

Constructors
• JTextField() -- creates a new text field the text is set to null and the no.
of columns is set to 0
• JTextField(String t) -- creates a new text field with the specified string
as the text
• JTextField(int columns) -- creates a new text field the text is set to null
and the no. of columns is set to specified int value
• JTextField(String text , int column ) -- creates a new text field with
specified string as the text with a width to display the specified no. of
columns.

Methods

Sweety Batavia Page 10


Swing

• void addActionListener(ActionEvent e) -- adds the action listenet to


receive action events from this textfield
• int getColumns() -- Returns the no of columns set for this textfield
• void setColumns(int c) --
• String getText() -- Returns the text contained in this textfield
• void setText(String s) --

the events related with JTextField


1. Actionevent
2. Keyevent

ActionEvent
In the textfield after filling in the entries the return key is to be pressed.
Pressing of the enter key generates actionEvent and ActionEvent is managed
by actionListener

Methods in actionListenet Interface


• void actionPerformed(ActionEvent ae)

Example -- String entered in textfield is displayed in the label


Textfieldeg.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class textfieldeg extends JFrame implements ActionListener


{
JTextField t1;
JLabel l1;
textfieldeg()
{
Container c= getContentPane();
c.setLayout(new FlowLayout());
t1=new JTextField(10);
t1.addActionListener(this);
c.add(t1);
l1=new JLabel();
c.add(l1);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
l1.setText(t1.getText());
}

Sweety Batavia Page 11


Swing

textfieldeg2.java
public class textfieldeg2
{
public static void main(String a[])
{
textfieldeg f = new textfieldeg();
f.setSize(300,300);
f.setVisible(true);
}
}

KeyEvent
It is generated when a key is pressed , typed or released. The key typed
event is generated only when a character is generated. Pressing alt+key do
not produce a character.
Some virtual key constants
VK_ENTER VK_CANCEL VK_CONTROL VK_SPACE
VK_BACK_SPACE VK_CLEAR VK_SHIFT VK_ESCAPE
VK_CAPS_LOCK VK_PAGE_UP VK_PAGE_DOWN VK_LEFT
VK_UP VK_DOWN VK_RIGHT VK_COMMA
VK_DELETE VK_F1 to VK_F12

Methods in KeyEvent class


• Char getKeyChar() -- returns the Unicode char for this key event if no
valid Unicode char is defined for this then the char generated is
CHAR_UNDEFINED
• boolean isActionKey() -- returns true if the key is action key
• int getKeyCode() -- returns the integer code for an actual key on the
keyboard means if enter is pressed then it returns 10 i.e ascii code

Methods in KeyListener Interface


void keyPressed(KeyEvent e)
void keyReleased(KeyEvent e)
void keyTyped(KeyEvent e)
Example to demonstrate that whatever char are pressed it is displayed on
the label
textfiledeg1.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class textfiledeg1 extends JFrame implements KeyListener


{
JTextField t1;
JLabel l1;
textfiledeg1()
{
Container c= getContentPane();
Sweety Batavia Page 12
Swing

c.setLayout(new FlowLayout());
t1=new JTextField(10);
t1.addKeyListener(this);
c.add(t1);
l1=new JLabel();
c.add(l1);
}
public void keyTyped(KeyEvent e)
{
char ch = e.getKeyChar();
String s;
s=t1.getText()+ch;
l1.setText(s);
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==e.VK_SPACE)
l1.setText(l1.getText()+ "space");
}
public void keyReleased(KeyEvent e)
{ }
}

textfieldeg4.java
public class textfieldeg4
{
public static void main(String a[])
{
textfiledeg1 f = new textfiledeg1();
f.setSize(300,300);
f.setVisible(true);
}
}

Creating JTextField on JApplet

textfieldapplet.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="textfieldapplet" width=300 height=300>
</applet>
*/
public class textfieldapplet extends JApplet implements ActionListener
{
JTextField t1;
JLabel l1;
public void init()
{

Sweety Batavia Page 13


Swing

Container c=getContentPane();
c.setLayout(new FlowLayout());
t1=new JTextField(10);
t1.addActionListener(this);
l1=new JLabel();
c.add(t1);
c.add(l1);
}
public void actionPerformed(ActionEvent ae)
{
l1.setText(t1.getText());
}
}

JPasswordField
It creates display similar to JTextField. The only difference is that when text
is displayed the actual char are replaced by *. It is subclass of
JTextComponent

Constructors
• JPasswordField() -- creates a new empty password field
• JTextField(String t) -- creates a new password field with the specified
string as the text
• JTextField(int columns) -- creates a new password field the text is set to
null and the no. of columns is set to specified int value
• JTextField(String text , int column ) -- creates a new password field with
specified string as the text with a width to display the specified no. of
columns.

Methods
• void setEchochar(char c) -- sets the specified character as echo
character for this field
• char getEchochar() -- Returns the echo character set for this field

Example shows how to create PasswordField in JFrame when user enter key
it will be displayed in label
passwordeg1.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class passwordeg1 extends JFrame implements ActionListener


{
JPasswordField t1;
JLabel l1;
passwordeg1()
{
Container c= getContentPane();
c.setLayout(new FlowLayout());
t1=new JPasswordField(10);
Sweety Batavia Page 14
Swing

t1.addActionListener(this);
c.add(t1);
l1=new JLabel();
c.add(l1);
}
public void actionPerformed(ActionEvent ae)
{
l1.setText(t1.getText());
}
}
passwordeg2.java
public class passwordeg2
{
public static void main(String a[])
{
passwordeg1 f = new passwordeg1();
f.setSize(300,300);
f.setVisible(true);
}
}
note: keyevents are same as in JTextField

JCheckBox
JcheckBox is a subclass of JToggleButton which is again a subclass of
AbstractButto. A chechbox is a two state graphical component that will be in
either selected or in deselected state
A checkbox when clicked generates the following events
1. ActionEvent
2. ChangeEvent
3. ItemEvent

Constructors
• JCheckBox() -- creates a checkbox with a blank label the checkbox is set
to deselected state
• JCheckBox(Icon i) -- creates a checkbox using the specified icon and is
set to deselected state
• JCheckBox(Icon I, Boolean state) -- creates a checkbox using the
specified icon and state
• JCheckBox(String s) -- creates the checkbox with the label set to s and
is set to deselected state
• JCheckBox(String s, Boolean state) --
• JCheckBox(String s, icon i) --
• JCheckBox(String s,icon I , Boolean state) --

Methods
• String getText() -- Returns the text contained in this checkbox
• void setText(String s) --
• Icon getIcon() -- returns the icon of the checkbox
• void setSelected(Boolean state) -- sets the checkbox to specified state
• boolean isSelected() -- returns the state of the checkbox
Sweety Batavia Page 15
Swing

Example program to create a checkbox and add on JFrame 3 checkbox and


one label is there label displays the text of selected checkbox using the
actionevent
checkbox1.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class checkbox1 extends JFrame implements ActionListener


{
JCheckBox c1,c2,c3;
JLabel l1;
checkbox1()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
c1=new JCheckBox("First");
c1.addActionListener(this);
c.add(c1);
c2=new JCheckBox("Second");
c2.addActionListener(this);
c.add(c2);
c3=new JCheckBox("Third");
c3.addActionListener(this);
c.add(c3);
l1=new JLabel();
c.add(l1);
}
public void actionPerformed(ActionEvent e)
{
if(c1.isSelected()==true)
l1.setText(l1.getText()+c1.getText());
if(c2.isSelected()==true)
l1.setText(l1.getText()+c2.getText());
if(c3.isSelected()==true)
l1.setText(l1.getText()+c3.getText());
}
}
checkbox2.java
public class checkbox2
{
public static void main(String a[])
{
checkbox1 f = new checkbox1();
f.setSize(300,300);
f.setVisible(true);
}
}

Sweety Batavia Page 16


Swing

JRadioButton
JRadioButton are like Jcheckbox. It is used to represent a collection of
mutually exclusive options i.e out of several options only one will be in
selected state and all the remaining are in deselected state. The radiobuttons
are created using jradiobutton class which is asubclass of jtogglebutton. The
jradiobutton must be placed in a button group the button group is created
using the buttongroupclass which has no argument constructor. After
creating jradiobutton it is to be added to he buttongroup using add()
method. Jradiobutton generates the following events
1. Actionevent
2. itemevent
3. changeevent

Constructors
• JRadioButton() -- creates a radiobutton without any label the
radiobutton is set to deselected state
• JRadioButton(Icon i) -- creates a radiobutton with icon i & radiobutton is
set to deselected state
• JRadioButton(Icon I ,Boolean state) -- creates a radiobutton with icon I
radiobutton is set to specified state
• JRadioButton(String s) -- creates a radiobutton with string as label and
radiobutton is set to deselected state
• JRadioButton(String s , Boolean state) -- creates a radiobutton with
string s and radiobutton is set to specified state
• JRadioButton(String s,Icon I) --
• JRadioButton(string s, Icon I ,Boolean state) --

Methods
All the methods are same as in JCheckBox

Example
When user checks any radiobutton its text is displayed in label

radiobutton.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class radiobutton extends JFrame implements ActionListener


{
JRadioButton r1,r2,r3;
JLabel l1;
radiobutton()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
r1=new JRadioButton("First");
r1.addActionListener(this);
Sweety Batavia Page 17
Swing

c.add(r1);
r2=new JRadioButton("Second");
r2.addActionListener(this);
c.add(r2);
r3=new JRadioButton("Third");
r3.addActionListener(this);
c.add(r3);
l1=new JLabel();
c.add(l1);
ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
bg.add(r3);
}
public void actionPerformed(ActionEvent e)
{
if(r1.isSelected()==true)
l1.setText(r1.getText());
if(r2.isSelected()==true)
l1.setText(r2.getText());
if(r3.isSelected()==true)
l1.setText(r3.getText());
}
}
radiobutton2.java
public class radiobutton2
{
public static void main(String a[])
{
radiobutton f = new radiobutton();
f.setSize(300,300);
f.setVisible(true);
}
}

ItemEvent
This event indicate that item like radiobutton is selected or deselected. Some
properties are as follows
1. DESELECTED indicates that item is deselected
2. SELECTED indicates that item is selected

Methods in ItemListener interface


void itemStateChanged(ItemEvent e)

Methods in ItemEvent class


itemSelectable getItemSelectable() -- returns the item selectable object
that originated the event

Example showing the use of item event class


radiobutton3.java
Sweety Batavia Page 18
Swing

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class radiobutton3 extends JFrame implements ItemListener


{
JRadioButton r1,r2,r3,r;
JLabel l1;
radiobutton3()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
r1=new JRadioButton("First");
r1.addItemListener(this);
c.add(r1);
r2=new JRadioButton("Second");
r2.addItemListener(this);
c.add(r2);
r3=new JRadioButton("Third");
r3.addItemListener(this);
c.add(r3);
l1=new JLabel();
c.add(l1);
ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
bg.add(r3);
}
public void itemStateChanged(ItemEvent e)
{
r=(JRadioButton) e.getItemSelectable();
l1.setText(r.getText());
}
}

radiobutton4.java
public class radiobutton4
{
public static void main(String a[])
{
radiobutton3 f = new radiobutton3();
f.setSize(300,300);
f.setVisible(true);
}
}

if in container jcheckbox & jradiobutton both are added and we want to


handle itemevent for both then how to know which component has generated
the event

Sweety Batavia Page 19


Swing

Example

radiobutton5.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class radiobutton5 extends JFrame implements ItemListener


{
JRadioButton r1,r2;
JCheckBox c1,c2;
JLabel l1;
radiobutton5()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
r1=new JRadioButton("First");
r1.addItemListener(this);
c.add(r1);
r2=new JRadioButton("Second");
r2.addItemListener(this);
c.add(r2);
c1=new JCheckBox("First checkbox");
c1.addItemListener(this);
c.add(c1);
c2=new JCheckBox("Second checkbox");
c2.addItemListener(this);
c.add(c2);
l1=new JLabel();
c.add(l1);
ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);

}
public void itemStateChanged(ItemEvent e)
{
String s=e.getSource().getClass().getName();
if(s=="javax.swing.JCheckBox")
{
JCheckBox c=(JCheckBox)e.getSource();
l1.setText(c.getText());
}
if(s=="javax.swing.JRadioButton")
{
JRadioButton r=(JRadioButton)
e.getItemSelectable();
l1.setText(r.getText());
}

Sweety Batavia Page 20


Swing

}
}

radiobutton6.java
public class radiobutton6
{
public static void main(String a[])
{
radiobutton5 f = new radiobutton5();
f.setSize(300,300);
f.setVisible(true);
}
}

JList
It is a subclass of Jcomponent. A list is used when the no. of items for
selection is large. Selection of an item is done by clicking on the item itself.
A swing list does not have a scrollbar to display the list list is to be placed
inside a JScrollPane() object.

Constructors
• JList() -- creates an empty list
• JList(Vector vec) -- creates a list with items specified in vector vec
• JList(object[] obj) -- creates a list with items specified in the object
array

Methods
• void setVisibleRowCount(int c) -- sets the no. of rows in the list to be
displayed. Default value is 8
• int getSelectedIndex() -- returns the index of the first selected item
• object getSelectedValue() -- returns the topmost selected item
• object[] getSelectedValues() -- returns the array of all selected items

Example in which when button is pressed all selected item is displayed in


label
list1.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class list1 extends JFrame implements ActionListener


{
JList j1;
JButton b1;
JLabel l1;
list1()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
String s[]= {"aaa","bbb","ccc","ddd","eee"};
Sweety Batavia Page 21
Swing

j1=new JList(s);
c.add(j1);
b1=new JButton("click");
b1.addActionListener(this);
c.add(b1);
l1=new JLabel();
c.add(l1);

}
public void actionPerformed(ActionEvent e)
{
l1.setText((String)j1.getSelectedValue());
}
}

lsit2.java
public class lsit2
{
public static void main(String a[])
{
list1 f = new list1();
f.setSize(300,300);
f.setVisible(true);
}
}

here we can get only one selected item we can select more than one item by
pressing ctrl key if we want to get all selected item then following change is
to be done
public void actionPerformed(ActionEvent e)
{
int sel[]=j1.getSelectedIndices();
for(int i=0;i<sel.length;i++)
{
l1.setText(l1.getText()+j1.getModel().getElementAt(sel[i]));
}
}

• SelectionMode property of JList


The constants shown below are used in conjunction with the
selectionmode property of the listselectionmodel interface
Constant used are as follows
• SINGLE_SELECTION -- user can select only one item at a time
• MULTIPLE_INTERVAL_SELECTION -- user can make selection of
multiple items.
Example -- lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
By default it is MULTIPLE_INTERVAL_SELECTION

DefaultListModel

Sweety Batavia Page 22


Swing

List created in JList by passing an array or vector do not have many


methods for manipulating the items in the list. These is no method in the
JList to add an item or remove an item in the list. The defaultlistmodel
which is a concrete subclass of abstractlistmodel has methods for adding
and removing items from the jlist this class implements an listmodel
interface

Steps
1. create an instance of defaultlistmodel
2. add items to this model
3. create jlist by passing this model as argument in the constructor

example
DefaultListModel m=new DefaultListModel();
m.addElement(“aa”);
m.addElement(“bb”);
JList l1 =new JList(m);

Methods
• void addElement(Object o) -- add the given object at end of list
• void clear() -- removes all the elements from thelist
• Object firstElement() -- returns the firstElement
• Object getElementAt() -- returns the list item at the specified index
• Int getSize() -- returns the no of items in the list
• void insertElementAt(Object o,int index) --
• boolean removeElement(Object o) -- removes the first occurrence of
the object in the list
• void removeElementAt(int index) -- removes the item at the specified
index in the list

Example

aaa add
bbb
ccc Add all
ddd

list3.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class list3 extends JFrame implements ActionListener


{
JList l1,l2;
JButton b1,b2;
DefaultListModel m1,m2;

list3()

Sweety Batavia Page 23


Swing

{
Container c=getContentPane();
c.setLayout(new FlowLayout());
m1=new DefaultListModel();
m1.addElement("aaa");
m1.addElement("bbb");
m1.addElement("ccc");
m1.addElement("ddd");
l1=new JList(m1);
m2=new DefaultListModel();
l2=new JList(m2);
c.add(l1);
c.add(l2);
b1=new JButton("Add");
b1.addActionListener(this);
c.add(b1);
b2=new JButton("Add All");
b2.addActionListener(this);
c.add(b2);

}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="Add")
{
int s[]=l1.getSelectedIndices();
String str[] =new String[10];
for(int i=0;i<s.length;i++)
{
m2.addElement(m1.getElementAt(s[0]));
str[i]=(String)m1.getElementAt(s[i]);
}
for(int i=0;i<str.length;i++)
{
m1.removeElement(str[i]);
}
}
if(e.getActionCommand()=="Add All")
{
for(int i=0;i<m1.getSize();i++)
{
m2.addElement(m1.getElementAt(i));
}
m1.clear();
}
}
}

list4.java
public class list4

Sweety Batavia Page 24


Swing

{
public static void main(String a[])
{
list3 f = new list3();
f.setSize(300,300);
f.setVisible(true);
}
}

ListSelectionListener Interface
List selectionEvent is defined in the javax.swing.event package

Methods
void valueChanged(ListSelectionEvent e) -- it is generated when selection
value is changed

Example
listselection.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

public class listselection extends JFrame implements ListSelectionListener


{
JList l1,l2;
JLabel lb;
listselection()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
String s[] = {"aaa","bbb","ccc","ddd"};
l1=new JList(s);
l1.addListSelectionListener(this);
c.add(l1);
lb=new JLabel();
c.add(lb);
}
public void valueChanged(ListSelectionEvent e)
{
l2=(JList)e.getSource();
lb.setText((String)l1.getSelectedValue());
}
}
listselection1.java
public class listselection1
{
public static void main(String a[])
{
listselection f = new listselection();
Sweety Batavia Page 25
Swing

f.setSize(300,300);
f.setVisible(true);
}
}

JComboBox
JComboBox is a subclass of JComponent. A combobox is a visual swing
graphical component that gives a popuplist when clicked. It is combination of
JList and JTextField. Only one item is visible at a time. A popupmenu displays
the choices a user can select from. In JList the items cannot be edited while
here it can be.

Constructors
• JComboBox() -- creates an empty ComboBox
• JComboBox (Vector vec) -- creates a ComboBox with items from
specified vector vec
• JComboBox (object[] obj) -- creates a ComboBox with items from
specified object array

Methods
• int getSelectedIndex() -- returns the index of the selected item
• object getSelectedItem() -- returns the currently selected item
• object[] getSelectedValues() -- returns the array of all selected items
• void addItem(Object o) -- add the given object at end of list
• Object getItemAt() -- returns the item at the specified index
• void removeItem(Object o) -- removes the specified item from the list
• void removeItemAt(int index) -- removes the item at the specified index
in the list
• int getItemCount() -- returns the no. of items in the list
• void removeAllItems() -- removes all items from the list

Example : when user clicks on any item in the combobox and press the
button display it is displayed in label.

combobox1.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class combobox1 extends JFrame implements ActionListener


{
JComboBox cb;
JButton b;
JLabel l;
combobox1()
{
Container c= getContentPane();
c.setLayout(new FlowLayout());
String s[] = {"aaa","bbb","ccc","ddd"};

Sweety Batavia Page 26


Swing

cb=new JComboBox(s);
c.add(cb);
b=new JButton("Display");
b.addActionListener(this);
c.add(b);
l=new JLabel();
c.add(l);
}
public void actionPerformed(ActionEvent e)
{
l.setText((String)cb.getSelectedItem());
}
}
combobox2.java
public class combobox2
{
public static void main(String a[])
{
combobox1 f = new combobox1();
f.setSize(300,300);
f.setVisible(true);
}
}

ItemEvent
Methods
• void itemStateChanged(ItemEvent e) -- whenever there is change of
state in the JCombobox this method is executed

Example when user selects any item immediately that item is displayed in
the label
combobox3.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class combobox3 extends JFrame implements ItemListener


{
JComboBox cb;
JLabel l;
combobox3()
{
Container c= getContentPane();
c.setLayout(new FlowLayout());
String s[] = {"aaa","bbb","ccc","ddd"};
cb=new JComboBox(s);
cb.addItemListener(this);
c.add(cb);
l=new JLabel();
c.add(l);
Sweety Batavia Page 27
Swing

}
public void itemStateChanged(ItemEvent e)
{
JComboBox d= (JComboBox)e.getSource();
l.setText((String)d.getSelectedItem());
}
}
combobox4.java
public class combobox4
{
public static void main(String a[])
{
combobox3 f = new combobox3();
f.setSize(300,300);
f.setVisible(true);
}
}

JScrollPane
JScrollPane is a subclass of JComponent. A JScrollPane is a visual component
that helps to scroll around a large sized item that is too big to be seen all at
once. JScrollPane provides a horizontal scrollbar and vertical scrollbar
automatically
There are 4 corners each corner is identified by the following int type
constants defined in the interface scrollpaneconstants

• ScrollPaneConstants.UPPER_LEFT_CORNER
• ScrollPaneConstants.UPPER_RIGHT_CORNER
• ScrollPaneConstants.LOWER_LEFT_CORNER
• ScrollPaneConstants.LOWER_RIGHT_CORNER

The top border is column header and left border is called row header the
right border represents an automatically adjustable vertical JScrollbar the
bottom border represents an automatically adjustable horizontal JScrollbar.
Whether a horizontal scrollbar is needed or not is defined by following
constants called HorizontalScrollbarPolicy
• ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
• ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
• ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER

Similarly verticalscrollbarPolicy can be defined. Both assume the first one by


default.
Constructors
• JScrollPane() -- creates a scrollpane without any component
• JScrollPane(int vconstant, int hconstant) -- creates a scrollpane with
scroll bar as specified in vconst and hconst
• JScrollPane(Component c) -- creates a scrollpane for specified
component
• JScrollPane(Component c, int vconst , int hconst) --

Sweety Batavia Page 28


Swing

Methods
• int getHorizontalScrollBarPolicy() -- returns the constant that tells the
whether the horizontal scrollbar will be displayed as needed always or
never.
• Int getVerticalScrollBarPolicy() --

Example sets the scrollbar around JList


scrollpane.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class scrollpane extends JFrame


{
scrollpane()
{
Container c= getContentPane();
c.setLayout(new FlowLayout());
String s[] = {"aaa","bbb","ccc","ddd","eee","fff","ggg",
"hhh","iii","jjj","kkk","lll","mmm"};
JList l = new JList(s);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(l,v,h);
c.add(jsp);
}
}
scrollpane1.java
public class scrollpane1
{
public static void main(String a[])
{
scrollpane f = new scrollpane();
f.setSize(300,300);
f.setVisible(true);
}
}

JMenuItem , JMenu , JMenuBar


A pulldown menu with several items can be created using Jmenuitem ,
Jmenu , JMenubar objects
A JMenu contains several JmenuItem by clicking menuitem , actions can be
initiated. AJMenuItem is like a button. A JMenuItem is to be attached to a
Jmenu object and this is to be attached to JMenuBar which is then attached
to JFrame or JApplet.
Steps
1. Create JMenuItem(many)
2. Create JMenu(many)
3. Create JMenuBar
4. Create JFrame or JApplet
Sweety Batavia Page 29
Swing

5. Add all JMenuitem to JMenu


6. add all JMenu to JMenuBar
7. Add JMenuBar to JFrame or JApplet

JMenuItem
It is part of JMenu display in window when a jmenu is clicked a popupmenu
appears displaying all menu items. Each menu item acts like a button by
clicking on it actions can be initiated.

Constructors
• JMenuItem() -- creates an empty menu item
• JMenuItem(Icon img) -- creates an menu item with a specified icon
• JMenuItem(String s) --
• JMenuItem(String s, Icon img) --

Methods
• void addActionListener(ActionEvent e) –
• String setText() --
• Icon getIcon() --

JMenu
It is a container for JMenuItem a menu can be attached with several
menuitems.

Constructors
• JMenu() -- creates an empty menu
• JMenu(String s) --

Methods
• void add(component c) –
• MenuItem add(JmenuItem m) --
• Int getItemCount() --
• Insert(JMenuItem m,int index) -- Inserts the specified menu item at the
specified index

JMenuBar

Constructors
• JMenuBar() --

Methods
• Add(Jmenu m) -- adds the specified item to the menubar
• Int getMenuCount() -- returnsthe no of items in the menubar

Example
menueg.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Sweety Batavia Page 30
Swing

public class menueg extends JFrame


{
JMenuItem ia,ib,ic,id;
JMenu col,font,red;
JMenuBar b;
menueg()
{
Container c= getContentPane();
c.setLayout(new FlowLayout());
ia = new JMenuItem("Dark red");
ib=new JMenuItem("Blue");
ic=new JMenuItem("aaa");
id=new JMenuItem("bbb");
red=new JMenu("red");
red.add(ia);
col=new JMenu("Color");
col.add(ia);
col.add(ib);
font = new JMenu("font");
font.add(ic);
font.add(id);
b=new JMenuBar();
b.add(col);
b.add(font);
c.add(b);
}
}
menueg1.java
public class menueg1
{
public static void main(String a[])
{
menueg f = new menueg();
f.setSize(300,300);
f.setVisible(true);

}
}
to perform some operations when menu item is clicked action event is used
to handle this
menueg2.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class menueg2 extends JFrame implements ActionListener


{
JMenuItem a,b,c,d;
JMenu font;

Sweety Batavia Page 31


Swing

JMenuBar mb;
JLabel l;
menueg2()
{
Container co= getContentPane();
co.setLayout(new FlowLayout());
a = new JMenuItem("aaaaaa");
b=new JMenuItem("bbbbbb");
c=new JMenuItem("cccccc");
d=new JMenuItem("dddddd");
font = new JMenu("font");
font.add(a);
font.add(b);
font.add(c);
font.add(d);
mb=new JMenuBar();
mb.add(font);
co.add(mb);
}
public void actionPerformed(ActionEvent e)
{
l.setText("aaaa");
}

}
menueg3.java
public class menueg3
{
public static void main(String a[])
{
menueg2 f = new menueg2();
f.setSize(300,300);
f.setVisible(true);

}
}
JTable
It is the component that displays the row and cols of data
Constructors
• JTable(Object data[][] , object colhead[]) -- here data is a2 dimensional
array of data that is to be displayed and col heads is a 1 dimensional
array with the column headings
tableeg.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class tableeg extends JFrame


{

Sweety Batavia Page 32


Swing

tableeg()
{
Container co= getContentPane();
co.setLayout(new FlowLayout());
String hd[] ={"Name","Per","Dept"};
String data[][]={ {"aaa","60","CE"},
{"bbb","70","CE"},
{"ccc","80","IT"}};
JTable t=new JTable(data,hd);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int
h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(t,v,h);
co.add(jsp);
}
}
tableeg1.java
public class tableeg1
{
public static void main(String a[])
{
tableeg f = new tableeg();
f.setSize(300,300);
f.setVisible(true);
}
}
JTree
It presents a hierarchial view of data. User has ability to expand or collapse
the data
Constructors
• JTree(DefaultMutableTreeNode t) --

Methods
• TreePath getPathForLocation(int x,int y) -- it will return the treepath of
node at specific location
How to create JTree
DefaultMutableTreeNode class is having add method that adds the child
node.

Example
treeeg.java
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;

public class treeeg extends JFrame


{
treeeg()
{
Sweety Batavia Page 33
Swing

Container co= getContentPane();


co.setLayout(new FlowLayout());
DefaultMutableTreeNode top = new
DefaultMutableTreeNode("Top");
DefaultMutableTreeNode a = new DefaultMutableTreeNode("a");
top.add(a);
DefaultMutableTreeNode a1 = new
DefaultMutableTreeNode("a1");
a.add(a1);
DefaultMutableTreeNode a2 = new
DefaultMutableTreeNode("a2");
a.add(a2);

DefaultMutableTreeNode b = new DefaultMutableTreeNode("b");


top.add(b);
DefaultMutableTreeNode b1 = new
DefaultMutableTreeNode("b1");
b.add(b1);
DefaultMutableTreeNode b2 = new
DefaultMutableTreeNode("b2");
b.add(b2);
JTree t= new JTree(top);
co.add(t);
}
}
treeeg1.java
public class treeeg1
{
public static void main(String a[])
{
treeeg f = new treeeg();
f.setSize(300,300);
f.setVisible(true);
}
}
to find which node is selected mouseclick is to be handled i.e if a1 is clicked it
is displayed in the label

treeeg2.java
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;

public class treeeg2 extends JFrame implements MouseListener


{
JLabel lab;
treeeg2()
{
Container co= getContentPane();

Sweety Batavia Page 34


Swing

co.setLayout(new FlowLayout());
DefaultMutableTreeNode top = new
DefaultMutableTreeNode("Top");
DefaultMutableTreeNode a = new DefaultMutableTreeNode("a");
top.add(a);
DefaultMutableTreeNode a1 = new
DefaultMutableTreeNode("a1");
a.add(a1);
DefaultMutableTreeNode a2 = new
DefaultMutableTreeNode("a2");
a.add(a2);

DefaultMutableTreeNode b = new DefaultMutableTreeNode("b");


top.add(b);
DefaultMutableTreeNode b1 = new
DefaultMutableTreeNode("b1");
b.add(b1);
DefaultMutableTreeNode b2 = new
DefaultMutableTreeNode("b2");
b.add(b2);
JTree t= new JTree(top);
t.addMouseListener(this);
co.add(t);
lab=new JLabel();
co.add(lab);
}
public void mouseClicked(MouseEvent e)
{
JTree tr=(JTree)e.getSource();
TreePath tp = tr.getPathForLocation(e.getX(),e.getY());
String snode=tp.getLastPathComponent().toString();
lab.setText(snode);
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}

}
treeeg3.java
public class treeeg3
{

Sweety Batavia Page 35


Swing

public static void main(String a[])


{
treeeg2 f = new treeeg2();
f.setSize(300,300);
f.setVisible(true);
}
}

here getLAstPAthComponent() method will return the name of node for which
we gettreepath

Sweety Batavia Page 36

You might also like