首页 > 解决方案 > 单击时尝试获取 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);
    }
  }
}

标签: java

解决方案


你不能只实现一个 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 组件上设置侦听器以查找每次点击的坐标(如果需要)。


推荐阅读