Java Code for Moving Text | Applet | Thread
Before reading this article you need to know the Java Applet Basics and Java.lang.Thread class in Java .
In this article we shall be explaining the code to display moving text in Java. To print the string in the window we will use the drawString() method from java.awt package. The drawString method takes three arguments :
drawString(string, x, y)
- string : This parameter takes the string to be displayed.
- x : This parameters takes the x co-ordinates where the string will be displayedon the screen.
- y : This parameter takes the y co-ordinates where the string will be displayed
on the screen.
We will be printing the string at (x, y) co-ordinates and then update the x co-ordinate and then repaint the screen again.
import java.awt.*;
import java.applet.*;
public class GFG extends Applet implements Runnable {
private String display;
private int x, y, flag;
Thread t;
public void init()
{
display = "GeeksforGeeks" ;
x = 100 ;
y = 100 ;
flag = 1 ;
t = new Thread( this , "MyThread" );
t.start();
}
public void update()
{
x = x + 10 * flag;
if (x > 300 )
flag = - 1 ;
if (x < 100 )
flag = 1 ;
}
public void run()
{
while ( true ) {
repaint();
update();
try {
Thread.sleep( 1000 );
}
catch (InterruptedException ie) {
System.out.println(ie);
}
}
}
public void paint(Graphics g)
{
g.drawString(display, x, y);
}
}
|
Output :
Note: The above function are a part of java.awt package and belongs to java.awt.Graphics class. Also, these codes might not run in an online compiler please use an offline compiler. The x and y coordinates can be changed by the programmer according to their need.
Last Updated :
06 Jun, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...