0% found this document useful (0 votes)
9 views33 pages

Module-03

The document provides study material for the Advanced Java course, focusing on Swing, a GUI toolkit that overcomes limitations of AWT by offering lightweight components and a pluggable look and feel. It covers key features of Swing, the Model-View-Controller architecture, event handling, and painting in Swing. Additionally, it includes examples of creating simple Swing applications and handling events through listeners.

Uploaded by

appucit2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views33 pages

Module-03

The document provides study material for the Advanced Java course, focusing on Swing, a GUI toolkit that overcomes limitations of AWT by offering lightweight components and a pluggable look and feel. It covers key features of Swing, the Model-View-Controller architecture, event handling, and painting in Swing. Additionally, it includes examples of creating simple Swing applications and handling events through listeners.

Uploaded by

appucit2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

|| Jai Sri Gurudev |

Sri Adichunchanagiri Shikshana Trust (R)

SJB INSTITUTE OF TECHNOLOGY

Study Material

Subject Name: Advanced Java


Subject Code: BCS613D

By
Faculty Name:
Mrs. Rajani,Vijayalakshmi B
Designation: Assistant Professor
Semester: VI

Department of Computer Science & Engineering

Aca. Year: Even Sem /2025


Advanced Java BCS613D

Module-3

Introducing Swing: The Origin of Swing, Swing Is Built on AWT, Two Key Swing Features, The MVC

Connection, Components and Containers, The Swing Packages, A Simple Swing Application, Event

Handling, Painting in Swing, Exploring Swing : JLabel and ImageIcon, JTextField,The Swing Buttons-

JButton, JToggleButton, Check Boxes, Radio Buttons.

1. Introducing Swing:
 In earlier days of Java AWT classes were used to create Graphical User
Interface(GUI’s).
 Now no longer AWT Classes are used to develop GUI.
 Today, most programmers use Swing for this purpose because “Swing is a set of classes
that provides more powerful and flexible GUI components than does the AWT”
 Earlier to swing, Java programmer uses AWT classes to develop GUI’s but AWT classes
contains limited graphical interface.
 This is one of reason that programmer wants to develop different component, that has
more flexible and rich in graphical interface.
 Because of the limited graphical interface AWT translate its various visual components
into their corresponding, platform-specific equivalents, or peers. That means look and
feel of the component is decided by platform, not by JAVA.
 Because the AWT components use native code resources, they are referred to as
heavyweight.
 The usage of native resources of platform led to following problems
 Because of variations between operating systems, a component might look, or even act,
differently on different platforms which also threaten the philosophy of java “write once,
run anywhere”.
 Second, the look and feel of each component was fixed and could not be (easily)
changed.
 The use of heavyweight components caused some frustrating restrictions.
 This Restriction and limitation of AWT classes create serious issues for programmer so
SWINGS came into picture.
 Introduced in 1997, Swing was included as part of the Java Foundation Classes (JFC).
 Java Swing component is completely incorporated in JDK 1.2.
2. SWING is Bulit on AWT
 There is one important point to be remembered that Although SWING eliminates
number of limitations of AWT classes, but SWING doesn't replace it.
 Swing is built on the foundation of the AWT.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

3. Key Features of SWING

 Java is a platform-independent language and runs on any client machine, the GUI look and
feel, owned and delivered by a platform-specific O/S, simply does not affect an application’s GUI
constructed using Swing components.
 Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not depend on any
non-Java [O/s based) system classes. Swing components have their own view supported by Java’s
look and feel classes.
 Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing
components without restarting an application. The Swing library supports components’ look and
feels that remain the same across all platforms wherever the program runs. The Swing library
provides an API that gives real flexibility in determining the look and feel of the GUI of an
application
 Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
 Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider,
colorpicker, and table controls.

4. Differentiate between AWT and Swings.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

Advantages:
 Swing components are lightweight and don't rely on peers.
 Swing supports a pluggable look and feel.
 Swing is built on AWT.
5. Model-View-Controller(MVC)

A visual component is a composite of three distinct aspects:


1. The model corresponds to the state information associated with the component.
2. The view determines how the component is displayed on the screen
3. The controller determines how the component responds to the user.
Swing uses a modified version of MVC called "Model-Delegate".
In this model the view (look) and controller (feel) are combined into a "delegate".
Hence, the look and feel can be changed without affecting how the component is used in
a program.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

6. Components and Containers

• Swing components are derived from the JComponent class.


