Results 1 to 12 of 12
  1. #1
    andreiutz10 is offline Member
    Join Date
    Nov 2011
    Posts
    10
    Rep Power
    0

    Default Getting the index of a button from an array to the EventHandler

    Hi, everyone. I'm having some trouble figuring out how to pass the index of a button from an array to create an event for that button.
    Here's what I have:
    Java Code:
    private void populateWithButtons(int iRows, int iCols)
        {
            for(int i = 0; i < iRows; i++)        
                for(int j = 0; j < iCols; j++)
                {   
                    buttons[i][j] = new JToggleButton();
                    buttons[i][j].setSize(50, 50);                                             
                    buttons[i][j].addActionListener(new ButtonManager());
                    add(buttons[i][j]);                       
                }       
        }
    After creating the buttons and adding them to the panel now I'm writing the ButtonManager class:
    Java Code:
    public class ButtonManager implements ActionListener {
        
        @Override
        public void actionPerformed(ActionEvent e, int i, int j)
        {
        JToggleButton b = (JToggleButton)e.getSource();
        b.setEnabled(false);
    }
    
    }
    Now what I want is to get the location of the button from the array (i, j) in the event handler so I can do a cascading action (minesweeper style) on the other buttons around. How can I pass those arguments without the compiler calling me a noob?

    Thanks!
    Last edited by pbrockway2; 11-30-2011 at 05:23 AM. Reason: code tags added

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Getting the index of a button from an array to the EventHandler

    Hi, welcome to the forum! When you post code, use the "code" tags. You put [code] at the start of the code and [/code] at the end.

    get the location of the button from the array (i, j) in the event handler
    The actionPerformed() method has to have exactly the signature that is declared in the ActionListener interface. That is, it takes a single ActionEvent argument. So you can't pass the index values that way.

    If the button is not going to move around within the array, then the ButtonManager class could remember the index values as instance variables. Set them in the ButtonManager constructor and pass them at the time the action listener is created and added to the button.

  3. #3
    andreiutz10 is offline Member
    Join Date
    Nov 2011
    Posts
    10
    Rep Power
    0

    Default Re: Getting the index of a button from an array to the EventHandler

    Awesome, I don't know why I couldn't think of that on my own. Thank you! Unfortunately that wasn't my only problem. I also need to assign icons to each button for when they're pressed, but for some reason they don't show up. I'll just post the code here instead of opening another thread. Hope that's ok.

    Java Code:
    private void setButtonValues(int iRows, int iCols)
        {
            for (int i = 0 ; i < iRows ; i++ )
                for (int j = 0 ; j < iCols ; j++ )
                   if ( buttons[i][j].getDisabledIcon() != mine )
                      switch(addValues(i , j))
                      {
                          case 0: buttons[i][j].setDisabledIcon(null); break;
                          case 1: buttons[i][j].setDisabledIcon(value1); break;
                          case 2: buttons[i][j].setDisabledIcon(value2); break;
                          case 3: buttons[i][j].setDisabledIcon(value3); break;
                          case 4: buttons[i][j].setDisabledIcon(value4); break;                      
                      }
        }
    
        private int addValues(int iRow, int iCol)
        {   int surroundingMines = 0;
            for (int i = -1 ; i <= 1 ; i++ )
                for ( int j = -1 ; j <= 1 ; j++ )
                    if(notOutOfBounds(iRow + i, iCol + j) && (i!= 0 || j != 0))
                    {                
                        if(buttons[iRow + i][iCol + j].getDisabledIcon() == mine)
                        surroundingMines++;
                    }
            return surroundingMines;
      }
    What this does is basically scan the buttons around and check how many mines there are and give the final value which is assigned by adding a picture with the corresponding number on it. For some reason they don't appear when I press the button, even though I know they are assigned since I have this in the event handler:

    Java Code:
    if(b.getDisabledIcon()== BoardPanel.getMine())
            JOptionPane.showMessageDialog(null, "You lost!");
    Which actually works and lets me know when I've clicked a mine, even if it doesn't display the picture. What am I missing?

    Thanks again!
    Last edited by andreiutz10; 11-30-2011 at 06:14 AM.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Getting the index of a button from an array to the EventHandler

    I also need to assign icons to each button for when they're pressed
    Do you really mean to change the disabled icon? (That's the one that displays when the button is inactive and hence not able to be pressed I would guess). AbstractButton allows you set a number of icons - for when the button is selected, pressed, rolledover etc.

    If this isn't the cause of your problem, post a brief compilable, runnable example. It doesn't have to have all the game logic: just a button or two which don't display an icon when you think they should. Remember: put [code] at the start of your code and [/code] at the end.

  5. #5
    andreiutz10 is offline Member
    Join Date
    Nov 2011
    Posts
    10
    Rep Power
    0

    Default Re: Getting the index of a button from an array to the EventHandler

    Ok, I made another project of only the basic stuff. The point is there's no icon showing when pressing the button. That's what I'm going for.

    a box class:

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package test;
    
    import java.awt.GridLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JToggleButton;
    
         public class box extends JFrame{
            private JPanel panel;
            private JToggleButton buttons[][];
            private ImageIcon coco;
            
            public box(){
            
            super("d(o.o)b");    
            panel = new JPanel(new GridLayout(12,12));        
            buttons = new JToggleButton[12][12];
            coco = new ImageIcon("icon.jpg");
            
            for(int i=0; i<12; i++)
                for(int j=0; j < 12; j++)
                {
                    buttons[i][j] = new JToggleButton();
                    buttons[i][j].setDisabledIcon(coco);
                    panel.add(buttons[i][j]);
                }
             add(panel); 
             setSize(400, 400);
             setDefaultCloseOperation(EXIT_ON_CLOSE);
             setVisible(true);
                }            
    }
    main class:

    Java Code:
    package test;
    
    
    public class Test {
    
        public static void main(String[] args) {
        
        
        
        box myWindow = new box();
        
        } 
    }

  6. #6
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Getting the index of a button from an array to the EventHandler

    First, a disclaimer: you want one of the resident swing folk, not me! (eg db who posts here, and of whom more later)

    But, from what I can tell the look and feel supplies the selected version of the icon. (And I am assuming that it is the selected one you want to set: ie what you see when the button is pressed.) What I've cooked up responds to button clicks by checking the selected status and changes the icon appropriately.

    (I'm using an Icon implementation that does not depend on external files, so that doesn't get in the way of testing. Also I've replaced the box class with the Box class. Ordinarily I would have stuck to your braces style, but the combination of {-on-a-new-line with braces missing when the block is one statement - but many lines - long is too much ;)

    Java Code:
    package test;
     
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JToggleButton;
     
    public class Box extends JFrame{
        private JPanel panel;
        private JToggleButton buttons[][];
        //private ImageIcon coco;
            // a yukky green icon for purposes of illustration
        Icon coco = new Icon() {
            @Override
            public int getIconHeight() {
                return 30;
            }
            @Override
            public int getIconWidth() {
                return 30;
            }
            @Override
            public void paintIcon(Component comp, Graphics g, int x, int y) {
                g.setColor(Color.GREEN);
                g.fillRect(x, y, 40, 40);
            }
        };
           
        public Box() {
            super("d(o.o)b");    
            panel = new JPanel(new GridLayout(12,12));        
            buttons = new JToggleButton[12][12];
            //coco = new ImageIcon("icon.jpg");
             
            for(int i=0; i<12; i++) {
                for(int j=0; j < 12; j++) {
                    buttons[i][j] = new JToggleButton();
                    //buttons[i][j].setIcon(coco);
                    panel.add(buttons[i][j]);
                    buttons[i][j].addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            JToggleButton src = (JToggleButton)e.getSource();
                            if(src.isSelected()) {
                                src.setIcon(coco);
                            } else {
                                src.setIcon(null);
                            }
                        }
                    });
                }
            }
            add(panel); 
            setSize(400, 400);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            //setVisible(true); // moved to Test's main()
        }            
    }
    The buttons now show an unattractive green colour when they're pressed.

    The Swing forum on this site is the proper place for the question. Darryl and others who know what they're talking about post there - and Darryl has also talked about something similar (icons for other two state buttons) at the Java Tips Weblog
    Last edited by pbrockway2; 11-30-2011 at 08:55 AM.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Getting the index of a button from an array to the EventHandler

    I've just reread your post and realised you *do* want disabled icons. (Sorry, I must be the only person here who's never played minesweeper. I have an incredibly low tolerance for 'puter games.)

    Again, setIcon() does what setDisabledIcon() won't. Exactly how you use it depends on the logic of your action listener. (Eg set the icon at the time you enable/disable buttons).

  8. #8
    andreiutz10 is offline Member
    Join Date
    Nov 2011
    Posts
    10
    Rep Power
    0

    Default Re: Getting the index of a button from an array to the EventHandler

    Yeah, I was hoping there's a way to generate everything before the event, it would have been really useful, but tough luck I guess. Back to the drawing board.

    Thank you for all your help!

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,335
    Rep Power
    25

    Default Re: Getting the index of a button from an array to the EventHandler

    how to pass the index of a button from an array to create an event for that button.
    I haven't followed the details of the discussion, so this might not help.
    The Swing class JComponent has a feature: ClientProperity that you can use to store data with the object.
    It is based a hashtable so you can store anything you want with the object, like its index in an array.

  10. #10
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default Re: Getting the index of a button from an array to the EventHandler

    To see a disabledIcon you have to setEnabled(false). Are you sure you didn't want to setPressedIcon(...) instead?

    Oh, and Fubarable is the resident expert on Minesweeper clones.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  11. #11
    andreiutz10 is offline Member
    Join Date
    Nov 2011
    Posts
    10
    Rep Power
    0

    Default Re: Getting the index of a button from an array to the EventHandler

    Hi, a little update. I tried changing to setIcon() and the icons are still not displaying. I'm starting to think that's the problem. Isn't it enough to create an ImageIcon and then just assigning it to button.setIcon(ImageIcon x); ? I noticed pb setting the size and calling the paintIcon method, but I assume those are just for creating your own icon. Are those really necessary if I already already have a jpg file? Sorry guys, I'm still new to this entire stuff.

    P.S. Darryl, what I did was use the setDisabledIcon to set an icon for each button and then in the action listener I set button.setEnabled(false) whenever clicked; shouldn't have the icon showed then?

  12. #12
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default Re: Getting the index of a button from an array to the EventHandler

    I suggest you create a SSCCE (Short, Self Contained, Compilable and Executable) example with just one button and test with that. If it works, find out what you've done differently in your actual program; if it doesn't, post the SSCCE along with the directory structure showing where the image file is relative to the class file. Also provide details of how you are running the program -- IDE / command line / Applet in Applet Viewer / browser etc.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. EventHandler issue
    By JOHNINALBANY in forum AWT / Swing
    Replies: 3
    Last Post: 07-07-2012, 02:28 PM
  2. how to read array index
    By aconti in forum New To Java
    Replies: 5
    Last Post: 08-12-2011, 09:52 PM
  3. get index from an array (very frustrating)
    By Yakg in forum New To Java
    Replies: 4
    Last Post: 12-06-2010, 06:26 PM
  4. adding eventhandler
    By karabo101 in forum New To Java
    Replies: 3
    Last Post: 05-20-2009, 11:38 PM
  5. Array Index out of bounds
    By leapinlizard in forum New To Java
    Replies: 5
    Last Post: 04-29-2009, 05:11 AM

Posting Permissions

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