我正在尝试在网格布局中使用 JLabels 实现一个小的框网格。这个想法是,当您单击特定框时,X 和 Y 坐标将显示在控制台窗口上。到目前为止我有这个,我相信它几乎就在那里,但是当我点击每个框时,窗口中出现了不正确的数字。例如,当我单击应该显示为 (0,0) 的框时,它给了我 16,17...???任何帮助都会很棒!谢谢。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class GridPanel extends JPanel{
private final int HEIGHT = 7;
private final int WIDTH = 12;
private final int TOTAL_BOXES = HEIGHT * WIDTH;
JLabel box[];
public GridPanel()
{
setLayout(new GridLayout(7,12));
box = new JLabel[TOTAL_BOXES];
for (int x = 0;x<box.length;x++){
box[x] = new JLabel("");
box[x].setOpaque(true);
box[x].setPreferredSize(new Dimension(30,30));
box[x].setBackground(Color.white);
box[x].setBorder(BorderFactory.createLineBorder(Color.black));
box[x].addMouseListener(new mListener());
}
for (int x = 0;x<box.length;x++)
add(box[x]);
}
private class mListener implements MouseListener
{
public void mouseClicked(MouseEvent box)
{
int x = box.getX();
int y = box.getY();
System.out.println(x +"," + y);
}
public void mousePressed (MouseEvent e){}
public void mouseExited (MouseEvent e){}
public void mouseReleased (MouseEvent e){}
public void mouseEntered (MouseEvent e){}
}
}