0

i want to move text inside JPanel like square am able to move the text from the top panel but cant move it Up from where it starts.

import java.awt.*;
import javax.swing.*;
public class test extends JPanel {
    int x = 100;
    int y = 100;
    public void move() {
        if (x < getWidth() - 100 && y < getHeight() - 100) x = x + 1;
        if (x >= getWidth() - 100 && y < getHeight() - 100) y = y + 1;
        if (y >= getHeight() - 100) x = x - 1;
        if (x < 0) y = y - 1;
    }
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        move();
        g2d.setColor(Color.BLUE);
        g2d.drawString(" X =  " + x + " Y " + y, x, y);
    }
    public static void main(String args[]) throws InterruptedException {
        JFrame frame = new JFrame("Test Frame");
        test ts = new test();
        frame.setSize(400, 500);
        frame.add(ts);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        while (true) {
            ts.repaint();
            Thread.sleep(10);
        }
    }
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89

1 Answers1

1

You can use this move method:

public void move() {

    if (100 <= x && x < getWidth() - 100 && y == 100)
        x = x + 1;
    if (x == getWidth() - 100 && 100 <= y && y < getHeight() - 100)
        y = y + 1;
    if (100 < x && x <= getWidth() - 100 && y == getHeight() - 100)
        x = x - 1;
    if (x == 100 && 100 < y && y <= getHeight() - 100)
        y = y - 1;
}

Resizing the component will stop the movement, but you didn't specify anything about that, so this does what you wanted.

Also, override paintComponent instead of paint.

user1803551
  • 12,965
  • 5
  • 47
  • 74