所以基本上我在玩图形和一堆有趣的东西,在制作游戏之前我想知道如何使用不同的循环来做一些有趣的事情,但我不知道如何使用INT 我在mouseMoved 方法中制作,然后在Graphics 方法中使用它。该代码可能会显示一个更好的示例来说明我要解释的内容。
package com.martin;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.*;
public class Grids extends JFrame implements MouseMotionListener {
JPanel p = new JPanel();
public int width = 1200;
public int height = 800;
public Grids() {
addMouseMotionListener(this);
windowLoader();
}
public static void main(String[] args){
new Grids();
}
public void windowLoader() {
setPreferredSize(new Dimension(width, height));
setMaximumSize(new Dimension(width, height));
setMinimumSize(new Dimension(width, height));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
// setBackground(Color.BLACK);
p.setSize(width, height);
p.setOpaque(false);
// p.setBackground(Color.BLACK);
add(p);
pack();
setVisible(true);
}
public void mouseMoved(MouseEvent e) {
double mouseX = e.getX();
double mouseY = e.getY();
}
public void mouseDragged(MouseEvent e) {
}
public void paint(Graphics g) {
Random rand = new Random();
int cols, rows;
int size = 8;
Color color;
for (rows = 0; rows < width; rows++) {
for (cols = 0; cols < height; cols++) {
color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
// g.setColor(color);
// g.fillRect(rows * size, cols * size, size, size);
// g.drawRect(rows * size, cols * size, size, size);
// g.drawLine(rows * size, cols * size, size, size);
// g.drawRoundRect(rows * size, cols * size, size, size, 10, 10);
// g.fillRoundRect(rows * size, cols * size, size, size, 10, 10);
}
}
// int x = 0;
// int y = 0;
// int spacing = rand.nextInt(20) + 1;
//
// while (spacing > -1) {
// spacing = spacing + rand.nextInt(20);
// }
//
// while (x < width) {
// g.drawLine(x, 0, x, height);
// x = x + spacing;
// }
// while (y < height) {
// g.drawLine(0, y, width, y);
// y = y + spacing;
// }
// Point mouseL = MouseInfo.getPointerInfo().getLocation();
// double mouseX = mouseL.getX();
// double mouseY = mouseL.getY();
int x = 0, y = 0;
//Can't access the int from the mouseMoved I get red underline for error (variable cannot be found)
while (x < width) {
if (mouseX < 1) {
x = x + 10;
} else {
x = x + (int)mouseX;
}
while (y < height) {
if (mouseY < 1) {
y = y + 10;
} else {
y = y + (int)mouseY;
}
g.fillRoundRect(x, y, 10, 10, 10, 10);
}
}
repaint();
}
}
这是整个代码,我尝试使用 MouseInfo 来获取指针位置,但它获取 JFrame 组件的位置,我想在 JFrame 本身而不是组件之外获取鼠标位置。