gpt4 book ai didi

java - 我在 GridLayout 中获取按钮的 X 和 Y 索引的方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:06:03 24 4
gpt4 key购买 nike

这与 How to get X and Y index of element inside GridLayout? 有关帖子及其答案。

无论出于何种原因,他们都没有建议扩展 JButton 以包含其在网格和相关按钮数组中的位置。

我制作了下图,简单地显示了按钮被点击时的坐标。

扩展JButton:

package buttons_array;

import javax.swing.*;

@SuppressWarnings("serial")
public class ButtonWithCoordinates extends JButton {

int coordX;
int coordY;

public ButtonWithCoordinates(String buttonText, int coordX, int coordY) {
super(buttonText);
this.coordX = coordX;
this.coordY = coordY;
}

/**
* @return the coordX
*/
public int getCoordX() {
return coordX;
}

/**
* @return the coordY
*/
public int getCoordY() {
return coordY;
}
}

示例图形用户界面:

package buttons_array;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonsArray implements ActionListener {

private ButtonWithCoordinates buttons[][];
private int nRows;
private int nCols;

private JFrame frame;
private JPanel panel;

public ButtonsArray(int x, int y) {
if (x > 0 && y > 0) {
nRows = x;
nCols = y;
buttons = new ButtonWithCoordinates[nRows][nCols];
for (int i=0; i < nRows; ++i) {
for (int j=0; j < nCols; ++j) {
buttons[i][j] = new ButtonWithCoordinates(" ", i, j);
buttons[i][j].addActionListener(this);
}
}
} else {
throw new IllegalArgumentException("Illegal array dimensions!!!");
}
}

@Override
public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub
ButtonWithCoordinates button = (ButtonWithCoordinates) e.getSource();
button.setText(button.getCoordX() + ", " + button.getCoordY());

}

public void GUI() {

if (buttons == null) { throw new NullPointerException("Array is not initialized!!!"); }

frame = new JFrame();
panel = new JPanel();

frame.setContentPane(panel);
panel.setLayout(new GridLayout(nRows, nCols));
for (int i=0; i < nRows; ++i) {
for (int j=0; j < nCols; ++j) {
panel.add(buttons[i][j]);
}
}

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new ButtonsArray(3, 5).GUI();
}
});

}

}

现在我的问题:

  1. 我在这里重新发明了轮子吗?我的意思是,有没有更直接的方法来实现同样的目标?

  2. 每次我们需要查找坐标时,它在任何方面都比搜索数组差吗?

最佳答案

原文versionexample使用的扩展名:

GridButton extends JButton

更新的version是基于所见的座谈会 here .虽然扩展在某些情况下可能是合适的,但提到了一些替代方案 here ;客户属性(property)特别方便。从网格坐标中识别按钮也很容易:

private static final int N = 5;
List<JButton> list = new ArrayList<>();

private JButton getGridButton(int r, int c) {
int index = r * N + c;
return list.get(index);
}

关于java - 我在 GridLayout 中获取按钮的 X 和 Y 索引的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21346281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com