• JComponent provides the functionality that is common to all components.
• For example, JComponent supports the pluggable look and feel.
• JComponent inherits the AWT classes Container and Component.
• Thus, a Swing component is built on and compatible with an AWT component.
• All of Swing’s components are represented by classes defined within the package
javax.swing.
The following table shows the class names for Swing components (including those
used as containers)

Containers:
Swing defines two types of containers:

1. Top-level containers :do not inherit JComponent,

2. Lightweight containers : do inherit JComponent

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

Top-level containers
1. JFrame ,JApplet ,JWindow ,Jdialog
2. These containers do not inherit Jcomponent.
3. They inherit the AWT classes Component and Container.
4. The top-level containers are heavyweight.
5. It must be at the top of a containment hierarchy
6. A top-level container is not contained within any other container.
7. Every containment hierarchy must begin with a top-level container.
8. The one most commonly used for applications is JFrame.
9. The one used for applets is JApplet.

Top-level Container Panes:

 Each top-level component defines a collection of "panes”

 The top-level pane is JRootPane.

 JRootPane manages the other panes and can add a menu bar.

 There are three panes in JRootPane:

o the glass pane,


o the content pane,
o the layered pane.

 Glass pane: This is the first pane and is very close to the monitor’s screen. Any
components to be displayed in the foreground are attached to this glass pane. To reach
this glass pane we use getGlassPane() method of JFrame class, which return Component
class object

 Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this frame. To go to the root pane, we can use getRootPane()
method of JFrame class, which returns JRootPane object.

 Layered pane: This pane is below the root pane. When we want to take several
components as a group, we attach them in the layered pane. We can reach this pane by
calling getLayeredPane() method of JFrame class which returns JLayeredPane class
object

 content pane: to add our components We can reach this pane by calling getcontentPane()

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

Lightweight containers:

• JPanel

• The second type of containers supported by Swing are lightweight containers.

• Lightweight contaiklners do inherit JComponent.

• used to organize and manage groups of related components(it can be contained within
another container. )

• Used to create subgroups of related controls that are contained within an outer container

• Panel JPanel is the simplest container. It provides space in which any other component
can be placed, including other panels.

7. The Swing Packages:


 Swing is a very large subsystem and makes use of many packages.
 These are the packages used by Swing that are defined by Java SE 6.
 The main package is javax.swing.
 This package must be imported into any program that uses Swing.
 It contains the classes that implement the basic Swing components,
such as push buttons, labels, and check boxes.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

8. A simple Swing Application


• There are two ways to create a frame:

1. By creating the object of Frame class (association)

import javax.swing.*;

public class FirstSwing

public static void main(String[] args)

JFrame f=new JFrame(“ MyApp”);

JButton b=new JButton("click");

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

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

f.setLayout(null); //using no layout managers

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

2. By extending Frame class(inheritance)

import javax.swing.*;

public class MySwing extends JFram //inheriting JFrame

JFrame f;

MySwing()

JButton b=new JButton("click");//create

button b.setBounds(130,100,100, 40);

add(b);//adding button on

frame setSize(400,500);

setLayout(null);

setVisible(true);

public static void main(String[] args)

new MySwing();

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

Note: We can write the code of swing inside the main(), constructor or any other method

9. Event Handling in Swings:

⚫ When swing component do respond to user input and the events are generated by
those interactions.
⚫ Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc.
⚫ The event handling mechanism used by Swing is the same as that used by the AWT.
⚫ In many cases, Swing uses the same events as does the AWT, and these events are
packaged in java.awt.event.
⚫ Events specific to Swing are stored in javax.swing.event.

Steps for Event Handling:


⚫ Choose the Appropriate Component: Decide which Swing component will trigger the
event. This could be a button, menu item, text field, etc.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

⚫ Create an Event Listener: Choose the appropriate listener interface for the event you want
to handle. Common listener interfaces include ActionListener, MouseListener,
KeyListener, etc.
⚫ Implement the Listener Interface: Implement the methods of the chosen listener interface
in your class. This involves writing code to respond to the specific event triggered by the
component.
⚫ Register the Listener: Attach the listener to the Swing component using the appropriate
method. For example, if you're using an ActionListener, you would typically use the
addActionListener() method to register the listener with a JButton or JMenuItem.
⚫ Handle the Event: Write the code that should execute when the event occurs. This code is
placed inside the listener's methods. For example, if you're handling a button click event
with an ActionListener, you would write the code inside the actionPerformed() method.

Registration Methods:
• For Button : public void addActionListener(ActionListener a){}
• For MenuItem: public void addActionListener(ActionListener a){}
• For TextField: public void addActionListener(ActionListener a){}
• public void addTextListener(TextListener a){}
• For TextArea public void addTextListener(TextListener a){}
• For Checkbox : public void addItemListener(ItemListener a){}
• For RadioButton: public void addItemListener(ItemListener a){}
• Choice: public void addItemListener(ItemListener a){}
• For List: public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

