Table of Contents
How does repaint work in Java?
Examples to Implement repaint Method in Java
Example #2
Conclusion
Home Java javaTutorial repaint in Java

repaint in Java

Aug 30, 2024 pm 03:38 PM
java

The repaint method in java is available in java.applet.Applet class is a final method used whenever we want to call update method along with the call to paint method; call to update method clears the current window, performs an update, and afterwards calls paint method.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Syntax:

package <packagename>;
// class extending applet
public class <classname> extends Applet{
public method <methodName>(<arguments>){
repaint();             // calling repaint method when required
}
}
Copy after login

The above syntax shows how a repaint method is used in java. The repaint method is a part of the java.applet.Applet class, and it cannot be overridden. Therefore repaint method can be directly called from a class extending Applet or its subclasses.

How does repaint work in Java?

The repaint method is a final method available in the Applet class, and that’s why it cannot be overridden. Whenever the repaint method is to be used, it should be directly called from the Applet class’s subclasses. The repaint method is responsible for handling update to the paint cycle of the applet. Whenever we want a component to repaint itself, we need to call the repaint method. In case we have made changes to the appearance of a component but have not made any changes to its size, then we can call the repaint method to update the new appearance of the component on the graphical user interface. The repaint method is an asynchronous method of applet class. When call to repaint method is made, it performs a request to erase and perform redraw of the component after a small delay in time.

Whenever the repaint method is invoked from a component, a request is sent to the graphical user interface, which communicates to the graphical user interface to perform some action at a future instance of time. The whole idea behind the repaint method is to avoid the call to paint () method directly.

Examples to Implement repaint Method in Java

Now we will see some java examples showing the use of the repaint method:

Example #1

Here is an example showing how the repaint method is used in java:

Code:

package com.edubca.repaintdemo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.applet.Applet;
// class extending applet component and implementing mouse event listener
public class RepaintDemo extends Applet implements MouseListener {
private Vector vector;
public RepaintDemo() {
vector = new Vector();
setBackground(Color.red);
addMouseListener(this);
}
public void paint(Graphics graphics) { // paint method implementation
super.paint(graphics);
graphics.setColor(Color.black);
Enumeration enumeration = vector.elements();
while(enumeration.hasMoreElements()) {
Point p = (Point)(enumeration.nextElement());
graphics.drawRect(p.x-20, p.y-20, 40, 40);
}
}
public void mousePressed(MouseEvent mouseevent) {
vector.add(mouseevent.getPoint());
repaint(); // call repaint() method
}
public void mouseClicked(MouseEvent mouseevent) {}
public void mouseEntered(MouseEvent mouseevent) {}
public void mouseExited(MouseEvent mouseevent) {}
public void mouseReleased(MouseEvent mouseevent) {}
public static void main(String args[]) {
JFrame frame = new JFrame(); // creating a jFrame object
frame.getContentPane().add(new RepaintDemo());      // Adding Window
frame.setTitle("Repaint Method Demo");       // set title of the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(375, 250);    // set size of window
frame.setVisible(true);        // set window as visible
}
}
Copy after login

Output: 

repaint in Java

After the mouse click event is performed, the following shapes will be visible with a black color border. Note that this is done through the repaint method, which calls the update and then paints method, due to which we are able to see visible shapes immediately after click event is performed.

repaint in Java

Example #2

To provide more clarity about the use of the repaint method, here is another example:

Code:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.applet.Applet;
import java.awt.Graphics;
// class extending
public class RepaintDemo extends Applet  {
int test=2;
public void paint(Graphics graphics)
{
super.paint(graphics);
setBackground(Color.cyan);   // set backgroung color of window
graphics.setColor(Color.black);   // set color of Text appearing on window
graphics.drawString("Value of Variable test = "+test, 80, 80);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex){}
// increasing value of variable by 1 and update its value of GUI
test++;
repaint();
}
}
Copy after login

Output:

repaint in Java

In the above example, we have an applet and a variable called test is declared inside it. We are continuously incrementing the value of the variable test, and we want to ensure that the variable’s updated value is visible on the user interface. Therefore, we are using the repaint method that ensures to call update method before the paint method. The output of the above program. In this window value of the test, the variable is always incrementing, and the updated value is visible on GUI.

Conclusion

The above example provides a clear understanding of the repaint method and its function. We should call the repaint method when we want the applet’s update and paint cycle to be invoked. The calling repaint method performs an immediate update to the look and appearance of a component.

The above is the detailed content of repaint in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles