Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
Java JCheckBoxMenuItem
Next article icon

Java JComponent

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java Swing, JComponent is an abstract class that programmers can use to modify to build unique components that are suited to the particular requirements of their applications. JComponent and other Swing components are lighter than their AWT equivalents. The Java runtime renders lightweight components directly, independent of the host operating system.

All Swing components, with the exception of top-level containers, are included in this core class. With the exception of JFrame and JDialog, which are top-level containers by definition and cannot be put under JComponent, all swing components with the letter "J" in their names are classified as JComponent.
JComponent offers event handling, helping developers respond to user events like mouse clicks, key presses, and other inputs.

Syntax of JComponent

public abstract class JComponent extends 
Container implements Serializable

In the syntax given above, the JComponent is declared as an abstract class, extending the Container class and implementing the Serializable interface. This format indicates that JComponent supports serialization for object persistence and provides a foundation for building GUI components that are customizable. It also inherits container capability.

Nested Class of JComponent

The nested class of JComponent is given below which provides its internal class hierarchy.

Name

Type

Description

JComponent.AccessibleJComponent

Class

By default, the JComponent's inner class is used to offer accessibility.

The nested classes of Java JComponent are inherited from the classes given below:

  • java.awt.Container
  • java.awt.Component

Constructor of JComponent

Constructor

Description

JComponent()

It is a default constructor initializes an empty JComponent.

JComponent Fields

Given below are the fields of JComponent that collects key information and attributes which affects the behavior of the component.

Field

Modifier Type

Description

listenerList

protected EventListenerList

A record of this component's event listeners

TOOL_TIP_TEXT_KEY

static String

The label that appears when the cursor is over an element. It is referred to as a 'value tip', 'flyover help', or 'flyover label'

ui

protected ComponentUI

This component's appearance and texture are assigned.

UNDEFINED_CONDITION

static int

Some APIs utilize this constant to indicate the absence of a specific condition.

WHEN_ANCESTOR_OF_FOCUSED_COMPONENT

static int

Always utilized for registerKeyboardAction. It indicates that the command must be executed when either the receiving component is the focused component or it is the focused component's ancestor.

WHEN_FOCUSED

static int

It is the registerKeyboardAction constant that indicates the command should be executed when the component is the center of attention.

WHEN_IN_FOCUSED_WINDOW

static int

The constant used for registerKeyboardAction indicates that the command should be executed when the receiving component is in the window with the focus or is the focused component itself.

The fields supported by the JComponent are inherited from:

  • Class - java.awt.Component
  • Interface - java.awt.image.ImageObserver

JComponent Methods

The JComponent class offers various methods. Following are some of the commonly used methods:

Method

Modifier Type

Description

addNotify​()

void

Alerts the component to the presence of a parent component.

contains​(int x, int y)

boolean

Allows the UI delegate to specify this component's exact form for mouse processing purposes.

getAlignmentX​()

float

Overrides Container.getAlignmentX to return the horizontal alignment.

getAlignmentY()

float

Overrides Container.getAlignmentY to return the vertical alignment.

getAncestorListeners​()

AncestorListener[]

Provides an array containing all of the registered ancestor listeners on this component.

getAutoscrolls​()

boolean

Gets the autoscrolls property.

getBorder​()

Border

Returns this component's boundary or null if none is set at this time.

getBounds​(Rectangle rv)

Rectangle

Returns rv after storing the component's boundaries in "return value" rv.

getGraphics​()

Graphics

Specifies the visual context for this component, allowing you to draw on it.

getHeight()

int

Returns the current height of the component.

getSize​(Dimension rv)

Dimension

Returns rv after storing the width and height of this component in the "return value" field.

getUI​()

ComponentUI

Returns the delegate's appearance and feel used to render this component.

getX​()

int

Returns the x coordinate of the component's origin.

getY()

int

Returns the y coordinate of the component's origin.

isOpaque​()

boolean

If this component is fully opaque, returns true.

paint​(Graphics g)

void

Called by Swing to draw components.

paintBorder​(Graphics g)

protected void

Paints the border of the component.

paintChildren​(Graphics g)

protected void

Paints the children of the component.

print​(Graphics g)

void

To print the component to the designated Graphics, use this technique.

printAll​(Graphics g)

void

Use this method to print the component.

setBackground​(Color bg)

void

Defines the color of this component's background.

setBorder​(Border border)

void

Sets the border of this component.

setFont​(Font font)

void

Determines the font for this element.

setForeground​(Color fg)

void

Fix the foreground color of this component.

setVisible​(boolean aFlag)

void

It points whether the component is visible or not visible.

setActionMap(ActionMap am)

void

The ActionMap is set to am.

setMaximumSize(Dimension maximumSize)

void

It sets this component's maximum size to a fixed number.

setMinimumSize(Dimension maximumSize)

void

It sets this component's minimum size to a constant value.

The methods supported my JComponent are inherited from the classes:

  • java.awt.Component
  • java.awt.Container
  • java.lang.Object

