java中grid什么意思_Java 如何获取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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值