java - 单击时尝试获取 JButton 的坐标
问题描述
我正在使用以下代码来创建 JButton 网格并在单击时更改它们的颜色。我想做的下一步是能够将此网格与其他类似的网格进行比较。我一直试图在单击时获取 JButton 的坐标 (x, y),但一直无法找到这样做的方法。提前感谢您的帮助!
public class ButtonGrid {
JFrame frame = new JFrame(); //creates frame
JButton[][] grid; //names the grid of buttons
HashMap<JButton, String> state;
static int WIDTH = 8;
static int LENGTH = 8;
public ButtonGrid(int width, int length) { //constructor
frame.setLayout(new GridLayout(width,length)); //set layout
grid = new JButton[width][length]; //allocate the size of grid
state = new HashMap<JButton, String>();
for(int y = 0; y < length; y++) {
for(int x = 0; x < width; x++) {
final JButton nb = new JButton();//new ButtonColor; //creates a button
nb.setPreferredSize(new Dimension(50, 50));
grid[x][y] = nb;
state.put(grid[x][y], "blank");
nb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(state.get(nb).equals("blank"))
mapButtonToColor(nb, "red");
else if(state.get(nb).equals("red"))
mapButtonToColor(nb, "blank");
setButtonColors();
}
});
frame.add(grid[x][y]); //adds new button to grid
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
public static void main(String[] args) {
new ButtonGrid(WIDTH, LENGTH);
}
public void mapButtonToColor(JButton b, String c) {
state.put(b, c);
}
public void setButtonColors() {
for(JButton b : state.keySet()) {
Color c = state.get(b).equals("red") ? Color.black : Color.white;
b.setBackground(c);
}
}
}
解决方案
你不能只实现一个 MouseListener 吗?
yourButton.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
System.out.println(x+","+y);
}
});
只要单击按钮,就可以获取坐标,这应该可以满足您的需求。您还可以在 JFrame 组件上设置侦听器以查找每次点击的坐标(如果需要)。
推荐阅读
- azure - Azure VM 在计划时间之前备份或时间不正确
- javascript - 如何在同一个元素上进行多次点击事件?
- react-native - Flatlist ref 值(如 scrollToEnd)抛出它不是函数的错误
- ios - 多个命令产生错误 GTMSession
- angular - 从 FormData 中提取数据
- python - 如何在 Python 中从 SQL 查询中获取数据
- python - PySpark:查找项目是否在前 5 名中
- javascript - 按键映射对象数组
- java - 来自servlet请求的输入流的线程问题
- postman - Postman - 如何在 POST 多部分/表单数据请求中嵌入文件作为 base64 字符串?