如何获得GridLayout内部元素的X和Y指数?我正在学习一个java教程,并看到在GridLayout中查找JButton的x/y索引的方法是遍历一个与布局相关的二维按钮数组b,并检查b[i][j] == buttonReference. @Override
public void actionPerformed(ActionEvent ae) {
JButton bx = (JButton) ae.getSource();
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
if (b[i][j] == bx)
{
bx.setBackground(Color.RED);
}
}是否有更简单的方法来获取按钮的X/Y索引?类似于:JButton button = (JButton) ev.getSource();int x = this.getContentPane().getComponentXIndex(button);int y = this.getContentPane().
getComponentYIndex(button);this作为一个GameWindow实例ev当用户按下按钮时触发ActionEvent。在这种情况下,它应该得到:x=2,y=1@gameWindow.java:package javaswingapplication;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.*;import javax.swing.*;
public class GameWindow extends JFrame implements ActionListener{
JButton b[][] = new JButton[5][5];
int v1[] = { 2, 5, 3, 7, 10 };
int v2[] = { 3, 5, 6, 9, 12 };
public GameWindow(String title)
{
super(title);
setLayout(new GridLayout(5, 5));
setDefaultCloseOperation(EXIT_ON_CLOSE );
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
{
b[i][j] = new JButton();
b[i][j].addActionListener(this);
add(b[i][j]);
}
}
@Override
public void actionPerformed(ActionEvent ae) {
((JButton)ae.getSource()).setBackground(Color.red);
}}@JavaSwingApplication.java:package javaswingapplication;public class JavaSwingApplication {
public static void main(String[] args) {
GameWindow g = new GameWindow("Game");
g.setVisible(true);
g.setSize(500, 500);
}}
3 回答
MYYA
TA贡献1868条经验 获得超4个赞
JButton#setName(字符串); JBUtton#setActionCommand(String); JBUtton#setAction(行动);
添加回答
举报
0/150
提交
取消