Example Program: Demonstrate a swing event handling application that creates


2 buttons Alpha and Beta and displays the text “Alpha pressed” when alpha button
is clicked and “Beta pressed” when beta button is clicked.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class EventDemo {
JLabel jlab;

EventDemo() {
JFrame jfrm = new JFrame("An Event Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(300, 150);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

JButton jbtnAlpha = new JButton("Alpha");


JButton jbtnBeta = new JButton("Beta");

jlab = new JLabel("Press a button:");

jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed..");
}
});

jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed..");
}
});

jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
jfrm.add(jlab);

jfrm.setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EventDemo();
}
});
}
}
Output:

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

10. Painting in Swing


 public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
 public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
 public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
 public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
 public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
 public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
 public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
 public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
 public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
 public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
 public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

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

public class Painting2 extends JPanel {

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

// Draw string
g.drawString("Hello", 40, 40);

// Draw rectangle
g.drawRect(130, 30, 100, 80);

// Fill rectangle
g.fillRect(130, 130, 100, 80);

// Draw oval
g.drawOval(30, 130, 50, 60);

// Fill oval
g.fillOval(130, 130, 50, 60);

// Draw line
g.drawLine(30, 200, 130, 200);

// Draw arc
g.drawArc(30, 250, 80, 80, 90, 180);

// Fill arc
g.fillArc(130, 250, 80, 80, 45, 135);

// Set color
g.setColor(Color.BLUE);

// Set font
g.setFont(new Font("TimesRoman", Font.BOLD, 20));
g.drawString("Swing Drawing Example", 10, 300);
}

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Swing Drawing Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Painting2 panel = new Painting2(); // Use Painting2 instead of


DrawingExample
panel.setPreferredSize(new Dimension(400, 400));

frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
});
}
}

11. Exploring Swing


⚫ Here in this topic we are going to discuss about Swing components that provide rich
functionality and allow a high level of customization.
Ex: buttons, check boxes, trees, and tables
⚫ These components are all lightweight, which means that they are all derived from
JComponent.
⚫ One other point: The Swing components are demonstrated in applets because the code for
an applet is more compact than it is for a desktop application.

a) The Swing Buttons:

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

 Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and


JRadioButton.
 All are subclasses of the AbstractButton class, which extends JComponent.
 AbstractButton contains many methods that allow you to control the behavior of buttons.
 For example, you can define different icons that are displayed for the button when it is
disabled, pressed, or selected.
 void setDisabledIcon(Icon di)
 void setPressedIcon(Icon pi)
 void setSelectedIcon(Icon si)
 void setRolloverIcon(Icon ri)
 Here, di, pi, si, and ri are the icons to be used for the indicated purpose.
 The text associated with a button can be read and written via the following methods:
 String getText( ): Read
 void setText(String str): Written

i) JButton:
• JButton class provides functionality of a button.
• JButton class has 2 constuctors,
1. JButton(Icon ic)
2. JButton(String str)

Jbutton with Text:

import javax.swing.*;

class FirstSwing

public static void main(String args[])

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

JFrame jf=new JFrame("My App");

JButton jb=new JButton("Next");

jb.setBounds(30, 100, 100, 50);

JButton jb1=new JButton("Prev");

jb1.setBounds(30, 200, 100, 50);

jf.add(jb);

jf.add(jb1);

jf.setSize(300, 600);

jf.setLayout(null);

jf.setVisible(true);

Output:

Jbutton with Image

package javaapplication4;

import javax.swing.*;

public class ButtonWithImage1{

ButtonWithImage1(){

JFrame f=new JFrame("Button Example");

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

JButton b=new JButton(new ImageIcon("C:\\Users\\LENOVO\\Downloads\\java-jbutton3 "));

b.setBounds(200,100,200, 100);

f.add(b);

f.setSize(300,400);

f.setLayout(null);

f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String[] args) {

new ButtonWithImage1();

} }

Output:

ii) JRadioButton

 It is used to represent multiple option single selection elements in a form.


 This is performed by grouping the JRadio buttons using a ButtonGroup
component.
 The ButtonGroup class can be used to group multiple buttons so that at a
time only one button can be selected.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

import javax.swing.*;

import javax.swing.*;

public class RadioButton1

public static void main(String args[])

