Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(new TestPane());
        frame.setSize(100, 100);
        frame.setVisible(true);
    }
}

class TestPane extends JPanel {
    String text = "Hello";
    JLabel label;
    int charIndex = 0;

    public TestPane() {
        setLayout(new GridBagLayout());
        label = new JLabel();
        add(label);
        Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String labelText = label.getText();
                labelText += text.charAt(charIndex);
                label.setText(labelText);
                charIndex++;
                if (charIndex >= text.length()) {
                    ((Timer) e.getSource()).stop();
                }
            }
        });
        timer.start();
    }
}