嗨,我是新来的,我不擅长解释问题,但我已经在网上搜索了很多年。这是我的问题:我想在鼠标 x 和 y 处绘制一个矩形。我希望有很多矩形,所以如果我要单击 JFrame 上的 50 ,50 坐标,它将绘制一个矩形,然后如果我单击其他地方,它将在那里绘制另一个矩形,但不会删除另一个矩形,所以我本来可以点击 5 次(<--example),然后我会同时拥有五个矩形。请帮助我并使其尽可能简单。提前谢谢你,请帮助我。
我的代码:
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public boolean running = false;
public static final String title = "tilebased game!";
private Thread thread;
public int height = 600;
public int width = 800;
private Dimension d = new Dimension(width, height);
public static Rectangle block;
public static Rectangle[] blocks = new Rectangle[2];
public static int blocknum = 0;
public static int xCreate;
public static int yCreate;
public static int xcoord;
public static int ycoord;
public Game() {
setPreferredSize(d);
setMinimumSize(d);
setMaximumSize(d);
addMouseListener(new tile());
addMouseMotionListener(new tile());
}
public void start() {
running = true;
new Thread(this).start();
}
public void stop() {
running = false;
}
public static void main(String[] args) {
Game g = new Game();
JFrame f = new JFrame();
f.add(g);
f.pack();
f.setTitle(title);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
g.start();
}
public void run() {
while(running){
tick();
render();
}
try{
Thread.sleep(5);
}catch(Exception e){
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(2);
return;
}
Graphics g = bs.getDrawGraphics();
tile.render(g);
g.dispose();
bs.show();
}
public void tick() {
}
}
和另一个实现MouseListener
and的类MouseMotionListener
:
public class listener implements MouseListener, MouseMotionListener {
public static Game game;
public Image img;
@Override
public void mouseDragged(MouseEvent arg0) {
}
@Override
public void mouseMoved(MouseEvent e) {
Game.xcoord = e.getX();
Game.ycoord = e.getY();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
}
}
}
这是对我的问题的补充。什么与我的代码兼容。(顺便说一句,我仍然只是在学习 java,我只有 13 岁,而且不是很聪明。)矩形也应该有固定的高度和宽度,所以当你点击一个特定区域时,它会绘制一个 10 x 10矩形,它会记住你的例子中已经绘制的所有其他矩形,请再次帮助我,谢谢