Wednesday, April 14, 2021

[Java Code Sample] How to display text letter by letter on JTextArea

 

Just like some old school RPGs or adventure games, here’s how to display text letter by letter in Java.

Here's the video tutorial:



And here's the code:


import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
 
public class Main {
     
    JFrame window;
    JPanel textPanel;
    JTextArea textArea;
    Font normalFont = new Font("Times New Roman", Font.PLAIN, 28);
     
    String text;
    int i =0;
     
    Timer timer = new Timer(80, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
             
            char character[] = text.toCharArray();
            int arrayNumber = character.length;
             
            String s = String.valueOf(character[i]);
             
            textArea.append(s);
             
            i++;
     
            if(i == arrayNumber){
                i = 0;
                timer.stop();
            }
        }       
    });
     
 
    public static void main(String[] args) {
         
        new Main ();
    }
     
    public Main(){
         
        window = new JFrame();
        window.setSize(800, 600);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.getContentPane().setBackground(Color.black);
        window.setLayout(null);
         
        textPanel = new JPanel();
        textPanel.setBounds(100, 100, 600, 250);
        textPanel.setBackground(Color.black);
        window.add(textPanel);
         
        textArea = new JTextArea();
        textArea.setBounds(100, 100, 600, 250);
        textArea.setBackground(Color.black);
        textArea.setForeground(Color.white);
        textArea.setFont(normalFont);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textPanel.add(textArea);
         
        window.setVisible(true);
         
        text = "This is the text area. This game is going to be great. I'm sure of it!!!!!!!!!!";
         
        timer.start();
    }
}

end

No comments:

Post a Comment