+ Reply to Thread
Results 1 to 2 of 2

Thread: How to get X and Y index of element inside GridLayout?

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    13

    How to get X and Y index of element inside GridLayout?

    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
    Code:
    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:
    Code:
    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
    Code:
    @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);
      }
    }

  2. #2
    Junior Member
    Join Date
    Jul 2012
    Posts
    12
    You have saved an array of all JButtons; you could search for ae.getSource() and you have the position.
    Code:
    for (int i = 0; i < 5; i++) {
      for (int j = 0; j < 5; j++) {
        if( b[i][j] == ae.getSource() ) { 
          // position i,j
        }
      }
    }

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts