0% found this document useful (0 votes)
3 views

Java Swing

Java Swing is a part of Java Foundation Classes used for creating window-based applications, built on top of AWT and providing lightweight, platform-independent components. It includes various classes such as JButton, JTextField, and JRadioButton, and supports features like pluggable look and feel and MVC architecture. The document also provides examples of using different Swing components, including buttons, labels, text fields, and more, along with their respective code implementations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Swing

Java Swing is a part of Java Foundation Classes used for creating window-based applications, built on top of AWT and providing lightweight, platform-independent components. It includes various classes such as JButton, JTextField, and JRadioButton, and supports features like pluggable look and feel and MVC architecture. The document also provides examples of using different Swing components, including buttons, labels, text fields, and more, along with their respective code implementations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

pJava Swing

1. Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used
to create window-based applications.

2. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.

3. Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as
 JButton
 JTextField
 JTextArea
 JRadioButton
 JCheckbox
 JMenu
 JColorChooser

No. Java AWT Java Swing

1 AWT components are platform- Java swing components


) dependent. are platform-independent.

2 AWT components are heavyweight. Swing components


) are lightweight.

3 AWT doesn't support pluggable Swing supports pluggable


) look and feel. look and feel.

4 AWT provides less components than Swing provides more


) Swing. powerful components such
as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.

1
5 AWT doesn't follows MVC(Model Swing follows MVC.
) View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.

Hierarchy of Java Swing classes

Simple Java Swing Example

File: FirstSwingExample.java

import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{

2
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

Java JButton

 The JButton class is used to create a labeled button that has platform
independent implementation.

 The application result in some action when the button is pushed. It inherits
AbstractButton class.

Java JButton Example

import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args)
{

3
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Example of displaying image on the button:


import javax.swing.*;
public class ButtonExample
{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
4
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new ButtonExample();
}
}

Output:

Java JLabel

 The object of JLabel class is a component for placing text in a container. It is


used to display a single line of read only text.

 The text can be changed by an application but a user cannot edit it directly.
It inherits JComponent class.

Java JLabel Example


import javax.swing.*;
class LabelExample
{
public static void main(String args[])

5
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Java JTextField

 The object of a JTextField class is a text component that allows the editing
of a single line text. It inherits JTextComponent class.

Java JTextField Example


import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])

6
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
} Output:

Java JPasswordField

 The object of a JPasswordField class is a text component specialized for


password entry. It allows the editing of a single line of text. It inherits
JTextField class.

Java JPasswordField Example


import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
7
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
}

Output:

APPLICATION 1 : CALCULATOR

import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();

8
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}

9
Output:

APPLICATION – 2 LOGIN FORM

import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
final JLabel label = new JLabel();
label.setBounds(20,150, 200,50);
final JPasswordField value = new JPasswordField();
value.setBounds(100,75,100,30);
JLabel l1=new JLabel("Username:");
l1.setBounds(20,20, 80,30);
JLabel l2=new JLabel("Password:");
l2.setBounds(20,75, 80,30);
JButton b = new JButton("Login");
b.setBounds(100,120, 80,30);
final JTextField text = new JTextField();

10
text.setBounds(100,20, 100,30);
f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username " + text.getText();
data += ", Password: "
+ new String(value.getPassword());
label.setText(data);
}
}); }
} Output:

Java JCheckBox

 The JCheckBox class is used to create a checkbox. It is used to turn an


option on (true) or off (false).
 Clicking on a CheckBox changes its state from "on" to "off" or from "off" to
"on ".
 It inherits JToggleButton class.

Java JCheckBox Example


import javax.swing.*;

11
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}

Output:

Java JRadioButton

12
 The JRadioButton class is used to create a radio button. It is used to
choose one option from multiple options. It is widely used in exam
systems or quiz.
 It should be added in ButtonGroup to select one radio button only.

Java JRadioButton Example


import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}

Output:

13
Java JComboBox

Java JComboBox Example


import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

Output:

14
Java JScrollBar Example
import javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollBarExample();
}}

Output:

15
Java JPopupMenu Example
import javax.swing.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final JFrame f= new JFrame("PopupMenu Example");
final JPopupMenu popupmenu = new JPopupMenu("Edit");
JMenuItem cut = new JMenuItem("Cut");
JMenuItem copy = new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);

f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);
f.setSize(300,300);
f.setLayout(null);
16
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}}

Output:

Java JPanel Example


import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{

17
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}

Output:

18
Java JTable

Java JTable Example


import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}

19
public static void main(String[] args) {
new TableExample();
}
}

Output:

Java JTree

 The JTree class is used to display the tree structured data or hierarchical
data. JTree is a complex component.

 It has a 'root node' at the top most which is a parent for all nodes in the tree.
It inherits JComponent class.

Java JTree Example


import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
20
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true); }
public static void main(String[] args) {
new TreeExample(); }}

Output:

Java JTabbedPane

 The JTabbedPane class is used to switch between a group of components by


clicking on a tab with a given title or icon. It inherits JComponent class.

Java JTabbedPane Example


import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){

21
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}

Output:

22
Java JScrollPane

 A JscrollPane is used to make scrollable view of a component.


 When screen size is limited, we use a scroll pane to display a large
component or a component whose size can change dynamically.

JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Scroll Pane Example");
// Display the window.
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
23
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZ
ONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICA
L_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Output:

APPLICATION 3 : REGISTRATION FORM

24
Create a Registration form using Swing.

import java.awt.Button;
import java.awt.GridLayout;
import java.awt.TextArea;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class SwingEx extends JFrame
{
SwingEx()
{
JPanel p = new JPanel();
setSize(300,300);
add(p);
p.setSize(300, 300);
p.setLayout(new GridLayout(7,2));
JLabel nameLabel = new JLabel();
nameLabel.setText("Name");
p.add(nameLabel);
JTextField nameText = new JTextField();
p.add(nameText);
JLabel fatherLabel = new JLabel();

25
fatherLabel.setText("Fathers Name");
p.add(fatherLabel);
JTextField fatherText = new JTextField();
p.add(fatherText);
JLabel genderLabel = new JLabel();
genderLabel.setText("Gender");
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
//CheckboxGroup lngGrp = new CheckboxGroup();
JLabel emptyLabel = new JLabel();
ButtonGroup genderRadio = new ButtonGroup();
genderRadio.add(male);
genderRadio.add(female);
p.add(genderLabel);
p.add(emptyLabel);
p.add(male);
p.add(female);
JLabel hobbyLabel = new JLabel();
hobbyLabel.setText("Hobby");
JComboBox hobbyCombo = new JComboBox ();
hobbyCombo.addItem("Reading");
hobbyCombo.addItem("Dance");
hobbyCombo.addItem("Painting");
p.add(hobbyLabel);
p.add(hobbyCombo);
JLabel addressLabel = new JLabel();
addressLabel.setText("Address");
26
p.add(addressLabel);
TextArea t = new TextArea();
p.add(t);
t.setSize(8,5);
t.setText("");
p.setVisible(true);
Button submitButton = new Button();
submitButton.setLabel("Submit");
p.add(submitButton);
Button cancelButton = new Button();
cancelButton.setLabel("Cancel");
p.add(cancelButton);
setVisible(true);
} public static void main(String args[])
{ new SwingEx();
}} OUTPUT

27
LAYOUT MANAGERS
 The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of
layout managers. There are following classes that represents the layout
managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout
Example of BorderLayout class:

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

public class Border {


JFrame f;
28
Border(){
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Java GridLayout

29
Example of GridLayout class

import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);

30
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Java FlowLayout

Example of FlowLayout class

import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();

31
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Java BoxLayout

32
Example of BoxLayout class with Y-AXIS:

import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample1 extends Frame {
Button buttons[];
public BoxLayoutExample1 () {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}

33
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}
next →← prev
Java BoxLayout

The BoxLayout is used to arrange the components either vertically or


horizontally. For this purpose, BoxLayout provides four constants. They are as
follows:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class


1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class


1. BoxLayout(Container c, int axis): creates a box layout that arranges the
components with the given axis.

34
Example of BoxLayout class with Y-AXIS:

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15.setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));

35
16.setSize(400,400);
17.setVisible(true);
18.}
19.
20.public static void main(String args[]){
21.BoxLayoutExample1 b=new BoxLayoutExample1();
22.}
23.}
download this example

Example of BoxLayout class with X-AXIS

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

public class BoxLayoutExample2 extends Frame {

36
Button buttons[];
public BoxLayoutExample2() {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
setSize(400,400);
setVisible(true);
}
public static void main(String args[]){
BoxLayoutExample2 b=new BoxLayoutExample2();
}
}
Java CardLayout

37
Example of CardLayout class

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListe
ner{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);

b1=new JButton("Apple");
38
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

39

You might also like