Example of Java JComponent

Let us have a look at a simple example to demonstrate the use of JComponent easily.

Below is the Example of Java JComponent:

Java
// Java code to implement the basic use of JComponent class import java.awt.*; import javax.swing.*; import javax.swing.JComponent; public class Component extends JComponent {     // Override the paintComponent method     protected void paintComponent(Graphics g)     {         // Call paintComponent from parent class         super.paintComponent(g);          // Draw a square         g.setColor(Color.BLUE);         g.fillRect(20, 20, 50, 50);         g.setColor(Color.BLACK);         g.drawString("Square", 30, 100);          // Draw a circle         g.setColor(Color.RED);         g.fillOval(90, 20, 50, 50);         g.setColor(Color.BLACK);         g.drawString("Circle", 100, 100);          // Draw a triangle         int xPoints[] = { 150, 200, 250 };         int yPoints[] = { 20, 70, 20 };         g.setColor(Color.GREEN);         g.fillPolygon(xPoints, yPoints, 3);         g.setColor(Color.BLACK);         g.drawString("Triangle", 170, 100);     }      // Main Method     public static void main(String[] args)     {          // Create a frame         JFrame f = new JFrame("JComponent Example");         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          // Create object of component class         Component customComponent = new Component();         f.add(customComponent);          // Set properties of frame         f.setSize(300, 200);         f.setVisible(true);     } } 

Output of JComponent Example:

JComponent Example

Explanation of the above Program:

In the above code, we have created a class named Component which extends the JComponent class. The paintComponent() method is overridden in the class. Swing calls this method automatically in order to render custom visuals. This method's creates a green triangle, a red circle, and a blue square on the component. The main method instantiates an object of the Component class, adds it to the frame, and creates a JFrame. It also sets its properties, including the title and closing operation.

Demo GIF showing the Execution of the above Program:

Output of JComponent-Example


Next Article
Java JCheckBoxMenuItem

A

abhinav_m22
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Advance Java
  • java-swing
  • Geeks Premier League 2023
Practice Tags :
  • Java

Similar Reads

  • Java JOptionPane
    In Java, JOptionPane is a part of the Java Swing library. It helps us to create dialog boxes such as message dialogs, conformation dialogs, input dialogs, and options dialogs In this article, we are going to explore some constructors, methods, and some examples of JOptionPane. Constructors of JOptio
    5 min read
  • Java JRootPane
    In Java Swing, JRootPane is a fundamental component that serves as the root container for creating complex user interfaces. It encapsulates the core functionality of a top-level window, like JFrame, and provides a structure for organizing the content within a GUI application. In Java JRootPane is a
    3 min read
  • Java JCheckBoxMenuItem
    Java JCheckBoxMenuItem is a GUI component in Swing that extends the JMenuItem class. It represents a Menu item with a checkbox that can be checked or unchecked. JCheckBoxMenuItem is often used in menu systems to allow users to toggle options. In this article, we are going to explore some constructor
    4 min read
  • Java JEditorPane
    A JEditorPane is a component in Java Swing that provides a simple way to display and edit HTML and RTF (Rich Text Format) content. It is a versatile component that allows you to display styled text, links, and images, making it useful for creating simple web browsers, rich-text editors, and content
    3 min read
  • Java Operators
    Java operators are special symbols that perform operations on variables or values. These operators are essential in programming as they allow you to manipulate data efficiently. They can be classified into different categories based on their functionality. In this article, we will explore different
    15 min read
  • Java JViewport
    Swing is a Java GUI (Graphical User Interface) toolkit that includes many components and tools for developing dynamic and user-friendly desktop applications. JViewPoint is majorly used for arranging and displaying large or scrollable content. What is a JViewPort?JViewport is mostly used to give a wi
    5 min read
  • Java JTextPane
    In Java, JTextPane is a versatile component that is part of the Swing library for building graphical user interfaces. It extends JEditorPane and provides an editable text component with rich text formatting capabilities. JTextPane allows you to display and edit styled text, making it suitable for im
    3 min read
  • Java JFrame
    Thе Java JFramе is an essential componеnt of Java Swing, which is a part of thе Java SWT(Standard Widgеt Toolkit). JFrame in Java is a class that allows you to crеatе and manage a top-lеvеl window in a Java application. It sеrvеs as thе main window for GUI-basеd Java applications and providеs a plat
    4 min read
  • Java JDesktopPane
    Java JDesktopPane is a part of the Swing library that helps Java Developers to make desktop-like applications, It allows the developers to manage and organize child frames within a parent frame. In this article, we are going to see some constructors, methods, fields, and some examples of JDesktopPan
    4 min read
  • Java Tokens
    In Java, Tokens are the smallest elements of a program that is meaningful to the compiler. They are also known as the fundamental building blocks of the program. Tokens can be classified as follows: KeywordsIdentifiersConstants/LiteralsOperatorsSeparators1. KeywordKeywords are pre-defined or reserve
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences