I have a grid of 225 JButtons in a 2d array of 15 x 15

I was windering do i need 225

 if (event.equals (Grid[0][1]))
        {
        }

or is their a loops or something, thanks in advance

Recommended Answers

All 36 Replies

Object src = event.getSource();
for(int x = 0; x < Grid.length; x++){
    for(int y = 0; y < Grid[x].length; y++){
        if(Grid[x][y] == src){ //the source of the event will be the same instance as one of the JButtons if one of them was clicked
            System.out.println("Clicked at (" + x + ", " + y + ")");
            return;
        }
    }
}

P.S. Not written in an IDE, so it might not compile perfectly, but I'm fairly sure it should.

and you may want to add a return statement to your if.
otherwise, it'll do all the iterations you know will be false, because you already found the one you needed.

:o yea good point. Facepalm...

Most likely the loops are unnecessary. Depending on what the OP needs to do when the button is clicked, there are many ways to attach data or specific actions to a button.

More info is needed about the intent of the buttons.

Object src = event.getSource();
for(int x = 0; x < Grid.length; x++){
    for(int y = 0; y < Grid[x].length; y++){
        if(Grid[x][y] == src){ //the source of the event will be the same instance as one of the JButtons if one of them was clicked
            System.out.println("Clicked at (" + x + ", " + y + ")");
            return;
        }
    }
}

P.S. Not written in an IDE, so it might not compile perfectly, but I'm fairly sure it should.

I'm getting an error,
no field name event was found in game?...

and do i put this code right in my actionEvent?

public void actionPerformed (ActionEvent e)
    {
        String event = e.getActionCommand ();
if (event.equals ("Quit"))
        {
            hide ();
            System.exit (0);
        }
}

Most likely the loops are unnecessary. Depending on what the OP needs to do when the button is clicked, there are many ways to attach data or specific actions to a button.

More info is needed about the intent of the buttons.

I just need to know which of the 225 buttons was clicked

Then the getSource() method on the mouse event will tell you.

Then the getSource() method on the mouse event will tell you.

can you please explain, as im a real noob, just starting my second java course, just starting to learn swing

MouseEvent.getSource() returns the Object that was clicked. You can cast that to object to JButton.

depending on what you need done, i like to program my grids manualy instead of using buttons, lets say when i did minesweeper for fun, it was not a 2d array of buttons, or even a 1d array of buttons in a baglayout.

just paint whatever kind of grid you need on a JPanel , put the mouselistener on the JPanel, from the MouseEvent in mouseClicked() save e.getX() and e.getY() and determine which grid square you clicked with a single formula... good luck :)

MouseEvent.getSource() returns the Object that was clicked. You can cast that to object to JButton.

Ok, So I am so comfused, im been trying differant things and stuff, couse i really dont feel like doing 225 action listeners

but can you do an example

so lets say my array is this

JButton pButtonarray[] [] = new JButton [15] [15];

How would i add a listener to each of these buttons with mouselistener,
which will print on screen which button was clicked

depending on what you need done, i like to program my grids manualy instead of using buttons, lets say when i did minesweeper for fun, it was not a 2d array of buttons, or even a 1d array of buttons in a baglayout.

just paint whatever kind of grid you need on a JPanel , put the mouselistener on the JPanel, from the MouseEvent in mouseClicked() save e.getX() and e.getY() and determine which grid square you clicked with a single formula... good luck :)

common guys, I havent solved my problem yet,I need more help

use putClientProperty to associate the row and column numbers with each button when you create them. In your ActionListener just use getSource().getClientProperty to get the row/col numbers for the button that was clicked. The documentation for these methods is, as always, in the Java API JavaDoc, and can also be found with Google. And no, I'm not going to write the code for you, but if you have a try and post what you have done when you get stuck I'll help you.

As James said, you can associated various information with the buttons by setting property values on them.

There are also other ways to associate various actions with the buttons, but we can't really give you specific suggestions because you still have never said what you need to do when the button is clicked. All you will say is "I need to know which button is clicked". Well, you've been told the answer to that. Obviously, you need to do something else with that information, but if you won't explain further then no one can help much more.

@JamesCherrill
@Ezzaral

until yesterday I ignored EventHandler, but now ... somehow as I tried from 'left _to_right_and_back'... I can't found something wrong, nor buggy,

here is an answer, link inside the code example is about JButton

Ok, so I have a grid of JButtons here

int ppositionx = 50, ppositiony = 175;
        for (int row = 0 ; row < 15 ; row++)
        {
            ppositiony = ppositiony + 21;
            ppositionx = 50;

            for (int x = 0 ; x < 15 ; x++)
            {
                pButtonarray [x] [row] = new JButton ();
                pButtonarray [x] [row].setBorder (compoundmain);
                pButtonarray [x] [row].setOpaque (false);
                pButtonarray [x] [row].setBounds (ppositionx, ppositiony, 25, 25);
                pButtonarray [x] [row].addActionListener (this);
                infoPane.add (pButtonarray [x] [row]);
                contentPane.add (infoPane);
                ppositionx = ppositionx + 21;
                
            }
        }

Everytime it goes through the loop It makes a JButton
so everytime it goes through the loop I would to add a clientproperty to The JButton
but i dont know how to do this,
do i do this?
pButtonarray [x] [row].putClientProperty(x,row);

how are you suposed to type to code for setting a client property?

maybe dis_agreed

putClientProperty is best way for listening everything in the TextComponents e.g. DocumentListener, for Listener that listening key event that came from keyboard, for MouseEvents is better look for Model

EDIT

did you tried code link I posted, don't reinvent the wheel

putClientProperty(java.lang.Object,java.lang.Object) is just a key-value pair mapping. Strings are often used for the key values, but they don't have to be. You can use any Object as a key, which allows for some pretty clever mapping schemes in some cases.

In your case, strings would be fine: setClientProperty("row", row) This would set an Integer value of row with a key named "row".

@mKorbel: I think the OP could go either way just fine. For more complex behaviors like your example of changing state on mouse events along with holding the data values, the inner class works well. For just attaching a couple of extra data values to a JButton, putClientProperty() is very handy and simple.

Object src = event.getSource();
for(int x = 0; x < Grid.length; x++){
    for(int y = 0; y < Grid[x].length; y++){
        if(Grid[x][y] == src){ //the source of the event will be the same instance as one of the JButtons if one of them was clicked
            System.out.println("Clicked at (" + x + ", " + y + ")");
            return;
        }
    }
}

P.S. Not written in an IDE, so it might not compile perfectly, but I'm fairly sure it should.

So I decided to go with the example from Armanious, and everything compiles, just that action event doesn't respond when i press a button

and this is my code in action event

public void actionPerformed (ActionEvent e)
    {
        String event = e.getActionCommand ();

        Object src = event;
        for (int x = 0 ; x < 15 ; x++)
        {
            for (int y = 0 ; y < 15 ; y++)
            {
                if (pButtonarray[x][y] == src)
                { //the source of the event will be the same instance as one of the JButtons if one of them was clicked
                    System.out.println ("Clicked at (" + x + ", " + y + ")");
                    return;
                }
            }
        }
}

and I add an action listener to each JButton here

int ppositionx = 50, ppositiony = 175;
        for (int row = 0 ; row < 15 ; row++)
        {
            ppositiony = ppositiony + 21;
            ppositionx = 50;

            for (int x = 0 ; x < 15 ; x++)
            {
                pButtonarray [x] [row] = new JButton ();
                pButtonarray [x] [row].setBorder (compoundmain);
                pButtonarray [x] [row].setOpaque (false);
                pButtonarray [x] [row].setBounds (ppositionx, ppositiony, 25, 25);
                pButtonarray [x] [row].addActionListener (this);
                infoPane.add (pButtonarray [x] [row]);
                contentPane.add (infoPane);
                ppositionx = ppositionx + 21;
            }
        }

