/ / Comment déplacer un texte comme un carré dans jPanel - java, swing

Comment déplacer un texte comme un carré dans jPanel - java, swing

Je veux déplacer du texte à l'intérieur de JPanel, comme un carré, je suis capable de déplacer le texte depuis le panneau supérieur, mais je ne peux pas le déplacer de là où il commence.

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);
}
}
}

Réponses:

1 pour la réponse № 1

Vous pouvez l'utiliser move méthode:

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;
}

Redimensionner le composant arrêtera le mouvement, mais vous n’avez rien spécifié à ce sujet, c’est ce que vous voulez.

En outre, remplacer paintComponent au lieu de paint.