大佬教程收集整理的这篇文章主要介绍了Java 如何获取GridLayout中元素的X和Y索引?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
你已经保存了所有Jbutton的数组;你可以搜索,ae.getsource()
并且拥有职位。
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if( b[i][j] == ae.getsource() ) {
// position i,j
}
}
}
我正在研究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,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);
}
}
以上是大佬教程为你收集整理的Java 如何获取GridLayout中元素的X和Y索引?全部内容,希望文章能够帮你解决Java 如何获取GridLayout中元素的X和Y索引?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。