Quiero mover el texto dentro de JPanel como un cuadrado. Puedo mover el texto desde el panel superior, pero no puedo moverlo hacia arriba desde donde comienza.
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);
}
}
}
Respuestas
1 para la respuesta № 1Puedes usar esto move
método:
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;
}
Cambiar el tamaño del componente detendrá el movimiento, pero no especificaste nada sobre eso, así que esto hace lo que querías.
Además, anular paintComponent
en lugar de paint
.