2、下图利用多线程, 实现了一个JLable(图标)在JFrame窗口中从左向右移动。 请修改该程序(将JFrame加高),实现以下功能的改进: (1)该图标从左向右平移, 到达右边界后,转向下移动; (2)到达下边界后, 转向左平移 (3)到达左边界后转向上移动, 如此循环。
时间: 2024-02-23 13:00:11 浏览: 18
以下是修改后的程序,实现了要求的功能:
```java
import javax.swing.*;
import java.awt.*;
public class MovingIcon extends JPanel implements Runnable {
private ImageIcon icon;
private int x, y, direction;
public MovingIcon() {
icon = new ImageIcon("icon.png");
x = 0;
y = 0;
direction = 0;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
icon.paintIcon(this, g, x, y);
}
public void run() {
while (true) {
switch (direction) {
case 0:
x += 5;
if (x >= getWidth() - icon.getIconWidth()) {
x = getWidth() - icon.getIconWidth();
direction = 1;
}
break;
case 1:
y += 5;
if (y >= getHeight() - icon.getIconHeight()) {
y = getHeight() - icon.getIconHeight();
direction = 2;
}
break;
case 2:
x -= 5;
if (x <= 0) {
x = 0;
direction = 3;
}
break;
case 3:
y -= 5;
if (y <= 0) {
y = 0;
direction = 0;
}
break;
}
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Moving Icon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400); // 修改窗口高度
MovingIcon icon = new MovingIcon();
frame.getContentPane().add(icon);
frame.setVisible(true);
Thread thread = new Thread(icon);
thread.start();
}
}
```
修改的关键是在 `run` 方法中,通过 `direction` 变量来控制移动方向。当移动到边界时,修改 `direction` 变量的值,从而改变移动方向。同时,要根据窗口高度和图标大小来计算边界位置。