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

Unit-IV JAVA Swing

The document provides an overview of GUI development using Java Swing, covering its components, packages, and event handling. It includes examples of simple Swing applications, event handling mechanisms, and various Swing components such as JLabel, JTextField, and JButton. Additionally, it discusses the structure and functionality of Swing applets and toggle buttons.

Uploaded by

Shravan Saraswat
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)
12 views

Unit-IV JAVA Swing

The document provides an overview of GUI development using Java Swing, covering its components, packages, and event handling. It includes examples of simple Swing applications, event handling mechanisms, and various Swing components such as JLabel, JTextField, and JButton. Additionally, it discusses the structure and functionality of Swing applets and toggle buttons.

Uploaded by

Shravan Saraswat
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/ 89

ELECTRICAL ENGINEERING SECTION

UNIVERSITY POLYTECHNIC, AMU 1

ALIGARH -202002 , U. P. (INDIA)

ELECTIVE-I B
OBJECT ORIENTED PROGRAMMING
(PCO-504E)
V SEMESTER 2022-23
DIPLOMA IN COMPUTER/ELECTRONICS ENGINEERING

DR ZAHID AHMED ANSARI


2

Unit IV – GUI Development Using


Java Swing
OVERVIEW

• JAVA Swing introduction • JTabbedpane


• The Swing Packages • JScrollPane
• A simple Swing Application • Jlist
• Jlabel and ImageIcon • JComboBox
• JTextField • JTable.
• The Swing Buttons
WHAT IS JAVA SWING?

◼ Part of the Java Foundation Classes (JFC) that is used to create window-
based graphical user interface (GUI) applications.
◼ A set of classes that provides powerful and flexible GUI components
◼ A rich set of built-in controls. Trees, image buttons, tabbed panes, sliders,
toolbars, etc.
◼ Controls are platform-independent and lightweight - Not built on native
window-system windows
◼ More customizable. Can change border, text alignment, or add image to
almost any control. Can customize how minor features are drawn.
◼ "Pluggable" look and feel. Can change look and feel at runtime, or design
own look and feel.

4
SWING PACKAGES

◼ Swing is a very large subsystem and consists of many packages

Javax.swing Javax.swing.border Javax.swing.colorchooser

Javax.swing.event Javax.swing.filechooser Javax.swing.plaf

Javax.swing.plaf.basic Javax.swing.plaf.metal Javax.swing.palf.multi

Javax.swing.plaf.synth Javax.swing.table Javax.swing.text

Javax.swing.text.html Javax.swing.text.html.parse Javax.swing.text.rtf

Javax.swing.tree Javax.swing.undo

5
HIERARCHY OF JAVA SWING CLASSES
A SIMPLE SWING APPLICATION

• A Simple Swing application uses two Swing components: JFrame and JLabel.
• JFrame is the top-level container that is commonly used for Swing applications.
• JLabel is the Swing component that creates a label, which is a component that displays
information.
• The program uses a JFrame container to hold an instance of a JLabel. The label displays a
short text message.
EXPECTED OUTPUT
A SIMPLE SWING APPLICATION
import javax.swing.*;

class SwingDemo {
SwingDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");

// Give the frame an initial size.


jfrm.setSize(275, 100);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a text-based label.


JLabel jlab = new JLabel(" Swing means powerful GUIs.");

// Add the label to the content pane.


jfrm.add(jlab);

// Display the frame.


jfrm.setVisible(true);
}

9
A SIMPLE SWING APPLICATION
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater( new Runnable() {
public void run() {
new SwingDemo();
}
});
}
}

10
HANDLE AN EVENT IN A SWING PROGRAM
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class EventDemo {
JLabel jlab;
EventDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");

// Specify FlowLayout for the layout manager.


jfrm.setLayout(new FlowLayout());

// Give the frame an initial size.


jfrm.setSize(220, 90);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make two buttons.


JButton jbtnAlpha = new JButton("Alpha");
11 JButton jbtnBeta = new JButton("Beta");
HANDLE AN EVENT IN A SWING PROGRAM
// Add action listener for Alpha and Beta
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.");
}
});
// Add the buttons to the content pane.
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);

// Create a text-based label.


jlab = new JLabel("Press a button.");
// Add the label to the content pane.
jfrm.add(jlab);

// Display the frame.


jfrm.setVisible(true);
12
}
HANDLE AN EVENT IN A SWING PROGRAM

public static void main(String args[]) {


// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EventDemo();
}
});
}
}

13
LAYOUT HEURISTICS
FlowLayout GridLayout

Left to right,
Top to bottom

BorderLayout CardLayout GridBagLayout


n

w c e One at a time JButton

14
s
EVENT HANDLING IN A SWING PROGRAM

• The event handling mechanism used by Swing is the “Delegation Event Model”.
• In this program we handles the event generated by a Swing push button (JButton)
• It uses four Swing components: A top level JFrame container, two push buttons (JButton), one
label JLabel.
• The JFrame container holds two instances of JButton push buttons named Alpha and Beta,
and an instance of a JLabel. The label initially displays a text message ‘Press a Button’.
• Each time a push button is pressed the string displayed in the label is changed to reflect
which button was pressed
• Sample output is shown below.
SWING APPLET

• A Swing applet extends JApplet rather than AWT Applet.


• JApplet is derived from Applet. Thus, JApplet includes all of the functionality
found in Applet and adds support for Swing.
• JApplet is a top-level Swing container, which means that it is not derived
from JComponent..
• Swing applets use the four lifecycle methods init(), start(), stop(), and
destroy(). We need override only those methods that are needed by the
applet.
• All interaction with components in a Swing applet must take place on the
event dispatching thread.
A SWING APPLET

• It uses four Swing components: A top level JApplet container, two push buttons
(JButton), one label JLabel.
• The Swing JApplet container holds two instances of JButton push buttons named Alpha
and Beta, and an instance of a JLabel. The label initially displays a text message ‘Press a
Button’.
• Each time a push button is pressed the string displayed in the label is changed to reflect
which button was pressed
• Sample output is shown below.
A SIMPLE SWING-BASED APPLET
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MySwingApplet extends JApplet {


JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;

// Initialize the applet.


public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable () {
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc) {
System.out.println("Can't create because of "+ exc);
}
}
18
A SIMPLE SWING-BASED APPLET
private void makeGUI() {
setLayout(new FlowLayout()); // Set the applet to use flow layout.
jbtnAlpha = new JButton("Alpha"); // Make two buttons.
jbtnBeta = new JButton("Beta");

// Add action listener for Alpha and Beta


jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Alpha was pressed.");
}
});
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Beta was pressed.");
}
});
// Add the buttons to the content pane.
add(jbtnAlpha);
add(jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
add(jlab);
}
}
19
JLABLE AND IMAGEICON
◼ JLabel is Swing’s easiest-to-use component. JLabel can be used to display text and/or
an icon. It is a passive component since it does not respond to user input
◼ JLable defines
 several constructors
◼ JLable(Icon icon)

◼ JLable(String str)

◼ JLable(String str, Icon icon, int align)

 Methods
◼ Icon getIcon()

◼ String getText()

◼ void setIcon(Icon icon)

◼ void setText(String str)

◼ ImageIcon encapsulates an image. It implements Icon interface


◼ ImageIcon constructor obtains the image in the file specified
◼ ImageIcon(String filename)

20
JLABLE AND IMAGEICON EXAMPLE

• Next we will take example of an applet to illustrate how to create and


display a label containing both an icon and a string.
JLABEL AND IMAGEICON

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

public class JLabelDemo extends JApplet {


public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}

22
JLABEL AND IMAGEICON

private void makeGUI() {

// Create an icon.
ImageIcon ii = new ImageIcon("france.gif");

// Create a label.
JLabel jl = new JLabel("France", ii, JLabel.CENTER);

// Add the label to the content pane.


add(jl);
}
}

23
JTEXTFIELD

• JTextField is the simplest Swing text component. It is also probably its most widely
used text component.
• JTextField allows you to edit one line of text.
• Three of JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
• Here, str is the string to be initially presented, and cols is the number of columns in the
text field. If no string is specified, the text field is initially empty. If the number of
columns is not specified, the text field is sized to fit the specified string
JTEXTFIELD

• JTextField generates events in response to user interaction. For example, an


ActionEvent is fired when the user presses ENTER.
• To obtain the text currently in the text field, call getText()
• The following example illustrates JTextField.
• It creates a JTextField and adds it to the content pane.
• When the user presses ENTER, an action event is generated.
• This is handled by displaying the text in the status window
JTEXTFIELD
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JTextFieldDemo extends JApplet {


JTextField jtf;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
27
JTEXTFIELD
◼ Simplest and most widely used Swing text component
 Constructors
◼ JTextField(int cols)

◼ JTextField(String str, int cols)

◼ JTextField(String str)

 Methods
◼ String getText()

28
JTEXTFIELD
private void makeGUI() {

// Change to flow layout.


setLayout(new FlowLayout());

// Add text field to content pane.


jtf = new JTextField(15);
add(jtf);
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Show text when user presses ENTER.
showStatus(jtf.getText());
}
});
}
}

29
SWING BUTTONS

• Swing defines four types of buttons


• JButton
• JToggleButton
• JCheckBox
• JRadioButton
• All are subclasses of the AbstractButton class
• The text associated with a button can be read and written via the
following methods:
• String getText()
• void setText(String str)

31
JBUTTON

• The JButton class provides the functionality of a push button.


• JButton allows an icon, a string, or both to be associated with the push button.
• Three of its constructors are:
• JButton(Icon icon)
• JButton(String str)
• JButton(String str, Icon icon)
• When the button is pressed, an ActionEvent is generated.
• This ActionEvent object passed to the actionPerformed() method of the
registered ActionListener
• The following example displays four push buttons and a label. Each button
displays an icon that represents the map of a country. When a button is
pressed, the name of that country is displayed in the label.
ICON-BASED JBUTTON
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JButtonDemo extends JApplet


implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
33
ICON-BASED JBUTTON
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());

// Add buttons to content pane.


ImageIcon france = new ImageIcon("france.gif");
JButton jb = new JButton(france);
jb.setActionCommand("France");
jb.addActionListener(this);
add(jb);

ImageIcon china = new ImageIcon("china.gif");


jb = new JButton(china);
jb.setActionCommand("China");
jb.addActionListener(this);
add(jb);

ImageIcon italy = new ImageIcon("italy.gif");


jb = new JButton(italy);
jb.setActionCommand("Italy");
jb.addActionListener(this);
34 add(jb);
ICON-BASED JBUTTON
ImageIcon japan = new ImageIcon("japan.gif");
jb = new JButton(japan);
jb.setActionCommand("Japan");
jb.addActionListener(this);
add(jb);

// Create and add the label to content pane.


jlab = new JLabel("Choose a Country Map");
add(jlab);
}

// Handle button events.


public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}
}

35
JTOGGLEBUTTON

• A Toggle button has two states


• Pushed
• Released

• When you press the toggle button it stays pressed, when you press a second time it releases
• Therefore, each time a toggle button is pushed, it toggles between its two states.
• By default the button is in the off position
• JToggleButton is super class of JCheckBox and JRadioButton classes
• JToggleButton defines several constructors. The one used in our example is:
JToggleButton(String str)
• This creates a toggle button that contains the text passed in str. By default, the button is in
the off position

37
JTOGGLEBUTTON

• JToggleButton generates an action event each time it is pressed. It also generates


an item event.
• When a JToggleButton is pressed in, it is selected. When it is popped out, it is
deselected.
• To handle item events, you must implement the ItemListener interface. Each time an
item event is generated, it is passed to the itemStateChanged() method defined by
ItemListener.
• The easiest way to determine a toggle button’s state is by calling the isSelected()
method
boolean isSelected()
• It returns true if the button is selected and false otherwise.
JTOGGLEBUTTON EXAMPLE
JTOGGLEBUTTON
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JToggleButtonDemo extends JApplet {


JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
40
JTOGGLEBUTTON
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());

// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");

// Add an item listener for the toggle button.


jtbn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");
}
});
// Add the toggle button and label to the content pane.
add(jtbn);
add(jlab);
}
41 }
JCHECKBOX

• The JCheckBox class provides the functionality of a check box. It’s immediate
superclass is JToggleButton, which provides support for two-state buttons.
• JCheckBox defines several constructors. One is
JCheckBox(String str)
• It creates a check box that has the text specified by str as a label.
• When the user selects or deselects a check box, an ItemEvent is generated.
ItemEvent is passed to the itemStateChanged() method defined by
ItemListener.
JCHECKBOX EXAMPLE
• The following example displays four check boxes and a label. When the user clicks a
check box, an ItemEvent is generated.
• Inside the itemStateChanged() method, getItem() is called to obtain a reference to
the JCheckBox object that generated the event.
• Next, a call to isSelected() determines if the box was selected or cleared.
• The getText() method gets the text for that check box and uses it to set the text inside
the label.
JCHECKBOX
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JCheckBoxDemo extends JApplet


implements ItemListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
44
JCHECKBOX
private void makeGUI() {
setLayout(new FlowLayout());
// Add check boxes to the content pane.
JCheckBox cb = new JCheckBox("C");
cb.addItemListener(this);
add(cb);

cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);

cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);

cb = new JCheckBox("Perl");
cb.addItemListener(this);
add(cb);

// Create the label and add it to the content pane.


jlab = new JLabel("Select languages");
add(jlab);
45 }
JCHECKBOX

// Handle item events for the check boxes.


public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)ie.getItem();

if(cb.isSelected())
jlab.setText(cb.getText() + " is selected");
else
jlab.setText(cb.getText() + " is cleared");
}
}

46
JRADIOBUTTON

• Radio buttons are a group of mutually exclusive buttons, in which only one button can
be selected at any one time.
• JRadioButton class extends JToggleButton.
• JRadioButton provides several constructors. The one is shown here:
• JRadioButton(String str)
• A button group is created by the ButtonGroup class. Elements are then added to the
button group using method:
• void add(AbstractButton ab)
• A JRadioButton generates action events, item events, and change events each time
the button selection changes.

48
JRADIOBUTTON EXAMPLE

• In following example three radio buttons are created and then added to a button
group.
• Pressing a radio button generates an action event, which is handled by
actionPerformed().
• Within that handler, the getActionCommand() method gets the text that is
associated with the radio button and uses it to set the text within a label.
JRADIOBUTTON

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

public class JRadioButtonDemo extends JApplet


implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}

50
JRADIOBUTTON
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());

// Create radio buttons and add them to content pane.


JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this);
add(b3);

// Define a button group.


ButtonGroup bg = new ButtonGroup();
bg.add(b1); bg.add(b2); bg.add(b3);

// Create a label and add it to the content pane.


jlab = new JLabel("Select One");
add(jlab);
51
}
JRADIOBUTTON

// Handle button selection.


public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}
}

52
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 default constructor creates an empty control with the tabs positioned
across the top of the pane.
• Tabs are added by calling addTab(). Here is one of its forms:
• void addTab(String name, Component comp)
• The general procedure to use a tabbed pane is outlined here:
1. Create an instance of JTabbedPane.
2. Add each tab by calling addTab().
3. Add the tabbed pane to the content pane.

54
JTABBEDPANE EXAMPLE
• Example illustrates a tabbed pane. The first tab is titled “Cities” and contains four buttons. Each
button displays the name of a city. The second tab is titled “Colors” and contains three check
boxes. Each check box displays the name of a color. The third tab is titled “Flavors” and contains
one combo box. This enables the user to select one of three flavors.
JTABBEDPANE
import javax.swing.*;

public class JTabbedPaneDemo extends JApplet {


public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}

56
JTABBEDPANE
private void makeGUI() {
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
add(jtp);
}
}

// Make the panels that will be added to the tabbed pane.


