检查每个按钮的位置
Check location of each button
我有一个包含 81 个按钮的框架,假设所有按钮都没有名称,大小都相等,并且都是自动设置的。所以当我点击一个时,我想知道点击了哪个。如果我使用实现 MouseListener 的 class 并使用此方法
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)];
}
}
编辑: 实际上,将相同的 MouseAdaptor 分配给所有按钮并使用 e.getSource()
知道哪个按钮在侦听器中调用会更好。
我有一个包含 81 个按钮的框架,假设所有按钮都没有名称,大小都相等,并且都是自动设置的。所以当我点击一个时,我想知道点击了哪个。如果我使用实现 MouseListener 的 class 并使用此方法
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)];
}
}
编辑: 实际上,将相同的 MouseAdaptor 分配给所有按钮并使用 e.getSource()
知道哪个按钮在侦听器中调用会更好。