{JFrame f=new JFrame("MyAppRadio");

JRadioButton r1=new JRadioButton("Male ");

JRadioButton r2=new JRadioButton("Female");

r1.setBounds(50, 100, 70, 30);

r2.setBounds(50,150,70,30);

ButtonGroup bg=new ButtonGroup();

bg.add(r1);

bg.add(r2);

f.add(r1);

f.add(r2);

f.setSize(500,500);

f.setLayout(null);

f.setVisible(true);

Output:

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

JCheckBox:
• A JCheckBox is the Swing equivalent of the Checkbox component in AWT.

This is sometimes called a ticker box, and is used to represent multiple option selections in a
form.

import javax.swing.*;

class FirstSwing

public static void main(String args[])

JFrame jf=new JFrame("CheckBox");

JCheckBox jb=new JCheckBox("JAVA");

jb.setBounds(30, 100, 100, 50)

JCheckBox jb1=new

JCheckBox("Python");

jb1.setBounds(30, 200, 100, 50);

jf.add(jb);

jf.add(jb1);

jf.setSize(300, 600);

jf.setLayout(null);

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

jf.setVisible(true);

Output:

JComboBox

• The JComboBox class is used to create the combobox (drop-down list).

• At a time only one item can be selected from the item list.

import java.awt.*;

import javax.swing.*;

public class Comboexample

public static void main(String[] args)

JFrame f=new JFrame("Combo demo");

String Branch[]={"cse","ise","ec","mech"};

JComboBox jc=new JComboBox(Branch);

jc.setBounds(50,50,80,50);

f.add(jc);

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

f.setSize(400, 400);

f.setLayout(null);

f.setVisible(true);

Output:

JToggleButton:
⚫ A useful variation on the push button is called a toggle button.

⚫ A toggle button looks just like a push button, but it acts differently because it has two
states: pushed and released.

⚫ When you press toggle button first time, it stays pressed(pushed). When you press the
button second time, it will be released(pops up).

⚫ Toggle buttons are objects of the JToggleButton class. JToggleButton implements


AbstractButton.

⚫ JToggleButton defines several constructors. The one used by the example in this section
is shown here: JToggleButton(String str)

⚫ This creates a toggle button that contains the text passed in str.

⚫ Like JButton, JToggleButton generates an action event each time it is pressed.

⚫ however, JToggleButton also generates an item event.

⚫ To handle item events, you must implement the ItemListener interface.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

⚫ Easiest way to determine the state of the button is by using this method: isSelected( );

It returns the Boolean value : true or false

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class ToggleButton1 {

private JFrame frame;

private JPanel panel;

private JLabel statusLabel;

public ToggleButton1() {

// Create the frame

frame = new JFrame("JToggleButton Example");

frame.setSize(300, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a panel to hold components

panel = new JPanel();

frame.add(panel);

// Create a toggle button

JToggleButton toggleButton = new JToggleButton("Toggle");

toggleButton.setPreferredSize(new Dimension(50, 50));

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

// Add an action listener to handle events when the button is pressed

toggleButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (toggleButton.isSelected()) {

statusLabel.setText("Button is selected");

} else {

statusLabel.setText("Button is not selected");

});

// Create a label to display status

statusLabel = new JLabel("Button is not selected");

// Add components to the panel

panel.add(toggleButton);

panel.add(statusLabel);

// Center the frame on the screen

frame.setLocationRelativeTo(null);

// Make the frame visible

frame.setVisible(true);

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

public static void main(String[] args) {

// Use the event dispatch thread to build the Swing UI

SwingUtilities.invokeLater(new Runnable() {

public void run() {

new ToggleButton1();

});

b. JLabel and ImageIcon:


It's a subclass of JComponent
It can be used to display text, images, or both on the GUI
JLabel defines several constructors
1. JLabel(Icon icon)
2. JLabel(String str)
3. JLabel(String str, Icon icon, int align)
Here, str and icon :text and icon used for the label
Align:the horizontal alignment of the text and/or icon(LEFT, RIGHT, CENTER, LEADING, or
TRAILING.)

ImageIcon:

• The easiest way to obtain an icon is to use the ImageIcon class

• ImageIcon implements Icon and encapsulates an image.

• Thus, an object of type ImageIcon can be passed as an argument to the Icon parameter of
JLabel’s constructor.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

• ImageIcon(String filename)

• Icon getIcon( ) ,String getText( )

• void setIcon(Icon icon)

• void setText(String str)

import javax.swing.*;

public class PgmImageIcon

public static void main(String[] args)

JFrame f=new JFrame("Image Icon");

jf.setLayout(null);

Icon icon = new ImageIcon("a.jpg");

JLabel label1 = new JLabel("Welocme to RNS",icon,JLabel.RIGHT);

label1.setBounds(20, 30, 267, 200);

f.add(label1);

f.setSize( 300,400);

f.setVisib le(true); } }

c. JPasswordField
• It is a lightweight component that allows the editing of a single line of text where the
view indicates something was typed, but does not show the original characters.

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

import javax.swing.*;

public class JTextFieldPgm

public static void main(String[] args)

JFrame f=new JFrame("My App");

JLabel namelabel= new JLabel("User ID: ");

namelabel.setBounds(10, 20, 70, 10);

JLabel passwordLabel = new JLabel("Password: ");

passwordLabel.setBounds(10, 50, 70, 10);

JTextField userText = new JTextField();

userText.setBounds(80, 20, 100, 20);

JPasswordField passwordText = new JPasswordField();

passwordText.setBounds(80, 50, 100, 20);

f.add(namelabel);

f.add( passwordLabel);

f.add(userText);

f.add(passwordText);

f.setSize(300, 300);

f.setLayout(null);

f.setVisible(true);

}}

Output:

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

d. JTable and JScrollPane


• The JTable class is used to display the data on two dimensional tables of cells.

Commonly used Constructors of JTable class:

1. JTable(): creates a table with empty cells

2. JTable(Object[ ][ ] rows, Object[ ] columns) :creates a table with the specified


data

JScrollpane:
• JScrollPane is a lightweight container that automatically handles the scrolling of another
component

• The component being scrolled can either be an individual component, such as a table, or
a group of components.

• In either case, if the object being scrolled is larger than the viewable area, horizontal
and/or vertical scroll bars are automatically provided, and the component can be scrolled
through the pane.

• The viewable area of a scroll pane is called the viewport

• In its default behavior, a JScrollPane will dynamically add or remove a scroll bar as
needed. For example, if the component is taller than the viewport, a vertical scroll bar is
added. If the component will completely fit within the viewport, the scroll bars are
removed

import javax.swing.*;

public class TableExample1

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

public static void main(String[] args)

JFrame f=new JFrame("Table Demo");

String data[][]={

{"100","CSE","VTU"}

{"101","ISE","VTU"}

{"102","CSE","VTU"}

{"103","ISE","VTU"}

{"105","ISE","VTU"}

{"106","ISE","VTU"}

};

String column[]={"courseID","Branch","University"};

JTable jt=new JTable(data,column);

JScrollPane js=new

JScrollPane(jt);

js.setBounds(30,100,300,100);

f.add(js);

f.setSize(300,400);

f.setLayout(null);

f.setVisible(true);

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

}}

