16

我正在研究一个 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);
  }
}
4

7 回答 7

19

此示例说明如何创建一个知道其在网格上的位置的网格按钮。该方法getGridButton()显示了如何根据其网格坐标有效地获取按钮引用,并且动作侦听器显示单击和找到的按钮是相同的。

网格按钮面板

package gui;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @see http://stackoverflow.com/questions/7702697
 */
public class GridButtonPanel {

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

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

    private JButton createGridButton(final int row, final int col) {
        final JButton b = new JButton("r" + row + ",c" + col);
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JButton gb = GridButtonPanel.this.getGridButton(row, col);
                System.out.println("r" + row + ",c" + col
                    + " " + (b == gb)
                    + " " + (b.equals(gb)));
            }
        });
        return b;
    }

    private JPanel createGridPanel() {
        JPanel p = new JPanel(new GridLayout(N, N));
        for (int i = 0; i < N * N; i++) {
            int row = i / N;
            int col = i % N;
            JButton gb = createGridButton(row, col);
            list.add(gb);
            p.add(gb);
        }
        return p;
    }

    private void display() {
        JFrame f = new JFrame("GridButton");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(createGridPanel());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new GridButtonPanel().display();
            }
        });
    }
}
于 2011-10-09T21:31:02.540 回答
9

您已经保存了一个包含所有 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
    }
  }
}
于 2011-10-09T10:01:23.623 回答
6

来自 JButtons

  • JButton#setName(String);

  • JBUtton#setActionCommand(String);

  • JBUtton#setAction(Action);

从/到容器

SwingUtilities#convert...

SwingUtilities#getDeepestComponentAt

于 2011-10-09T10:30:16.750 回答
1

您可以在创建 JButton 时使用 setName() 将其位置(例如 button.setName(i+" "+j);) 存储在 JButton 中;然后,您可以通过在空间周围拆分从 button.getName() 获得的字符串来访问它。这不是一种特别有效的方法,但听起来有点像您正在(或现在)正在寻找的东西。

于 2013-04-25T16:13:31.567 回答
1

此解决方案选择所有对象之间的所有对象,例如他们
首先编写获取文本的方法或 Jbuuton 或 jlable 所需的一切或....代码下的第二次更改

public class Event_mouse implements MouseListener {

    @Override
    public void mouseReleased(MouseEvent e) {
        try {
            Everything source = (Everything) e.getSource();
             if(Everything.gettext==gol){

             }

        } catch (Exception ee) {
            JOptionPane.showMessageDialog(null, ee.getMessage());

    }

}
于 2016-10-09T10:51:37.617 回答
1

我认为有更好的方法,例如我创建了一个从 javax.swing 扩展 JButton 的新 JButton 类,我将其命名为 JButton2,然后我向它添加了 2 个新属性(xGridPos 和 yGridPos),如下所示:

private class JButton2 extends JButton{
    public int xGridPos;
    public int yGridPos;
}

当我创建一个新的 JButton2 时,我使用网格上的 x 和 y 位置设置了这个新属性,这样您就可以获得 x 和 y 并将它们与 getSource 和使用 cast 一起使用:

private class ListenerTest implements ActionListener{
    public void actionPerformed(ActionEvent theActionEvent){
        JButton2 theButton = (JButton2)actionE.getSource();
        // Use the xGridPos and yGridPos in section with theButton.xGridPos or
        // theButton.xGridPos
    }
}

我希望这会有所帮助:D。

于 2020-12-10T17:18:58.700 回答
0

您不需要按钮显式存储它们的 x,y 位置。考虑以下代码:

JComponent e=//something with GridLayout
var count=e.getComponentCount();
var row=count/11;//for example, you have an 11*11 grid
var col=count%11;
var bb=new JButton(row+" "+col);//or any other text you like
bb.addActionListener(unused->System.out.println(
    "pressed button "+count+ " in row="+row+" col="+col
    ));
this.add(bb);
于 2021-07-17T01:45:45.950 回答