Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get X and Y index of element inside GridLayout?
    primarykey
    data
    text
    <p>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</p> <p><code>b[i][j] == buttonReference</code>.</p> <pre><code> @Override public void actionPerformed(ActionEvent ae) { JButton bx = (JButton) ae.getSource(); for (int i = 0; i &lt; 5; i++) for (int j = 0; j &lt; 5; j++) if (b[i][j] == bx) { bx.setBackground(Color.RED); } } </code></pre> <p>Is there an easier way to get the X/Y indexes of a button?</p> <p>Something like:</p> <pre><code>JButton button = (JButton) ev.getSource(); int x = this.getContentPane().getComponentXIndex(button); int y = this.getContentPane().getComponentYIndex(button); </code></pre> <p><code>this</code> being a GameWindow instance and <code>ev</code> the ActionEvent triggered when the user presses the button.</p> <p><img src="https://i.imgur.com/AWNw0.png" alt=""></p> <p>In this case it should get: x == 2, y == 1</p> <p>@GameWindow.java:</p> <pre><code>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 &lt; 5; i++) for (int j = 0; j &lt; 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); } } </code></pre> <p>@JavaSwingApplication.java:</p> <pre><code>package javaswingapplication; public class JavaSwingApplication { public static void main(String[] args) { GameWindow g = new GameWindow("Game"); g.setVisible(true); g.setSize(500, 500); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload