Java 检查每个按钮的位置
我有一个包含81个按钮的框架,假设所有按钮都不包含名称,大小都相等,并且都是自动设置的。所以,当我点击一个我想知道哪一个是点击。如果我使用一个实现MouseListener并使用此方法的类Java 检查每个按钮的位置,java,user-interface,button,Java,User Interface,Button,我有一个包含81个按钮的框架,假设所有按钮都不包含名称,大小都相等,并且都是自动设置的。所以,当我点击一个我想知道哪一个是点击。如果我使用一个实现MouseListener并使用此方法的类 mouseClicked(MouseEvent e){ temp[0]= e.getX(); temp[1]= e.getY(); } 我怎样才能用这些坐标检查? 我是否必须为每个按钮设置其自己的位置才能执行此操作 我相信这就是你想要的 public static final int BUTTONS
mouseClicked(MouseEvent e){
temp[0]= e.getX();
temp[1]= e.getY();
}
我怎样才能用这些坐标检查?
我是否必须为每个按钮设置其自己的位置才能执行此操作 我相信这就是你想要的
public static final int BUTTONS_WIDTH_COUNT = 9;
public static final int BUTTONS_HEIGHT_COUNT = 9;
public static final Button[][] BUTTONS = new Button[BUTTONS_WIDTH_COUNT][BUTTONS_HEIGHT_COUNT]
...
// I'll assume that the buttons are taking up the entire frame so no offsets are taken into account
frame.addMouseListener(
new MouseAdaptor() {
mouseClicked(MouseEvent e) {
// The X Y coordinates are relative to the component so
int frameWidth = frame.getBounds().getWidth();
int frameHeight = frame.getBounds().getHeight();
Button buttonClicked = buttons[e.getX()/(frameWidth/BUTTONS_WIDTH_COUNT)][e.getY()/(frameHeight/BUTTONS_HEIGHT_COUNT)];
}
}
编辑:事实上,最好将相同的鼠标捕捉器分配给所有按钮,并使用
e.getSource()
来知道侦听器中调用了哪个按钮。我相信这就是您要寻找的
public static final int BUTTONS_WIDTH_COUNT = 9;
public static final int BUTTONS_HEIGHT_COUNT = 9;
public static final Button[][] BUTTONS = new Button[BUTTONS_WIDTH_COUNT][BUTTONS_HEIGHT_COUNT]
...
// I'll assume that the buttons are taking up the entire frame so no offsets are taken into account
frame.addMouseListener(
new MouseAdaptor() {
mouseClicked(MouseEvent e) {
// The X Y coordinates are relative to the component so
int frameWidth = frame.getBounds().getWidth();
int frameHeight = frame.getBounds().getHeight();
Button buttonClicked = buttons[e.getX()/(frameWidth/BUTTONS_WIDTH_COUNT)][e.getY()/(frameHeight/BUTTONS_HEIGHT_COUNT)];
}
}
编辑:实际上,最好将同一个MouseAdaptor分配给所有按钮,并使用
e.getSource()
来知道侦听器中调用的是哪个按钮。非常好的答案,谢谢。我会给你一个+1,但我不能,因为我还没有足够的代表:(没问题。我认为你仍然可以“批准”作为原始海报的答案。令人惊讶的答案,谢谢。我会给你一个+1,但我不能,因为我还没有足够的代表:(没问题。我认为你仍然可以“批准”作为原始海报的答案。