Output:

e. JTabbedpane

• JTabbedPane encapsulates a tabbed pane

• It manages a set of components by linking them with tabs.

• Selecting a tab causes the component associated with that tab to come to the
forefront

• JTabbedPane defines three constructors.

• Default constructor-creates an empty control with the tabs positioned across


the top of the pane.

• The other two constructors specify the location of the tabs, which can be
along any of the four sides.

• Model-SingleSelectionModel model.

• Tabs -addTab( )
import javax.swing.*;

public class MainClass

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

public static void main(String[] a)

JFrame f = new JFrame("JTab");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.add(new JTabbedPaneDemo());

f.setSize(500, 500);

f.setVisible(true);

} class JTabbedPaneDemo extends JPanel

JTabbedPaneDemo()

makeGUI();

void makeGUI()

JTabbedPane jtp = new JTabbedPane();

jtp.addTab("Cities", new CitiesPanel());

jtp.addTab("Colors", new ColorsPanel());

jtp.addTab("Flavors", new FlavorsPanel());

add(jtp);}}

class CitiesPanel extends JPanel

public CitiesPanel()

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

JButton b1 = new JButton("NewYork");

add(b1);

JButton b2 = new JButton("London");

add(b2);

JButton b3 = new JButton("Hong Kong");

add(b3);

JButton b4 = new JButton("Tokyo");

add(b4);

class ColorsPanel extends JPanel

public ColorsPanel()

JCheckBox cb1 = new

CheckBox("Red"); add(cb1);

JCheckBox cb2 = new

JCheckBox("Green"); add(cb2);

JCheckBox cb3 = new

JCheckBox("Blue"); add(cb3);

class FlavorsPanel extends JPanel

public FlavorsPanel()

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B


Advanced Java BCS613D

JComboBox jcb = new JComboBox();

jcb.addItem("Vanilla");

jcb.addItem("Chocolate");

jcb.addItem("Strawberry");

add(jcb);

Output:

Dept. of CSE,SJBIT Rajani, Vijayalakshmi B

You might also like