【发布时间】:2021-10-14 04:28:40
【问题描述】:
问题: 我想获取鼠标相对于 JFrame 而不是屏幕的坐标。我正在使用带有 JPanel 数组的屏幕,当我单击它们时它们会改变颜色。我该怎么做?
我能找到的大多数解决方案都建议获取组件的坐标,但我不能这样做,因为这意味着它也会找到相对于每个 JPanel 的坐标?
代码:
public TestCoordinates() {
initComponents();
JPanel[][] arrGrid = new JPanel[3][4];
int tileColour = 0;
//nested for loops create the grid
for (int y = 0; y < 3; y++) {
tileColour++;
for (int x = 0; x < 4; x++) {
arrGrid[y][x] = new JPanel();
add(arrGrid[y][x]);
arrGrid[y][x].setBounds((x * 100) + 100, (y * 100) + 100, 100, 100);
arrGrid[y][x].setVisible(true);
//sets grid colour to alternating colours
tileColour++;
double tileColourDouble = tileColour;
double tileColour2 = tileColourDouble / 2;
arrGrid[y][x].setBackground(Color.cyan);
if ((tileColour2 == Math.floor(tileColour2)) && !Double.isInfinite(tileColour2)) {
arrGrid[y][x].setBackground(Color.green);
} else {
arrGrid[y][x].setBackground(Color.cyan);
}
//adds mouse listener
arrGrid[y][x].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int yCo = getRow(e.getLocationOnScreen().y - 100);
int xCo = getColumn(e.getLocationOnScreen().x - 100);
System.out.println(e.getLocationOnScreen());
System.out.println(yCo + ", " + xCo);
arrGrid[yCo][xCo].setBackground(Color.gray);
}
//converts screen location to single x-coordinate of clicked JPanel's y-coordinate
private int getRow(int y) {
int row = 0;
for (int i = 0; i < y / 100; i++) {
row++;
}
return row;
}
//converts screen location to single x-coordinate of clicked JPanel's x-coordinate
private int getColumn(int x) {
int column = 0;
for (int i = 0; i < x / 100; i++) {
column++;
}
return column;
}
});
}
}
}
【问题讨论】:
-
为什么不在框架中添加一个 MouseListener 呢?此侦听器仅用于获取 JFrame 上的鼠标信息。
-
某事like this 可能会为你做这件事
标签: java swing jframe jpanel mouselistener