Ich möchte Text innerhalb von JPanel wie ein Quadrat verschieben. Ich kann den Text vom oberen Bedienfeld verschieben, aber ich kann ihn nicht nach oben verschieben, wo er beginnt.
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);
}
}
}
Antworten:
1 für die Antwort № 1Sie können dies verwenden move
Methode:
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;
}
Wenn Sie die Größe der Komponente ändern, wird die Bewegung gestoppt, aber Sie haben nichts angegeben, sodass dies das tut, was Sie wollten.
Überschreiben Sie auch paintComponent
Anstatt von paint
.