I'm really happy the code is accually compiling, and I'm hoping its just a small problem

no wait a few minutes

EDIT

1) works both ActionListeners, but Swing doesn't guaranteed ordering

2) in programing languages isn't to much space to pass String Variable as Object or Void or Class name, here is one of then expecting Reflection, use EventHandler rather than inner ActionListener or whatever another Zoo

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.EventHandler;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** based on  @see http://stackoverflow.com/questions/7702697 */
public class GridButtonPanel extends JPanel {

    private static final int N = 2;
    private final List<GridButton> list = new ArrayList<GridButton>();

    public GridButtonPanel() {
        super(new GridLayout(N, N));
        for (int i = 0; i < N * N; i++) {
            int row = i / N;
            int col = i % N;
            GridButton gb = new GridButton(row, col);
            gb.addActionListener((ActionListener) EventHandler.create(ActionListener.class, this,
                    "actionName" + row + "A" + col));
            list.add(gb);
            this.add(gb);
        }
    }

    public void actionName0A0() {
        System.out.println("Whatever");
    }

    public void actionName0A1() {
        System.out.println("Whatever");
    }

    public void actionName1A0() {
        System.out.println("Whatever");
    }

    public void actionName1A1() {
        System.out.println("Whatever");
    }

    private GridButton getGridButton(int r, int c) {
        int index = r * N + c;
        return list.get(index);
    }

    private class GridButton extends JButton {

        private int row;
        private int col;

        public GridButton(int row, int col) {
            super("r" + row + ",c" + col);
            this.row = row;
            this.col = col;
            this.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    int r = GridButton.this.row;
                    int c = GridButton.this.col;
                    GridButton gb = GridButtonPanel.this.getGridButton(r, c);
                    System.out.println("r" + r + ",c" + c
                            + " " + (GridButton.this == gb)
                            + " " + (GridButton.this.equals(gb)));
                }
            });
        }
    }

    private void display() {
        JFrame f = new JFrame("GridButton");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        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();
            }
        });
    }
}

no wait a few minutes

ok

please see my edit

please see my edit

ok, so your using a grid, and im not allowed to use a grid, so its a realy pain in the arse

do you know whats wrong with my code though?

your problem is that you pretty ignore dynamic LayoutManagers and use AbsoluteLayout, then your setBound creating lots of important problems

1) hard to find JComponents without using SwingUtilitities

2) JComponents aren't resiziable

3) sometimes is too hard calculate Insets (setBounds + gap)

4) I saw some issues that nexFocusableComponent doesn't works as I expected

This is really not a difficult problem

pButtonarray [x] [row].putClientProperty("x",x);
pButtonarray [x] [row].putClientProperty("row",row);
pButtonarray [x] [row].addActionListener (this);
public void actionPerformed(ActionEvent e) {
    JButton btn = (JButton)e.getSource();
    System.out.println("clicked x " + btn.getClientProperty("x") 
       + ",row " + btn.getClientProperty("row"));
}

This is really not a difficult problem

pButtonarray [x] [row].putClientProperty("x",x);
pButtonarray [x] [row].putClientProperty("row",row);
pButtonarray [x] [row].addActionListener (this);
public void actionPerformed(ActionEvent e) {
    JButton btn = (JButton)e.getSource();
    System.out.println("clicked x " + btn.getClientProperty("x") 
       + ",row " + btn.getClientProperty("row"));
}

So i tried that and i get this error from

pButtonarray [x] [row].putClientProperty("x",x);
pButtonarray [x] [row].putClientProperty("row",row);

No applicable overload for the method named "putClientProperty" was found in type "javax.swing.JComponent". Perhaps you wanted the overloaded version "void putClientProperty(java.lang.Object $1, java.lang.Object $2);" instead?

what does this mean?

What are you using to compile the program and which version of Java? That should resolve just fine to putClientProperty(Object,Object).

What are you using to compile the program and which version of Java? That should resolve just fine to putClientProperty(Object,Object).

im using readytoprogram Java IDE


using java 1.4.2

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.