获取网格布局上按钮的位置 [英] get position of the button on gridlayout

查看:41
本文介绍了获取网格布局上按钮的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用网格布局获取单击按钮的位置(我的意思是行和列)?

public void init(最终容器窗格){JPanel 控件 = new JPanel();int size = (int) Math.sqrt(puzzle.getSize() + 1);control.setLayout(new GridLayout(size, size));for (int i = 0; i <拼图.getSize(); i++) {int k =拼图.getListItem(i);如果 (k == 拼图.getEmptyFlag())control.add(new JLabel(""));别的 {JButton jb = new JButton(String.valueOf(k));jb.addMouseListener(新鼠标适配器(){@覆盖public void mouseClicked(MouseEvent e) {//获取行和列}});控件.添加(jb);}}窗格.添加(控件);}

解决方案

  1. 切勿为此目的在 JButton 上添加 MouseListener.改用 ActionListener.
  2. 为什么不创建 JButton 的数组或 ArrayList,然后简单地遍历列表以找到合适的列表?

private JButton[][] buttonGrid = new JButton[ROWS][COLS];

在其他地方,您需要用可行的 JButton 对象填充网格并将这些 JButton 放入您的 GUI.

然后在程序中使用嵌套的 for 循环遍历网格,将网格按钮与 getSource() JButton 进行比较.

即在 JButton 的 ActionListener 中

public void actionPerformed(ActionEvent e) {for (int row = 0; row < ROWS; row++) {for (int col = 0; col 

<小时>

编辑
你问:

<块引用>

  1. 为什么?

因为它在很多情况下都不能正常工作.ActionListeners 已经构建为专门与 JButtons 和 JMenuItems 一起工作,并且具有使此功能运行良好且轻松的机制.例如,假设您决定让 JButton 仅在用户填充两个 JTextField 时启用,并且您使用 JButton 的 setEnabled(boolean enabled) 方法来执行此操作,禁用 JButton 不会停止MouseListener 无法工作,但它会停止 ActionListener.

<小时>

编辑 2

例如

import java.awt.GridLayout;导入 java.awt.event.ActionEvent;导入 java.awt.event.ActionListener;导入 javax.swing.*;公共类 ButtonGridEg 扩展 JPanel {私有静态最终 int ROWS = 8;private static final int COLS = ROWS;私有静态最终 int GAP = 5;私有 JButton[][] buttonGrid = new JButton[ROWS][COLS];公共 ButtonGridEg() {setLayout(new GridLayout(ROWS, COLS, GAP, GAP));ActionListener buttonListener = new ActionListener() {@覆盖公共无效动作执行(ActionEvent evt){JButton selectedBtn = (JButton) evt.getSource();for (int row = 0; row < buttonGrid.length; row++) {for (int col = 0; col < buttonGrid[row].length; col++) {如果(buttonGrid[row][col] == selectedBtn){System.out.printf("选定的行和列:%d %d%n", row, col);}}}}};for (int row = 0; row < buttonGrid.length; row++) {for (int col = 0; col < buttonGrid[row].length; col++) {String text = String.format("按钮 [%d, %d]", row, col);buttonGrid[row][col] = new JButton(text);buttonGrid[row][col].addActionListener(buttonListener);添加(buttonGrid[row][col]);}}}私有静态无效 createAndShowGui() {ButtonGridEg mainPanel = new ButtonGridEg();JFrame frame = new JFrame("ButtonGridEg");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.getContentPane().add(mainPanel);框架.pack();frame.setLocationByPlatform(true);frame.setVisible(true);}公共静态无效主(字符串 [] args){SwingUtilities.invokeLater(new Runnable() {公共无效运行(){createAndShowGui();}});}}

How to get position(I mean row and column) of the clicked button with gridlayout?

public void init(final Container pane) {
    JPanel controls = new JPanel();
    int size = (int) Math.sqrt(puzzle.getSize() + 1);
    controls.setLayout(new GridLayout(size, size));
    for (int i = 0; i < puzzle.getSize(); i++) {
        int k = puzzle.getListItem(i);
        if (k == puzzle.getEmptyFlag())
            controls.add(new JLabel(""));
        else {
            JButton jb = new JButton(String.valueOf(k));
            jb.addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    //get row and column
                }

            });
            controls.add(jb);
        }
    }
    pane.add(controls);
}

解决方案

  1. Never add a MouseListener on a JButton for that purpose. Use an ActionListener instead.
  2. Why not create an array or ArrayList of JButton and then simply iterate through the list to find the proper one?

i.e.,

private JButton[][] buttonGrid = new JButton[ROWS][COLS];

Elsewhere you will need to fill the grid with viable JButton objects and place those JButtons into your GUI.

Then later in program use a nested for loop iterating through the grid comparing the grid button with the getSource() JButton.

i.e. in the JButton's ActionListener

public void actionPerformed(ActionEvent e) {
  for (int row = 0; row < ROWS; row++) {
    for (int col = 0; col < COLS; col++) {
       if buttonGrid[row][col] == e.getSource();
       // here you have your row and column
    }
  }
}


Edit
You ask:

  1. why?

Because it won't work correctly in many situations. ActionListeners have been built to work specifically with JButtons and JMenuItems and have mechanisms that make this function work well l and easily. For example, say you decide to have a JButton that is only enabled once the user has filled two JTextFields, and you use the JButton's setEnabled(boolean enabled) method to do this, disabling the JButton will not stop the MouseListener from working, but it will stop the ActionListener.


Edit 2

For example,

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class ButtonGridEg extends JPanel {
   private static final int ROWS = 8;
   private static final int COLS = ROWS;
   private static final int GAP = 5;
   private JButton[][] buttonGrid = new JButton[ROWS][COLS];

   public ButtonGridEg() {
      setLayout(new GridLayout(ROWS, COLS, GAP, GAP));

      ActionListener buttonListener = new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent evt) {
            JButton selectedBtn = (JButton) evt.getSource();
            for (int row = 0; row < buttonGrid.length; row++) {
               for (int col = 0; col < buttonGrid[row].length; col++) {
                  if (buttonGrid[row][col] == selectedBtn) {
                     System.out.printf("Selected row and column: %d %d%n", row, col);
                  }
               }
            }
         }
      };
      for (int row = 0; row < buttonGrid.length; row++) {
         for (int col = 0; col < buttonGrid[row].length; col++) {
            String text = String.format("Button [%d, %d]", row, col);
            buttonGrid[row][col] = new JButton(text);
            buttonGrid[row][col].addActionListener(buttonListener);
            add(buttonGrid[row][col]);
         }
      }
   }

   private static void createAndShowGui() {
      ButtonGridEg mainPanel = new ButtonGridEg();

      JFrame frame = new JFrame("ButtonGridEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

这篇关于获取网格布局上按钮的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