如何获得内部GridLayout的元素的X和Y索引? [英] How to get X and Y index of element inside GridLayout?

查看:307
本文介绍了如何获得内部GridLayout的元素的X和Y索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习一个java教程,看到的方式找到一个JButton的X / Y指标内GridLayout的是遍历键b的二维数组是关联到布局,并检查是否

B [I] [J] == buttonReference

  @覆盖
  公共无效的actionPerformed(ActionEvent的AE){
    JButton的BX =(JButton的)ae.getSource();
    的for(int i = 0;我小于5;我++)
      为(中间体J = 0; J&小于5; J ++)
        如果(B [i] [j]的== BX)
        {
          bx.setBackground(Color.RED);
        }
  }

有没有更简单的方式来获得一个按钮的X / Y索引?

是这样的:

  JButton的按钮=(JButton的)ev.getSource();
INT X = this.getContentPane()getComponentXIndex(按钮)。
。INT Y = this.getContentPane()getComponentYIndex(按钮);

这个是一个GameWindow实例和 EV 中的ActionEvent触发,当用户presses的按钮。

在此情况下,它应该得到:X == 2,Y == 1

@ GameWindow.java:

 包javaswingapplication;进口java.awt.Color中;
进口java.awt.GridLayout中;
java.awt.event中导入*。
进口的javax.swing *。公共类GameWindow扩展JFrame中实现的ActionListener
{
  JButton的B〔] [] =新的JButton [5] [5];  INT V1 [] = {2,5,3,7,10};
  INT v2中[] = {3,5,6,9,12};  公共GameWindow(字符串名称)
  {
    超(职称);    的setLayout(新的GridLayout(5,5));
    setDefaultCloseOperation(EXIT_ON_CLOSE);    的for(int i = 0;我小于5;我++)
      为(中间体J = 0; J&小于5; J ++)
      {
        B〔I] [J] =的新的JButton();
        B〔I] [J] .addActionListener(本);
        加(B [I] [J]);
      }
  }  @覆盖
  公共无效的actionPerformed(ActionEvent的AE){
    ((JButton的)ae.getSource())的setBackground(Color.red)。
  }
}

@ JavaSwingApplication.java:

 包javaswingapplication;公共类JavaSwingApplication {
  公共静态无效的主要(字串[] args){
    GameWindow G =新GameWindow(游戏);
    g.setVisible(真);
    g.setSize(500,500);
  }
}


解决方案

此示例演示如何创建一个知道其在网格位置的网格按钮。该方法 getGridButton()显示了如何有效地基于其网格坐标获得一个按钮参考,并动作监听显示,点击,发现按键是相同的。

 包贵;进口java.awt.EventQueue中;
进口java.awt.GridLayout中;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;
进口的java.util.ArrayList;
进口的java.util.List;
进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JPanel中;/ **
 * @see http://stackoverflow.com/questions/7702697
 * /
公共类GridButtonPanel {    私有静态最终诠释N = 5;
    私人最终名单<&的JButton GT;名单=新的ArrayList<&的JButton GT;();    私人的JButton getGridButton(INT R,诠释三){
        INT指数= R * N + C;
        返回list.get(索引);
    }    私人的JButton createGridButton(最终诠释排,最终诠释COL){
        最后一个JButton B =的新的JButton(R+行+C+ COL);
        b.addActionListener(新的ActionListener(){            @覆盖
            公共无效的actionPerformed(ActionEvent的五){
                JButton的GB = GridButtonPanel.this.getGridButton(行,列);
                的System.out.println(R+行+C+ COL
                    ++(B == GB)
                    ++(b.equals(GB)));
            }
        });
        返回b;
    }    私人的JPanel createGridPanel(){
        JPanel的P =新JPanel(新网格布局(N,N));
        的for(int i = 0; I< N * N;我++){
            INT行= I / N;
            INT山坳= I%N;
            JButton的GB = createGridButton(行,列);
            list.add(GB);
            p.add(GB);
        }
        回磷;
    }    私人无效显示(){
        JFrame的F =新的JFrame(GridButton);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(createGridPanel());
        f.pack();
        f.setLocationRelativeTo(NULL);
        f.setVisible(真);
    }    公共静态无效的主要(字串[] args){
        EventQueue.invokeLater(新的Runnable(){            @覆盖
            公共无效的run(){
                新GridButtonPanel()显示();
            }
        });
    }
}

I am studying a java tutorial and saw that the way to find the x/y indexes of a JButton inside a GridLayout is to traverse a bidimensional array of buttons b which is associated to the layout and checking if

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);
        }
  }

Is there an easier way to get the X/Y indexes of a button?

Something like:

JButton button = (JButton) ev.getSource();
int x = this.getContentPane().getComponentXIndex(button);
int y = this.getContentPane().getComponentYIndex(button);

this being a GameWindow instance and ev the ActionEvent triggered when the user presses the button.

In this case it should get: 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);
  }
}

解决方案

This example shows how to create a grid button that knows its location on the grid. The method getGridButton() shows how to obtain a button reference efficiently based on its grid coordinates, and the action listener shows that the clicked and found buttons are identical.

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();
            }
        });
    }
}

这篇关于如何获得内部GridLayout的元素的X和Y索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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