单击时尝试获取JButton的坐标

时间:2018-05-03 20:55:46

标签: java

我使用以下代码创建JButtons网格并在点击时更改其颜色。我想要做的下一步是能够将此网格与其他网格进行比较。点击后,我一直试图获取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);
    }
  }
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

也许这会对你有所帮助:

当在所述网格中按下按钮时,简单地迭代它以找到被点击的按钮,然后返回坐标,如下所示:

private class ButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){
        Object source = e.getSource();
        for(int i = 0;i< grid.length; i++){
            for(int j = 0;j < grid.length;j++){
                if(source == grid[i][j]){
                    JButton clicked == grid[i][j];
                    // do something with this 
                }
            }
        }
    }
}