Changing A JButton's Icon In an Array of JButtons

I am making a battleship game and I have an array of buttons set up on the playing board.
When the user clicks a button, if it is a hit I would like the icon of the button to change.
This is what I have so far...
playerOcean = m1.getplayerOcean();
     compOcean = m1.getpcOcean();
          for (int x=0; x < 10; x++)
               for (int y=0; y < 10; y++)
                    if (playerOcean[x][y] == 2)
                         playButtons [x] [y].setIcon(hit);
Where hit = private Icon hit = new ImageIcon("boom.jpg");
And playerOcean is the array in which the locations of the ships are stored, where 2 is a hit.

Hi, mygrymm-
There are lots of inefficient ways to do this having to do with traversing arrays, etc., but probably the best thing for you to do is to create a two dimensional associative array, or an Object of Objects, in JavaScript parlance.  That way, you can look up the X in the parent object and the Y in that object to see if it exists.  Here's a really brief sample that I haven't tested, but should get you going in the right direction.
Let's say my boundary is 4, 5:
var xArray = new Object();
xArray["4"] = new Object();
xArray["4"]["5"] = true;
Then, when I test....
var currX = somehow.get.the.object.x.value;
var currY = somehow.get.the.object.y.value;
if (xArray[currX.toString()][currY.toString()] == true) {
   console.log("boundary hit!");
Hope that helps,
-Elaine

Similar Messages

  • Gui - making an array of JButtons to make a grid

    how do i declare an array of JButtons to make a 16x16 grid? here is an example:
    JPanel grid = new JPanel();
    grid.setLayout (new GridLayout(16,16));
    Container content = frame.getContentPane();
    ImageIcon icon = new ImageIcon("picture.gif");
    JButton[][] element = new JButton[16][16];
    for ( i = 0; i < 16; i++ )
    for ( j = 0; j < 16; j++)
    grid.add(element[i][j].setIcon(icon));
    content.add(grid);
    is that correct at all? it returns this error:
    'void' type not allowed here
    grid.add(elem[i][j].setIcon(icon));
    the caret points to the open parenthesis in setIcon(icon).
    if an array of JButtons doesnt work at all, is there an alternative? my program allows the user to arrange various bricks, etc. to create a maze.

    A 2-dimensional array of JButtons is perfectly possible, provided you write valid Java code. That's all the compiler is complaining about. And also, you forgot to create any button objects to go in the array. Try something like this:for ( i = 0; i < 16; i++ ) {
      for ( j = 0; j < 16; j++) {
        element[i][j] = new JButton();
        element[i][j].setIcon(icon);
        grid.add(element[i][j]);
    content.add(grid);That will get you started. Of course those buttons won't do anything until you add listeners to them, but that's your next challenge, I suppose.
    (By the way, there's a bug in the code that runs this forum. Wherever you see "<i>" in the code, alter it to use the correct rectangular brackets.)

  • Return an array of JButtons - Is this possible?

    Is it possible to return an array of JButtons? I have madean array of JButtons and assigned them anonymous listeners as they each do the same thing so i only had to do one in the for loop creation
    the idea is that i want to ship this code out to a method called createButtons and call it in the make frame method, but i cant seem to find a solution that actually works
    thanks

    JustSomeGuy wrote:
    If you went to your teacher and asked them how they felt about [the java forums], and under what circumstances it may be considered cheating, I think you will be suprised by the answer. Most teachers actually want you to learn, big shocker I know.
    JSGJSG.kudos++;
    compSciUndergrad wrote:
    if you want to tell me your opinions i am all ears, i hope they are not to harsh :SI'm of the opinion that at least 90% of students who are concerned about being seen as cheating are only concerned because they feel that they are cheating. Furthermore atleast 90% of students who "feel" that they are cheating have perfectly valid concerns, because they are in fact cheating.
    In my humble opinion it would be better for all concerned if cheaters did get caught, and sooner rather than later... because when they hit the real-world, where there really is no-one to cheat off, cheaters allways seem to come-a-cropper, big-time... because they also lie about there total lack of progress, in a shortsighted attempt to cover up there total imcompetence... too often taking those who entrusted them to actually do the friggin job down with them.
    Lots of good people getting skinned-alive by a pack of feral know-nothing friggin lawers, all because some moron kid tells a pack of lies, and thinks he's gonna get away with it come crunch time. Ummm... No thanks. Ta.
    So, much better to delineate between the competent and the not-competent programmer at the paedogogical stage. Eh what?
    I wouldn't class posting a bit of code on a forum as lay-down-mazaire proof positive that "He's a cheat". My concern is that you are actively concerned (paranoid even), which is indicative that you have actually cheated in the past; and plan to do so in the future. That's all.
    Cheers. Keith.

  • When i drag icons from the adress bar to the desktop they are changed to the firefox icon, how can i keep the sites icon?

    Rather than use favorites, I like to drag the icon in the address bar to the desktop or a folder to create a shortcut. In my older computers the icon in the shortcut was the same as the icon in the address bar. in my new Win 7 computer the icon is changed to a Firefox icon. How can I prevent the icon from being changed?

    If you drag a link or favicon on the left end of the location bar onto the desktop to create an internet shortcut then that shortcut gets the icon of the default browser.
    If you want a different icon (favicon) then you have to assign that icon yourself to the desktop shortcut (right-click: Properties).
    You can usually get the favicon if you append "favicon.ico" to the main domain of a website (e.g. http://www.mozilla.com/favicon.ico ) to display the favicon in a tab and save that image to a folder or see if you can find it in "Tools > Page Info > Media".

  • HT203421 I have recently purchased some apps from the app store and after downloading them, the icon that appears in the dock changes to a different icon. It is now the same icon appearing on all newly downloaded apps.  Does anyone know what is happening

    I have recently purchased some apps from the app store and after downloading them, the icon that appears in the dock changes to a different icon. It is now the same icon appearing on all newly downloaded apps.  Does anyone know what is happening here? Even updating an older game app resulted in the original game icon changing to the new identical icon that all new apps are appearing with.  This new icon is like a page with a ruler, pencil and paintbrush. Any tips on how to stop this or how to revert to the icon as it appears on the app store would be appreciated.

    https://discussions.apple.com/thread/6132949?tstart=0

  • How in the HECK can I change my Hard Drive icon??!??!!

    I've tried searching these discussion forums for how to do this, but the question has always remained unanswered! Does ANYbody know how to use this? I'd buy applecare but I'm a student and can't afford it. Would somebody please figure out how to make it so that you can paste a new icon on top of the standard icon for 10.3.9? It's driving me crazy that after I copy the icon I want to use for my hard drive that I can't paste it on top.
    And I've tried doing a permissions repair in Disk Utility.
    400 MHz PowerPC G4   Mac OS X (10.3.9)  

    That's how other people do it, HVlaar; it's the standard procedure. Works fine for me. Are you logged into an admin account? Have you considered that changing your hard drive icon probably isn't an important thing to do anyway?

  • Is it possible to make an array of JButtons?

    is it possible to make an array of JButtons?

    Note that this doesn't create any JButtons, just the array!

  • How to change The Standard JOptionPane Icon?

    in this simple code
    i want to change the Standard JOptionPane icon to a different icon
    how could it be?
    thank you
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.WindowListener;
    import java.awt.event.WindowEvent;
    import javax.sound.sampled.*;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.ImageIcon;
    import javax.swing.Icon;
    import java.awt.event.*;
      public class MyFrame extends JFrame 
    JLabel label=new JLabel("Hello");
      MyInner inner;
          MyFrame ()
            setupGUI();
        private void setupGUI()
           JFrame f =new JFrame();
        //   f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
           f.setTitle("Window Event");
            f.setSize(550,350);
            f.setResizable(false);
            f.setLayout(new BorderLayout());
            f.add("Center",label);
            f.show(true);
             inner=new  MyInner();
             f.addWindowListener(inner);
                   class MyInner extends WindowAdapter
           public void windowClosing(WindowEvent ee)
                         Toolkit tool = Toolkit.getDefaultToolkit();
                  tool.beep();
                      JOptionPane.showMessageDialog(null, "Nice Work! " );
                      System.exit(0);
          public  static void main(String[]args)
             MyFrame frame=new MyFrame ();
    }

    For instance:
        class MyInner extends WindowAdapter
            public void windowClosing(WindowEvent ee)
                Toolkit tool = Toolkit.getDefaultToolkit();
                tool.beep();
                JOptionPane.showMessageDialog(null, "Nice Work! ");
                ImageIcon myImageIcon = new ImageIcon("myPic.jpg"); // needs proper path here
                JOptionPane.showMessageDialog(null, "Better Work!", "Dang, I'm smart!", JOptionPane.ERROR_MESSAGE, myImageIcon);
                System.exit(0);
        }

  • How to change the node's icon in a tree when the node collapse or expand?

    how to change the node's icon in a tree when the node collapse or expand?

    Hi,
    You may need to use custom skin for that.
    -Arun

  • How can I generate an array of JButton in Eclipse 3.2 ?

    I know something like this shud work ::
    JButton[] barray = new JButton(5); // To create an array of 5 Buttons
    But the problem is that in the JButton class, there is no constructor that takes an integer argument.
    Any ideas ... ?
    Ajay Garg

    Please don't cross post - http://forum.java.sun.com/thread.jspa?threadID=5249328&tstart=0

  • I would suggest a new feature:The possibilty to change the mouse pointer icon when you hover on an a

    I would suggest a new feature:The possibilty  to change the mouse pointer icon when you hover on an active link by any other one icon I select.

    Current Firefox versions have a feature called tear-off tabs.<br />
    You can detach a tab from the current window and open it in a new window by dragging a tab in the browser window.<br />
    You can drag that tab back to the tab bar in the original window to undo that detaching.
    bug489729 (Disable detach and tear off tab):
    * https://addons.mozilla.org/firefox/addon/bug489729-disable-detach-and-t

  • How do I change application/dock/desktop icons?

    I recently downloaded a set of icons I'd like to replace my current icons on my desktop/dock. However, I'm having some problems. I've searched for the process to switch them I'm aware that you have to go to the Command+i option, copy the icon in the left, then go to what you want to switch and paste it to the icon in the left there. However, I think I might be having a problem changing it to the icon because after I get the info window open, the icon in the left is not the actual icon I'm trying to change it to. It looks like this:
    Instead of changing to the icon/picture I want, it changes to the identification of a .png/.ico image.
    Am I making any sense? And if so, can someone please help?
    Message was edited by: jrockingmoogle

    I don't think I am exactly sure of your problem, but I'll comment anyway. The procedure for changing an icon is, kindof, how you have described it; select the item with the icon you want to use and choose Get Info. Then select the icon in the Get Info window, by clicking on it once (in the upper left). This will cause an outline to appear around it. Then select Copy from the edit menu. Now select the item you want to change and repeat that same procedure, except, select Paste from the Edit pull down menu, in place of Copy, after you have selected the icon in the Get Info window.
    For changing System icons, you'll need something like CandyBar.

  • IOS 7 doesn't change the lighting bolt icon when iPhone 4s is fully charged

    When I connect my iPhone 4s to a plug and it starts charging, I can see a lightning bolt on iOS7 next to the battery, but when it is fully charged it doesn't change to a plug icon as it used to change on iOS 6. Any suggestions? Does it damage my battery?

    Well, for the time being (I mean, if Apple does not go back to the bolt/plug icons) if the device shows 100% then it's fully charged.
    But feel free to let Apple know that you want it in http://www.apple.com/feedback

  • How to create an array of JButtons and How to implment it ...

    This is what i want to do - I want to create an array of JButtons that has 8 rows of 8 buttons, could someone help me with this (im creating a checkers board) all i need is the array of buttons and them in 8 rows of 8 buttons .... im pretty confident in the way of making them do what i want but need help getting it up and running .... please note it is to be done in the swing environment and not in a applet or anything - ie in a JPanel and a JFrame .... any help would be GREATLY appreciated.

    U can try this
            JButton b[][] = new Button[8][8];
         setLayout(new YourLayout());
         for(int i =0; i<8; i++)
              for(int j =0; j<8; j++)
                   b[i][j] = new Button("Test");
                   b[i][j].addActionListener(new YourAction());
                   add(b[i][j]);
         }               

  • How to change the color of icons

    Hello all...
    Is there a way to change color of an icon??? It seem to me that I was able to do this in a previous OS but I have lost the way to accomplish the task.

    Thanks for your reply Templeton; however, your method only changes the color of the label not the icon itself. I'm looking to change the color of the icon.

Maybe you are looking for

  • Firefox says i have java already ..but java is not showing on my control panel what can i do to download the java

    How can you help me clear this problem with Java, my system is windows 7

  • Error starting IntergratedWebLogicServer

    hi am on window xp and using oracle 11g database and my WebLogic Server Version: 10.3.4.0, am having problem when running Intergrated WebLogicSever my error log is *** Using HTTP port 7101 *** *** Using SSL port 7102 *** "C:\Documents and Settings\De

  • SapBI

    <Moderator Message: Thread locked due to the following reasons: a) meaningless subject; b) requesting information sent to privat email; c) replies contained link farms; d) unability to search for information by yourself; e) question/request too vague

  • SOAP-Exception: unsupported response content type

    Hi, can anybody give me a little hint?. I currently try to run the JDeveloper "Tutorial" web service examples. I could successfully implement and deploy the DateTime Web-Service example. But when executing "DateTimeClient.java" I get the error messag

  • Dropping Undo Tablespace 9i

    Hey Folks, I really need some help here. I'm trying to drop/recreate the undo tablespace (currently 25gig) Oracle 9i When I try to drop the undo tablespace 'UNDOTBS1' I get the following error: “ORA-01548: active rollback segment '_SYSSMU1$' found,