我正在嘗試在網格佈局中使用JLabels實現一個小網格框。 這個想法是,當你點擊一個特定的框時,X和Y座標在控制檯窗口上顯示。我有這個到目前爲止,我相信它幾乎在那裏,但是當我點擊每個框不正確的數字出現在窗口中。例如,當我點擊應讀取的框(0,0)時,它會給我16,17 ...?任何幫助將是偉大的!謝謝。網格X和Y座標中的可點擊JLabels?
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){}
}
}