Java图形界面里怎么让一个黑色的矩形在白底的窗口里面朝一个方向移动

最好能粘贴代码,大神们求教,谢谢啦!
2025-02-23 22:01:43
推荐回答(1个)
回答1:

最简单的就是用Timer去控制,每次重绘界面,下面给你代码。

如果多个矩形一起动,就要用多线程,每个线程控制一个矩形

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class Main extends JPanel implements ActionListener{
private static final long serialVersionUID = 737057843348492270L;

Timer timer = new Timer(20, this);
int x, y;

public Main() {
x = 0; y = 90;
this.setPreferredSize(new Dimension(300, 200));
timer.start();
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, 300, 200);
g.setColor(Color.BLACK);
g.drawRect(x, y, 40, 20);
g.dispose();
}

@Override
public void actionPerformed(ActionEvent arg0) {
x = (x + 1) % 300;
repaint();
}

public static void main(String[] args) {
Main panel = new Main();
JFrame frm = new JFrame("demo");
frm.add(panel);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.pack();
frm.setVisible(true);
    }
}