Thursday, April 15, 2021

[Java Code Sample] Scrolling Text (Like end credit roll text)

 

Here's a sample code to create a scrolling/moving text just like ending credit roll text for video games or movies.


Video tutorial:



Code:




public class Main {

	public static void main(String[] args) {
		
		Screen screen = new Screen();
	}

}



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Screen extends JPanel implements ActionListener{
	
	Timer creditTimer = new Timer(5,this);
	String text;
	int textY = 600;	
	
	public Screen() {
		
		JFrame window = new JFrame("Credit Roll Test");
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setLocationRelativeTo(null);
		window.add(this);
		window.setVisible(true);
		this.setBackground(Color.black);
		
		text = "Congratulations!\n\n"
				+ "Story\n"
				+ "Yuji Horii\n\n"
				+ "Illustration\n"
				+ "Akira Toriyama\n\n"
				+ "Music\n"
				+ "Koichi Sugiyama\n\n\n\n\n\n\n\n\n\n\n\n\n"
				+ "Thank you for playing!";
		
		creditTimer.start();
	}
	
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		
		Graphics2D g2d = (Graphics2D)g;
		
		g2d.setFont(new Font("Times New Roman", Font.PLAIN, 28));
		g2d.setColor(Color.white);
		g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		
		int y = textY;
		
		for(String line : text.split("\n")) {
			
			int stringLength = (int)g2d.getFontMetrics().getStringBounds(line, g2d).getWidth();
			int x = getWidth()/2 - stringLength/2;
			g2d.drawString(line, x, y +=28);
		}	
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
		System.out.println(textY);
		
		textY--;
		if(textY < -320) {
			creditTimer.stop();
		}
		
		repaint();
	}

}


end


No comments:

Post a Comment