class CitiesPanel extends JPanel {
public CitiesPanel() {
JButton b1 = new JButton("New York"); add(b1);
JButton b2 = new JButton("London"); add(b2);
JButton b3 = new JButton("Hong Kong"); add(b3);
JButton b4 = new JButton("Tokyo"); add(b4);
}
}
57
JTABBEDPANE
class ColorsPanel extends JPanel {
public ColorsPanel() {
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}

class FlavorsPanel extends JPanel {


public FlavorsPanel() {
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}

58
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 contained within another lightweight container, such as a JPanel.
• 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.
• JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll bars.
• Here are the steps to follow to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll using
JScrollPane(Component comp)
3. Add the scroll pane to the content pane.

60
JSCROLLPANE EXAMPLE

• Example illustrates a scroll pane. First, a JPanel object is created, and 400 buttons are
added to it, arranged into 20 columns. This panel is then added to a scroll pane, and the
scroll pane is added to the content pane. Because the panel is larger than the viewport,
vertical and horizontal scroll bars appear automatically. You can use the scroll bars to
scroll the buttons into view.

61
JSCROLLPANE
import java.awt.*;
import javax.swing.*;
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}

62
JSCROLLPANE
private void makeGUI() {
` // Add 400 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);

// Add the scroll pane to the content pane. Because the default border layout
// is used, the scroll pane will be added to the center.
add(jsp, BorderLayout.CENTER);
}
}
63
JLIST

• In Swing, the basic list class is called JList. It supports the selection of one or more items
from a list. Although the list often consists of strings, it is possible to create a list of any
object that can be displayed.
• JList provides several constructors. Following constructor creates a JList that contains the
items in the array specified by items.
JList(Object[] items)
• A JList generates a ListSelectionEvent when the user makes or changes a selection or
deselects an item.
• It is handled by implementing ListSelectionListener. This listener specifies only one
method, called valueChanged()
• By default, a JList allows the user to select multiple ranges of items within the list, but you
can change this behavior by calling setSelectionMode()

64
JLIST

• Following applet demonstrates a simple JList, which holds a list of cities. Each time a city is selected
in the list, a ListSelectionEvent is generated, which is handled by the valueChanged() method
defined by ListSelectionListener. It responds by obtaining the index of the selected item and
displaying the name of the selected city in a label.

65
JLIST
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class JListDemo extends JApplet {
JList jlst;
JLabel jlab;
JScrollPane jscrlp;
// Create an array of cities.
String Cities[] = { "New York", "Chicago", "Houston",
"Denver", "Los Angeles", "Seattle", "London", "Paris", "New Delhi",
"Hong Kong", "Tokyo", "Sydney" };
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
66
JLIST
private void makeGUI() {

// Change to flow layout.


setLayout(new FlowLayout());

// Create a JList.
jlst = new JList(Cities);

// Set the list selection mode to single-selection.


jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

// Add the list to a scroll pane.


jscrlp = new JScrollPane(jlst);

// Set the preferred size of the scroll pane.


jscrlp.setPreferredSize(new Dimension(120, 90));

// Make a label that displays the selection.


jlab = new JLabel("Choose a City");
67
JLIST
// Add selection listener for the list.
jlst.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent le) {
// Get the index of the changed item.
int idx = jlst.getSelectedIndex();
// Display selection, if item was selected.
if(idx != -1)
jlab.setText("Current selection: " + Cities[idx]);
else // Othewise, reprompt.
jlab.setText("Choose a City");

}
});
// Add the list and label to the content pane.
add(jscrlp);
add(jlab);
}
}

68
JCOMBOBOX

• Swing provides a combo box (a combination of a text field and a drop-down list) through the
JComboBox class.
• A combo box normally displays one entry, but it will also display a drop-down list that allows a
user to select a different entry.
• The following JComboBox constructor initializes the combo box using items array
• JComboBox(Object[ ] items)
• JComboBox generates an action event when the user selects an item from the list.
• JComboBox also generates an item event when the state of selection changes, which occurs
when an item is selected or deselected.
• One way to obtain the item selected in the list is to call getSelectedItem() on the combobox.

69
JCOMBOBOX

• The following example demonstrates the combo box. The combo box contains entries for
“France,” “Germany,” “Italy,” and “Japan.” When a country is selected, an icon-based label is
updated to display the flag for that country.

70
JCOMBOBOX
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "France", "Germany", "Italy", "Japan" };

public void init() {


try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
71
JCOMBOBOX
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());

// Instantiate a combo box and add it to the content pane.


jcb = new JComboBox(flags);
add(jcb);

// Handle selections.
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".gif"));
}
});

// Create a label and add it to the content pane.


jlab = new JLabel(new ImageIcon("france.gif"));
add(jlab);
}
}
72
JTABLE

• JTable is a component that displays rows and columns of data. You can drag the cursor on
column boundaries to resize columns. You can also drag a column to a new position.
• Depending on its configuration, it is also possible to select a row, column, or cell within the table,
and to change the data within a cell.
• JTable consists of one or more columns of information. At the top of each column is a heading. In
addition to describing the data in a column, the heading also provides the mechanism by which
the user can change the size of a column or change the location of a column within the table.
• JTable does not provide any scrolling capabilities of its own. Instead, you will normally wrap a
Jtable inside a JScrollPane.
• JTable supplies several constructors. The one used here is
• JTable(Object data[][], Object colHeads[])
• Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-
dimensional array with the column headings.

73
JTABLE

• Here are the steps required to set up a simple JTable that can be used to display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.

74
JTABLE EXAMPLE

The following example illustrates how to create and use a simple table. A one-dimensional array of
strings called colHeads is created for the column headings. A two-dimensional array of strings called
data is created for the table cells. You can see that each element in the array is an array of three
strings. These arrays are passed to the JTable constructor. The table is added to a scroll pane, and
then the scroll pane is added to the content pane. The table displays the data in the data array. The
default table configuration also allows the contents of a cell to be edited. Changes affect the
underlying array, which is data in this case.
JTABLE
import java.awt.*;
import javax.swing.*;
public class JTableDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}

76
JTABLE
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };

// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
77
JTABLE
// Create the table.
JTable table = new JTable(data, colHeads);

// Add the table to a scroll pane.


JScrollPane jsp = new JScrollPane(table);

// Add the scroll pane to the content pane.


add(jsp);
}
}

78
JTREE

• A tree is a component that presents a hierarchical view of data. The user has the ability to expand
or collapse individual subtrees in this display.
• Trees are implemented in Swing by the JTree class. One of the JTree constructor is shown below
• JTree(TreeNode tn) // tn is root node
• JTree does not provide any scrolling capabilities of its own. Instead, a JTree is typically placed
within a JScrollPane. This way, a large tree can be scrolled through a smaller viewport.
• Here are the steps to follow to use a tree:
1. Create an instance of JTree.
2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.

79
JTREE EXAMPLE
Example illustrates how to create a tree and handle selections. The program creates a
DefaultMutableTreeNode instance labeled “Options.” This is the top node of the tree hierarchy.
Additional tree nodes are then created, and the add() method is called to connect these nodes to
the tree. A reference to the top node in the tree is provided as the argument to the JTree
constructor. The tree is then provided as the argument to the JScrollPane constructor. This scroll
pane is then added to the content pane. Next, a label is created and added to the content pane.
The tree selection is displayed in this label. To receive selection events from the tree, a
TreeSelectionListener is registered for the tree. Inside the valueChanged() method, the path to the
current selection is obtained and displayed.
JTREE
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class JTreeDemo extends JApplet {
JTree tree;
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
81
JTREE
private void makeGUI() {
// Create top node of tree.
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");

// Create subtree of "A".


DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);

// Create subtree of "B".


DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);
82
JTREE
// Create the tree.
tree = new JTree(top);

// Add the tree to a scroll pane.


JScrollPane jsp = new JScrollPane(tree);

// Add the scroll pane to the content pane.


add(jsp);

// Add the label to the content pane.


jlab = new JLabel();
add(jlab, BorderLayout.SOUTH);

// Handle tree selection events.


tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
jlab.setText("Selection is " + tse.getPath());
}
});
}
}
83
A PAINT EXAMPLE

• Here is a program that creates a class called PaintPanel that extends JPanel.
The program then uses an object of that class to display lines whose
endpoints have been generated randomly. Sample output is shown here.
PAINT LINES TO A PANEL
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

// This class extends JPanel. It overrides the paintComponent() method so


// that random lines are plotted in the panel.
class PaintPanel extends JPanel {
Insets ins; // holds the panel's insets
Random rand; // used to generate random numbers

// Construct a panel.
PaintPanel() {
// Put a border around the panel.
setBorder(BorderFactory.createLineBorder(Color.RED, 5));
rand = new Random();
}

85
PAINT LINES TO A PANEL
// Override the paintComponent() method.
protected void paintComponent(Graphics g) {
// Always call the superclass method first.
super.paintComponent(g);
int x, y, x2, y2;
// Get the height and width of the component.
int height = getHeight();
int width = getWidth();
// Get the insets.
ins = getInsets();

// Draw ten lines whose endpoints are randomly generated.


for(int i=0; i < 10; i++) {
// Obtain random coordinates that define the endpoints of each line
x = rand.nextInt(width-ins.left);
y = rand.nextInt(height-ins.bottom);
x2 = rand.nextInt(width-ins.left);
y2 = rand.nextInt(height-ins.bottom);
// Draw the line.
g.drawLine(x, y, x2, y2);
}
86 }
PAINT LINES TO A PANEL
// Demonstrate painting directly onto a panel.
class PaintDemo {
PaintPanel pp;

PaintDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("Paint Demo");
// Give the frame an initial size.
jfrm.setSize(200, 150);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create the panel that will be painted.


pp = new PaintPanel();
// Add the panel to the content pane. Because the default border layout is
// used, the panel will automatically be sized to fit the center region.
jfrm.add(pp);

// Display the frame.


jfrm.setVisible(true);
}
87
PAINT LINES TO A PANEL

public static void main(String args[]) {


// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PaintDemo();
}
});
}

88
THANK YOU!

You might also like