得到网格布局按钮的位置 [英] get position of the button on gridlayout

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

问题描述

如何获得位置(我的意思是行和列)与GridLayout的点击的按钮呢?

 公共无效的init(最终容器窗格){
    JPanel的控制=新JPanel();
    INT大小=(int)的的Math.sqrt(puzzle.getSize()+ 1);
    controls.setLayout(新的GridLayout(尺寸,大小));
    的for(int i = 0; I< puzzle.getSize();我++){
        INT K = puzzle.getListItem(ⅰ);
        如果(K == puzzle.getEmptyFlag())
            Controls.Add被(新的JLabel());
        其他{
            JButton的JB =的新的JButton(将String.valueOf(K));
            jb.addMouseListener(新MouseAdapter(){                @覆盖
                公共无效的mouseClicked(的MouseEvent E){
                    //获取行和列
                }            });
            Controls.Add被(JB);
        }
    }
    pane.add(对照);
}


解决方案

  1. 从不在一个JButton为此目的添加的MouseListener。使用一个ActionListener来代替。

  2. 为什么不创建JButton的数组或ArrayList中,然后简单地遍历列表找到正确的吗?

即,

 私人的JButton [] [] = buttonGrid JButton的新[行数] [COLS];

在其他地方,你需要填写与可行的JButton对象的网格,并把这些Jbutton将进入你的GUI。

再后来在程序中使用嵌套循环通过网格迭代比较与电网按钮的getSource()的JButton。

即。在JButton的ActionListener的

 公共无效的actionPerformed(ActionEvent的五){
  对于(INT行= 0;&行LT;的行;行++){
    对于(INT COL = 0;&山坳下,COLS;西++){
       如果buttonGrid [行] [COL] == e.getSource();
       //这里你有你的行和列
    }
  }
}


修改结果
你问:


  

      
  1. 为什么?

  2.   

由于它不会在许多情况下正常工作。的ActionListeners已建成与Jbutton将和JMenuItems具体工作,并有机制,使该功能工作做好升和轻松。例如,假设你决定要当用户填好两个JTextField即只启用了一个JButton,并使用JButton的的setEnabled(启用布尔)的方法来做到这一点,禁用的JButton不会停止工作的MouseListener的,但它会停止的ActionListener。


编辑2

例如,

 进口java.awt.GridLayout中;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;
进口的javax.swing *。公共类ButtonGridEg继承JPanel {
   私有静态最终诠释行数= 8;
   私有静态最终诠释COLS =的行;
   私有静态最终诠释GAP = 5;
   私人的JButton [] [] = buttonGrid JButton的新[行数] [COLS];   公共ButtonGridEg(){
      setLayout的(新的网格布局(行,COLS,GAP,GAP));      ActionListener的buttonListener =新的ActionListener(){         @覆盖
         公共无效的actionPerformed(ActionEvent的EVT){
            JButton的selectedBtn =(JButton的)evt.getSource();
            对于(INT行= 0;&行LT; buttonGrid.length;排++){
               对于(INT COL = 0;&山坳下,buttonGrid [行]。长度;西++){
                  如果(buttonGrid [行] [COL] == selectedBtn){
                     System.out.printf(选定的行和列:%D%N,行,列);
                  }
               }
            }
         }
      };
      对于(INT行= 0;&行LT; buttonGrid.length;排++){
         对于(INT COL = 0;&山坳下,buttonGrid [行]。长度;西++){
            字符串文本=的String.format(按钮[%D,%D]。行,列);
            buttonGrid [行] [COL] =的新的JButton(文本);
            buttonGrid [行] [COL] .addActionListener(buttonListener);
            添加(buttonGrid [行] [COL]);
         }
      }
   }   私有静态无效createAndShowGui(){
      ButtonGridEg的mainPanel =新ButtonGridEg();      JFrame的帧=新的JFrame(ButtonGridEg);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane()加(mainPanel中)。
      frame.pack();
      frame.setLocationByPlatform(真);
      frame.setVisible(真);
   }   公共静态无效的主要(字串[] args){
      SwingUtilities.invokeLater(新的Runnable(){
         公共无效的run(){
            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天全站免登陆