AJ_Slip_1A

AJ_Slip_1A

Slip No.1

A) Write a java program to scroll the text from left to right and vice versa continuously.
    import javax.swing.*;
    import java.awt.*;

    public class ScrollingTextSimple extends JPanel {
    private String text = "Scrolling Text Example";
    private int xPos = 0;

    public ScrollingTextSimple() {
    Timer timer = new Timer(50, e -> moveText());
    timer.start();
    }

    private void moveText() {
    xPos += 5; // Move text to the right
    if (xPos > getWidth()) {
    xPos = -getTextWidth(); // Reset to start from the left
    }
    repaint();
    }

    private int getTextWidth() {
    FontMetrics metrics = getFontMetrics(getFont());
    return metrics.stringWidth(text);
    }

    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setFont(new Font("Arial", Font.PLAIN, 20));
    g.setColor(Color.BLACK);
    g.drawString(text, xPos, getHeight() / 2);
    }

    public static void main(String[] args) {
    JFrame frame = new JFrame("Scrolling Text");
    ScrollingTextSimple scrollingText = new ScrollingTextSimple();

    frame.add(scrollingText);
    frame.setSize(400, 100);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    }
    }

No comments:

Post a Comment