0% found this document useful (0 votes)
54 views34 pages

Unit-Iv Swings Notes

Uploaded by

pearl
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)
54 views34 pages

Unit-Iv Swings Notes

Uploaded by

pearl
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/ 34

CMRCET CSE JAVA UNIT-IV PART-II NOTES

Syllabus:
Swing – Introduction, limitations of AWT, MVC architecture, components, containers, exploring swing-
JApplet, JFrame and JComponent, Icons and Labels, text fields, buttons – The JButton class, Check
boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.

Swings
Introduction:

Swing is a set of classes that provides more powerful and flexible GUI components than does the AWT

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, 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 etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.
CMRCET CSE JAVA UNIT-IV PART-II NOTES

The solution was Swing. Introduced in 1997, Swing was included as part of the Java Foundation Classes
(JFC). Swing was initially available for use with Java 1.1 as a separate library. However, beginning with
Java 1.2, Swing (and the rest of the JFC) was fully integrated into Java.

Swing Components Are Lightweight:

Swing components are lightweight. This means that they are written entirely in Java and do not map
directly to platform-specific peers

Swing Supports a Pluggable Look and Feel:

Swing supports a pluggable look and feel (PLAF). Because each Swing component is rendered by Java
code rather than by native peers, the look and feel of a component is under the control of Swing

In other words, it is possible to “plug in” a new look and feel for any given component without creating
any side effects in the code that uses that component.

AWT has several limitations:


AWT lacks some essential components like tables and trees, often used in desktop applications.

Due to the lack of certain component features, the toolkit does not support images on buttons.

Since AWT is platform-dependent, its extensibility is limited, constraining its adaptability.

MVC
• The way that the component looks when rendered on the screen

• The way that the component reacts to the user

• The state information associated with the component

The MVC architecture:

In MVC terminology, the model corresponds to the state information associated with the component.
For example, in the case of a check box, the model contains a field that indicates if the box is checked
or unchecked. The view determines how the component is displayed on the screen, including any aspects
of the view that are affected by the current state of the model. The controller determines how the
component reacts to the user.

For example, when the user clicks a check box, the controller reacts by changing the model to reflect
the user’s choice (checked or unchecked). This then results in the view being updated. By separating a
component into a model, a view, and a controller, the specific implementation of each can be changed
without affecting the other two. For instance, different view implementations can render the same
component in different ways without affecting the model or the controller
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Components and Containers:


-> A container holds a group of components

->Because containers are components, a container can also hold other containers.

->This enables Swing to define what is called a containment hierarchy at the top of which must be a top-
level container

Components:

-> In general, 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

List of swing components :

Containers:

Swing defines two types of containers.

The first are top-level containers: JFrame, JApplet, JWindow, and JDialog.

These containers do not inherit JComponent. They do, however, inherit the AWT classes
Component and Container
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Furthermore, every containment hierarchy must begin with a top-level container. The one most
commonly used for applications is JFrame. The one used for applets is JApplet.

The second type of containers supported by Swing are lightweight containers. Lightweight containers
do inherit JComponent. An example of a lightweight container is JPanel, which is a general-purpose
container. Lightweight containers are often used to organize and manage groups of related components
because a lightweight container can be contained within another container.

The Top-Level Container Panes Each top-level container defines a set of panes. At the top of the
hierarchy is an instance of JRootPane. JRootPane is a lightweight container whose purpose is to manage
the other panes

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.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.


CMRCET CSE JAVA UNIT-IV PART-II NOTES

hierarchy of javax swing:

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method and Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.

Java Swing Examples


CMRCET CSE JAVA UNIT-IV PART-II NOTES

There are two ways to create a frame:


By creating the object of Frame class (association)

By extending Frame class (inheritance)

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

Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame object
inside the main() method.

File: FirstSwingExample.java

package azam;

import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
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
f.getDefaultCloseOperation();
}
}
Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Example of Swing by Association inside constructor

We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.

File: Simple.java
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.

File: Simple2.java

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.

Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


CMRCET CSE JAVA UNIT-IV PART-II NOTES

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the


button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the


button.

void addActionListener(ActionListener It is used to add the to this object.


a)

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.

Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button


with no text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, Creates a check box with text and specifies


boolean selected) whether or not it is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken


from the Action supplied.

Code:
CMRCET CSE JAVA UNIT-IV PART-II NOTES

package azam;

import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
checkbox2.setBounds(150,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}

Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Java JRadioButton
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.

Code:

package azam;

import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
CMRCET CSE JAVA UNIT-IV PART-II NOTES

b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}

Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in


the specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements in


items) the specified Vector.

Commonly used Methods:

Methods Description
CMRCET CSE JAVA UNIT-IV PART-II NOTES

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the


list.

void setEditable(boolean b) It is used to determine whether the


JComboBox is editable.

void It is used to add the ActionListener.


addActionListener(ActionListener a)

void addItemListener(ItemListener i) It is used to add the ItemListener.


Code:

package azam;
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES

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.

Commonly used Constructors:

Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab


placement of JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab


placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab


tabLayoutPolicy) placement and tab layout policy.
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Java JTabbedPane Example


import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
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:
CMRCET CSE JAVA UNIT-IV PART-II NOTES

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.

Constructors

Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when


present, sets the scroll pane's client. The two int parameters,
when present, set the vertical and horizontal scroll bar policies
JScrollPane(Component)
(respectively).

JScrollPane(int, int)

JScrollPane(Component,
int, int)

Useful Methods

Modifier Method Description

void setColumnHeaderView(Component) It sets the column header for the scroll


pane.

void setRowHeaderView(Component) It sets the row header for the scroll pane.

void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and
must be one of the following constants
Component getCorner(String)
defined in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
CMRCET CSE JAVA UNIT-IV PART-II NOTES

LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

JScrollPane Example
Code:

package azam;

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);

scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {


createAndShowGUI();
}
});
}
}
CMRCET CSE JAVA UNIT-IV PART-II NOTES

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.

JTree class declaration


Let's see the declaration for javax.swing.JTree class.

Commonly used Constructors:

Constructor Description

JTree() Creates a JTree with a sample model.

JTree(Object[] Creates a JTree with every element of the specified array as the child
CMRCET CSE JAVA UNIT-IV PART-II NOTES

value) of a new root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which
root) displays the root node.

Java JTree Example


Code:

package azam;

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");
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();
}}
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.

JTable class declaration


Let's see the declaration for javax.swing.JTable class.

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Code:

import javax.swing.*;
CMRCET CSE JAVA UNIT-IV PART-II NOTES

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);
}
public static void main(String[] args) {
new TableExample();
}
}

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.
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and


with an empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified


text.

JLabel(Icon i) Creates a JLabel instance with the specified


image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified


horizontalAlignment) text, image, and horizontal alignment.

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this


component will display.

void setHorizontalAlignment(int It sets the alignment of the label's contents


alignment) along the X axis.

Icon getIcon() It returns the graphic image that the label


displays.

int getHorizontalAlignment() It returns the alignment of the label's


contents along the X axis.
Example:
CMRCET CSE JAVA UNIT-IV PART-II NOTES

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.

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified


text.

JTextField(String text, int Creates a new TextField initialized with the specified
columns) text and columns.

JTextField(int columns) Creates a new empty TextField with the specified


number of columns.

Commonly used Methods:


CMRCET CSE JAVA UNIT-IV PART-II NOTES

Methods Description

void addActionListener(ActionListener It is used to add the specified action


l) listener to receive action events from this
textfield.

Action getAction() It returns the currently set Action for this


ActionEvent source, or null if no Action is
set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action


removeActionListener(ActionListener l) listener so that it no longer receives action
events from this textfield.
package azam;
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();
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;
CMRCET CSE JAVA UNIT-IV PART-II NOTES

}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}

Output:

JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The
JApplet class extends the Applet class.

Code:

package test1;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements
ActionListener{
JButton b;
JTextField tf;
CMRCET CSE JAVA UNIT-IV PART-II NOTES

public void init(){


tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null); }
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
} }

Output:

Java JComponent

The JComponent class is the base class of all Swing components except top-level
containers. Swing components whose names begin with "J" are descendants of the
JComponent class. For example, JButton, JScrollPane, JPanel, JTable etc. But,
JFrame and JDialog don't inherit JComponent class because they are the child of
top-level containers.

The JComponent class extends the Container class which itself extends
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Component. The Container class has support for adding components to the
container.

Fields

Modifier and Field Description


Type

protected accessibleContext The


AccessibleContext AccessibleConte
xt associated
with this
JComponent.

protectedEventList listenerList A list of event


enerList listeners for this
component.

static String TOOL_TIP_TEXT_KEY The comment to


display when the
cursor is over the
component, also
known as a
"value tip",
"flyover help",
or "flyover label"

protected ui The look and


ComponentUI feel delegate for
this component.

static int UNDEFINED_CONDITION It is a constant


used by some of
CMRCET CSE JAVA UNIT-IV PART-II NOTES

the APIs to mean


that no condition
is defined.

static int WHEN_ANCESTOR_OF_FOCUSED It is a constant


_COMPONENT used for
registerKeyboard
Action that
means that the
command should
be invoked when
the receiving
component is an
ancestor of the
focused
component or is
itself the focused
component.

static int WHEN_FOCUSED It is a constant


used for
registerKeyboard
Action that
means that the
command should
be invoked when
the component
has the focus.

static int WHEN_IN_FOCUSED_WINDOW Constant used


for
registerKeyboard
Action that
CMRCET CSE JAVA UNIT-IV PART-II NOTES

means that the


command should
be invoked when
the receiving
component is in
the window that
has the focus or
is itself the
focused
component.

Constructor

Constructor Description

JComponent() Default JComponent constructor.

Useful Methods

Modifier and Method Description


Type

void setActionMap(ActionMap am) It sets the ActionMap to


am.

void setBackground(Color bg) It sets the background


color of this component.

void setFont(Font font) It sets the font for this


component.
CMRCET CSE JAVA UNIT-IV PART-II NOTES

void setMaximumSize(Dimension It sets the maximum size


maximumSize) of this component to a
constant value.

void setMinimumSize(Dimension It sets the minimum size


minimumSize) of this component to a
constant value.

protected void setUI(ComponentUI newUI) It sets the look and feel


delegate for this
component.

void setVisible(boolean aFlag) It makes the component


visible or invisible.

void setForeground(Color fg) It sets the foreground


color of this component.

String getToolTipText(MouseEvent It returns the string to be


event) used as the tooltip for
event.

Container getTopLevelAncestor() It returns the top-level


ancestor of this
component (either the
containing Window or
Applet), or null if this
component has not been
added to any container.

TransferHandler getTransferHandler() It gets the


transferHandler
CMRCET CSE JAVA UNIT-IV PART-II NOTES

property.

Java JComponent Example


Code:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyJComponent extends JComponent {
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(30, 30, 100, 100);
}
}
public class JComponentExample {
public static void main(String[] arguments) {
MyJComponent com = new MyJComponent();
// create a basic JFrame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComponent Example");
frame.setSize(300,200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the JComponent to main frame
frame.add(com);
frame.setVisible(true);
}
}

Output:
CMRCET CSE JAVA UNIT-IV PART-II NOTES

Difference between JPanel, JFrame, JComponent, and


JApplet:
Those classes are common extension points for Java UI designs. First off, realize
that they don't necessarily have much to do with each other directly, so trying to
find a relationship between them might be counterproductive.

JApplet - A base class that lets you write code that will run within the context of a
browser, like for an interactive web page. This is cool and all but it brings
limitations which is the price for it playing nice in the real world. Normally
JApplet is used when you want to have your own UI in a web page. I've always
wondered why people don't take advantage of applets to store state for a session so
no database or cookies are needed.

JComponent - A base class for objects which intend to interact with Swing.

JFrame - Used to represent the stuff a window should have. This includes borders
(resizeable y/n?), titlebar (App name or other message), controls
(minimize/maximize allowed?), and event handlers for various system events like
'window close' (permit app to exit yet?).
CMRCET CSE JAVA UNIT-IV PART-II NOTES

JPanel - Generic class used to gather other elements together. This is more
important with working with the visual layout or one of the provided layout
managers e.g. gridbaglayout, etc. For example, you have a textbox that is bigger
then the area you have reserved. Put the textbox in a scrolling pane and put that
pane into a JPanel. Then when you place the JPanel, it will be more manageable in
terms of layout.

You might also like