Fastest and simplest way to display a 2D grid in Swing, using images?

Hi,
I'm trying to draw a game-board in Swing. I've already figured out how to draw it in my teachers turtle-graphics thing, but I want to make my game a little prettier.
I've managed to draw the entire GUI in Swing, and it has full functionality, I'm just missing the "drawMap()" method that should display the game in the level-JPanel.
One of my friends at school already managed to do this, but he used -400- lines of code and two objects/classes. I hope there is a better way.
The turtle version of my code is like this:
     void turtle() {
          int width = game.getGrid()[0].length;
          int height = game.getGrid().length;
          STG.home(true);
          String url = null;
          STG.up();
          for (int y = 0; y < game.getGrid().length; y++) {
               for (int x = 0; x < game.getGrid()[y].length; x++) {
                    switch (game.getGrid()[y][x]) {
                    case WALL:
                         url = "/sokoban/icons/wall.png";               
                         break;
                    case EMPTY:
                         url = (game.getTargets()[y][x]) ? "/sokoban/icons/target.png" : "/sokoban/icons/tile.png"; // url = (boolean) ? iftrue dothis : elseiffalse dothis
                         break;
                    case MOVER:
                         url = (!game.getWinner()) ? "/sokoban/icons/mover.png" : "/sokoban/icons/happyMover.png";                         
                         break;
                    case CRATE:     
                         url = (!game.getTargets()[y][x]) ? "/sokoban/icons/crate.png" : "/sokoban/icons/crateOnTarget.png";
                         break;
                    default:
                         break;
                    STG.image(url, 30, 30, (width/2-x)+0.40, -height/2+y);
          }I'm pretty sure there has to be a similar way of doing this in Swing, without using hundreds of lines of code.
Here's a screen-shot so there's absolutely no confusion about what I'd like to achieve:
[http://img198.imageshack.us/img198/2815/40317025.png]
I want to draw the game-board in the JPanel titled 'Level: 1'.
Please point me in the right direction =)

Thanks. The values of getGrid and iIcon are correct.
I did make a working class that could draw up a map, what I'm having trouble with is implementing it in my GUI.
I'm pretty new to this, and I'm miles ahead of what I am supposed to be doing at this time.. I guess I'm in way over my head, but still, I think it's a lot of fun, and I want to finish :)
This is the working example
package sokoban1;
import java.awt.*;
import javax.swing.*;
public class DrawMap extends JFrame {
     private static final long serialVersionUID = 1L;
     ImageIcon tile           = new ImageIcon("C:/Users/David/Desktop/OOP/Workspace/ovinger/resources/sokoban/icons/tile.png");
     ImageIcon wall           = new ImageIcon("C:/Users/David/Desktop/OOP/Workspace/ovinger/resources/sokoban/icons/wall.png");
     ImageIcon target     = new ImageIcon("C:/Users/David/Desktop/OOP/Workspace/ovinger/resources/sokoban/icons/target.png");
     ImageIcon mover      = new ImageIcon("C:/Users/David/Desktop/OOP/Workspace/ovinger/resources/sokoban/icons/mover.png");
     ImageIcon happyMover      = new ImageIcon("C:/Users/David/Desktop/OOP/Workspace/ovinger/resources/sokoban/icons/happyMover.png");
     ImageIcon crate      = new ImageIcon("C:/Users/David/Desktop/OOP/Workspace/ovinger/resources/sokoban/icons/crate.png");
     ImageIcon crateOnTarget = new ImageIcon("C:/Users/David/Desktop/OOP/Workspace/ovinger/resources/sokoban/icons/crateOnTarget.png");
     char [][] testGrid = {{'#', '#', '#', '#', '#'}, {'#', ' ', ' ', ' ', '#'}, {'#', '$', '$', '$', '#'}, {'#', '@', '@', '@', '#'}, {'#', '#', '#', '#', '#'}};
     int height = testGrid.length;
     int width = testGrid[0].length;
     GridLayout sokobanMap = new GridLayout(height,width);
     final char WALL = '#' , EMPTY = ' ', MOVER = '@', CRATE = '$';
     public DrawMap() {}
     public void addComponentsToPane(final Container pane) {
          setResizable(false);
          final JPanel gamePanel = new JPanel();
          gamePanel.setLayout(sokobanMap);
          JPanel controls = new JPanel();
          controls.setLayout(new GridLayout(height ,width));
          ImageIcon iIcon = null;
          boolean b = true;
          for (int y = 0; y < height; y++) {
               for (int x = 0; x < width; x++) {
                    switch (testGrid[y][x]) {
                    case WALL:
                         iIcon = wall;               
                         break;
                    case EMPTY: // url = (boolean) ? ifTrue this : ifFalse this
                         iIcon = (b) ? target: tile;     //game.getTargets()[y][x]
                         break;
                    case MOVER:
                         iIcon = (b) ? happyMover : mover; //game.getWinner()
                         break;
                    case CRATE:     
                         iIcon = (b) ? crateOnTarget : crate; //game.getTargets()[y][x]
                         break;
                    gamePanel.add(new JLabel(iIcon));
          pane.add(gamePanel, BorderLayout.NORTH);
      * Create the GUI and show it.  For thread safety,
      * this method is invoked from the
      * event dispatch thread.
     public void draw() {
          //Schedule a job for the event dispatch thread:
          //creating and showing this application's GUI.
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    //Create and set up the window.
                    DrawMap sokoFrame = new DrawMap();
                    sokoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    //Set up the content pane.
                    sokoFrame.addComponentsToPane(sokoFrame.getContentPane());
                    //Display the window.
                    sokoFrame.pack();
                    sokoFrame.setVisible(true);
}And this is my GUI [http://pastebin.com/RqprGWSy] (Well, NetBeans did most of the work, which might add to my confusion :p)
The gamePanel is probably added, since I can see its frame, or maybe I'm misunderstanding something. I'll take a closer look.
Thanks for all your help so far :)

Similar Messages

  • HT1338 I am trying (without success) to design an organization chart on Diagram Painter, please advise fastest and easiest way to complete this task?

    I am trying (without success) to design an organization chart on Diagram Painter, please advise fastest and easiest way to complete this task?

    Purchasing an app from the App Store does not mean that Apple's forums are the right place to ask questions about it. Asking about it here is roughly similar to asking another customer at Wal-mart how to assemble the bicycle you bought there. Ask the company that created the app, using the link Bob gave you.

  • Simple and efficient way to display image on jpanel

    AOA
    What may be the simple and efficient way
    to display a strored jpg image on a jpanel in an application.
    i will appreciate more than one ways.
    thanks

    JPanel panel = new JPanel() {
         public void paintComponent(Graphics g) {
                   g.drawImage(......);
    };

  • What is the least expensive and simplest way to print from the iPad 2?

    What is the least expensive and simplest way to print from the iPad 2?

    Setup AirPrint Printer
    1. Buy an AirPrint enabled printer; see list below
    http://support.apple.com/kb/ht4356
    2. Run the CD provided and set printer and iPad on the same network
    3. Start printing from your iPad using AirPrint

  • Is there a way to do a spelling quiz in captivate using images and not questions as reference.

    Is there a way to do a spelling quiz in captivate using images and not questions as reference. Specifically i want have blank lines underneath an image, where the user looks at the image and types the correct letters to fill in the blank. For example a picture of a dog, with this _ _ _ underneath for the user to fill in, or in some cases perhaps having them fill in the vowel like so "d_g".I must have audio with this , as the students will be able to listen to the audio sound out the word phonetially to help them be able to type it!
    Appreciate any advice! Cheers!

    Hello everybody!
    This widget is great!! Thank you for that!!
    I searched for something like that earlier and made an other workaround:
    http://forums.adobe.com/message/1912430#1912430
    The Javascript did not work in my test. I brought to the "if you reach this slide" feature but it failed.
    Regards,
    Markus

  • Could someone please tell me the fastest, cheapest, simplest way to back up all my data (photos and music) thanks!

    Well I am heading in to the
    apple services store to collect my computer which went dead in my power cut 10 days ago (discussed in my last post), and has since been fixed with new power supply.  My question is - what's the cheapest and easiest way for me to back-up all my data (several thousand photos, and similar number of songs on iTunes, and a few quicktime video files)  Is there a product I can buy to save it on - I have no idea how many gigs etc, that will be? and what I need to buy to do so, and finally, how easy/fast will it be to save everything.... this is indeed a very simple thing, I am sure, but I have never done it before, just saved odd bits on pen drives, etc.....  The repair is costing over $400 - and as it's an old imac, aside from the fact it has all of Final Cut Pro Studio on it - it's hardly worth the repair price.... what I want though is to save everything as cheaply and simply as possible - what do I need to buy and how (in simple language please) do I save it... Many many thanks if anyone can put this in simple language for me... Cheers

    I agree with BGreg about OWC, great people and service, quality products and competitive prices. Not bigbox sell cheap stuff prices but fair prices. Like him I also like cloning with SuperDuper! or CCC. For most users CCC is perfect - SuperDuper! adds some extras that techs like.
    But I'll also add a vote for Apple's own TimeMachine. It is an automatic backup system that runs every hour; the first backup takes a while and the rest not very long because they are backing up only the chances made in the last hour. Due to its schema, TimeMachine is most effective with a backup drive that is 2-3 times larger than your backup set. If you are using 200GB of your 500GB drive, then your TimeMachine backup drive should be at least 400GB and preferably closer to 600GB.
    The two backup schemes are different and having two different backups is a very good idea - backup drives have been known to die . The clone's advantage is that it is a bootable system disk - if your computer's drive dies you can boot with it and keep working until you get the computer repaired. If your computer's drive gets messed up you can boot with the clone and try to repair it or at least recover some of the most recent files that aren't on the clone. (Which happens to be one of the disadvantages of a clone - people tend to reclone somewhat infrequently.) Having TimeMachine means you have very recent backups.
    So if you intend to keep using this computer - TimeMachine might be the better choice - or at least another consideration. If you are just grabbing data - CCC will do the trick best.

  • STORAGE OF PDF IN A TABLE, AND ALSO WAY TO DISPLAY THROUGH THE REPORT

    Hello All,
    Kindly help me out if possible,
    I have a table, lets say table1.
    Kindly guide me that if I want to store a PDF under a column of table1 then how can I store it? What the datatype should I use to store this pdf.
    Also Kindly give me the way to display this PDF through Report...
    Thank you...
    Edited by: 974572 on Dec 3, 2012 2:26 AM

    PLEASE DO NOT SHOUT (in the title as well).
    >
    I have a table, lets say table1.
    Kindly guide me that if I want to store a PDF under a column of table1 then how can I store it? What the datatype should I use to store this pdf.
    >
    Store in a BLOB column.
    >
    Also Kindly give me the way to display this PDF through Report...
    >
    See < a href="https://forums.oracle.com/forums/search.jspa?threadID=&q=display+pdf&objID=f137&dateRange=thisyear&userID=&numResults=15">this link and check the solutions given.</a>

  • Simplest way to transfer Contacts/Addresses to the Curve using iMac / Palm Desktop ?

    I have a new 8300 Curve and approximately 1500 Contacts/Addresses in my iMac on Palm Desktop ( they are also in Palm handheld).
    I am able to export these Contacts/Addresses to my iMac desktop in various formats: excel workbook, .csv Comma Delimited , .txt Text Delimited, vcard. 
    My computer is an intel iMac with OS X version 10.4.11.
    What is the best/simplest way to transfer those Contacts/Addresses to the Curve? 
    Thanks
    Dan 

    Hi,
    OMG! I know how it feels when we got our all contacts in a tabular formatted file which is created in excel, CSV formatted file and unfortuntealy all the blackberry phones arre abel to rectify only vCard formatted file. This is the reason when i was facing the same problem than at that point of time i find out a simple and free download software which can convert contacts from excel to vCard file format. here is the complete step by step instructions http://www.exceltovcard.onlinetechaid.com/ and you can download it free.  after converting contacts you just have to follow a simple set of instructions which i am going to mention it below and you are able to use all these contacts in your curve or also in another Blackberry phone. so the instructions are :
    (i) Copy all the contacts in your Memory Card.
    (ii)  Now open your file manager
    (iii) select memory card
    (iv) open the location where you save all the contacts in vCard formatted file
    (v) Now click on options in your blackberry phone select "Select All"
    (vi) After that click on addd to contacts.
    Just try these simple way and you are able to use all your contacts in your Blackberry phone and make your life simple.

  • Simplest way to display a title or caption at the beginning of each scene?

    I am editing a video to make an instructional dvd covering 23 separate lessons. Without some kind of text in the first few seconds of each scene, there is no way for the viewer to quickly and efficiently distinguish one scene from another as they jump forward or backward from scene to scene. They would have to go back to the main menu between each scene to find the one they're looking for, and that's cumbersome.
    I would like to add a caption/title (not sure what the technical Adobe term is -- I'm obviously an amateur) to the screen at the beginning of each scene. It can be a text overlay on top of the video, or it can be a blacked out screen (or whatever) with text that lasts a few seconds before each scene begins. I just need something to let the viewer know which lesson they are about to see.
    I went through the footage and added scene markers at appropriate places, and the menu is functional. Now I'm looking for the most efficient (least time-consuming) way to accomplish my goal. It looks like one alternative is to manually split the clips at each scene change, then go to sceneline and insert a title between each scene, then manually type in the text that corresponds to my description of each scene. I hope this isn't the only, or the most efficient way.
    Anyone know a simpler alternative? The simpler the better, as only a few people will be using the dvd so I don't want the cost (measured in editing time and effort) to outweigh the benefit of viewer convenience. Thanks in advance.

    I agree with Steve G. on adding the Titles from the PrE Titler function. Also, being new to PrE, this article on Titler might be useful, before you get tripped up by a few aspects of a New Title: http://forums.adobe.com/message/4976998#4976998
    Good luck,
    Hunt

  • Fastest and easiest way to drop a tablespace with LOB Segments

    When I try to drop a tablespace I get a message that I can't cause it still contains LOB Segments. I searched to see what objects like tables or indexes are in that tablespace and there are none.
    Any one run into this? Any way to get around this issue?

    Sorry,
    Version = 10.2.0.4
    OS = Win2003 32bit
    Command used = DROP TABLESPACE IWORKS_LARGE_TABLES INCLUDING CONTENTS AND DATAFILES;
    Error Message = ORA-22868: table with LOBs contains segments in different tablespaces
    Objects currently in this tablespace:
    SQL> select s.segment_name, s.segment_type
      2    from dba_segments s
      3   where tablespace_name = 'IWORKS_LARGE_TABLES'
      4  ;
    SEGMENT_NAME                                                                     SEGMENT_TYPE
    SYS_IL0000060885C00008$$                                                         LOBINDEX
    SYS_LOB0000060885C00008$$                                                        LOBSEGMENT
    SYS_IL0000060918C00048$$                                                         LOBINDEX
    SYS_LOB0000060918C00048$$                                                        LOBSEGMENTI basically want to drop the whole tablespace but these objects are not allowing me to.

  • Fastest and easiest way to transfer system & files G3 to G5

    I have a G3 b&W with a 400 firewire card in it, and two basic ATA hard drives. Which would be easiest way to transfer 10.3.9 system (with classic) by means of Carbon Copy Cloner, and all files to a partition on the G5 Mac.
    Since the G5 has 400 & 800 firewire, or ethernet transfer.
    I think Migration Assistant will help with the transfer, but not sure wich way to go about this.
    Berry

    Hi Berry, to use CCC you need an older version for 10.3, version 2.3, because the B&W doesn't support FWTDM.
    Put the G5 in FW Target Mode…
    http://docs.info.apple.com/article.html?artnum=58583
    Wait for the G5's HD to show up on B&W.
    But, if perchance it's just Classic you need, you can Simply copy OS9's "System Folder" & "Applications OS9" over.

  • What's Up with Firefox and the way it displays sites?

    Just wondering what is going on with Firefox? My site looks fine in both Safari and Google Chrome, however when I look at it in Firefox for some reason two of my links are covered up by the contact box that I have at the bottom of the navigation bar.
    In Firefox both the Events and Blog links are covered by this box, but are fine in Safari and Google Chrome, as you will see.
    What can I do about this - http://www.bodycentred-therapy.com

    I gave up on Firefox a good while back and now use Chrome more and more.
    I downloaded the latest V 3.6.13 of Firefox a couple of days ago and it doesn't seem much better. Having said that I haven't looked at V 4 beta at all. It might be worth your while trying your site in that version to see if the cause of the problem is something they may be trying to fix.
    I was trying an experiment putting the code for several single music players into one HTML Snippet and discovered that Firefox chops the bottom off and I had to add a line or two of code to force it to expand downwards.

  • What's the simplest way to edit the audio on a DVD using a Mac?

    I appreciate you taking the time to read/respond to this post.
    Here's the deal:
    My church records its service on DVDs to pass out to members.  This past weekend an annoying, high-pitch hum found it's way on to our DVD.  We also record audio versions of our service to pass out on CDs, and (scratching my head) this week's CD turned out just fine, no hum.
    Is there an easy way to detach the "bad" audio from the DVD and replace it with the good "audio" from the CD?  I know I could do what I want using iMovie, but every time I do something like this using that program, the picture quality on my new DVD looks worst than the original, plus it takes a ton of time converting and reauthoring.
    Your help and suggestions are most appreciated.

    I've never really used IMovie cause I have Final Cut, but I'm surprised its degrading your video , This makes me wonder what format your movies are in , are they .dv ( digital video ) ?
    You may even take a look at your burn settings in IDVD , I cant think of anything else outside of video editing software that will do what you are trying to do, in short its your only real option..  

  • What would be the simplest way to view and take control over the internet?

    Hi All:
    Can some one tell me what would be the best and simplest way to connect from my laptop to another laptop through the internet?
    I have DYNdns running on the second laptop and have a host name assigned to that system for it to update the IP since the system uses different internet connections. The services that I would like to be able to have are the viewing and controlling of the system. I've read some where in this NG that if I have a copy of ARD admin. installed on that system also, it would be one way to do it... can some one verify this and please let me know if there are any specific settings I need to have on either one of the systems.
    I can connect to the second laptop while in my home network with no problem and perform all tasks. when trying to connect through the internet.. the system shows offline .
    Both systems are identical in hardware an software, Intel 2.16, 2G's RAM, OS X ver 10.5.2 all up to date and ARD 3.2
    Yes, I'm new to ARD and yes I'm searching the NG and the net. but I figure it doesn't hurt to ask since time is limited.
    All help greatly appreciated ..
    TIA
    Oscar A.

    To be able to connect to a workstation from outside it's network, the ports that ARD uses must be open on both ends of the connection. ARD uses ports 3283 and 5900 so those must be open.
    If your workstations get their addresses from an NAT device rather than being "real", the ports also need to be forwarded in the router to the workstation's internal IP address. ARD uses port 3283 for the reporting and updating function, so if your Macs are getting their IP addresses through NAT, since you can only forward a port to a single workstation, you can only get reports, push package/files to etc. for a single workstation.
    ARD uses the VNC protocol for observation and control, though, and there are a range of IP addresses for that protocol, starting with 5900. ARD uses 5900 by default, so that port would be forwarded to the first workstation. You would, I believe, need to install VNC servers on the systems (since the ARD client cannot listen on any port other than 5900 while VNC servers can be set for other ports such as 5901, 5902, etc. You would then forward 5901 to the second workstation (and on to 5902, 5903, etc.). You can then use the following information:
    Remote Desktop 2: How to specify a port number for a VNC client
    to connect.
    The only other options are: 1) to run the ARD administrator on a workstation on the network, and then take control of that system from outside, either via VNC or another copy of ARD, or 2) set up a virtual private network (VPN) so that when you connect from outside, your admin system is officially part of the local network.
    Hope this helps.

  • Whats the fastest (and least complicated) way to copy Music from my PC to my ipod

    am trying to copy music from my PC to iPod touch but it never seems to work HELPPPPPPPP!

    Fastest and easiest way is to sync it through iTunes. You should also consider subscribing to iTunes match. It costs around $20 for a year and puts all your songs onto the cloud. This allows you to easily transfer the songs without having to sync your iPod. When you add a song to iTunes, through iTunes match it will upload the song to the cloud and automatically download the song to your iPod.

Maybe you are looking for

  • Multiple iPod Touch issues

    I received my iPod Touch last Thursday and then spent most of Friday just trying to get the blasted thing to accept my wireless password. Note: I have multiple wireless devices, (one router) all of which use the same password with no problems. Finall

  • Itunes could not restore the iphone because a session could not be started with the iphone

    Recently I sent my iPhone 5 to apple service centre as my phone could not turn on and stuck at apple logo. The technician use DFU restore and successfully reboot my phone. However, all my data and content are being erased. Now I tied to restore from

  • Infinite restore loop AND disk utility lists HD size as 500GB

    So, after reading everyone else's problem with the restore loop i have another kink to add to the mix. I am running software 1.2.1 in itunes 7.5 on a 5th gen 30GB ipod on a MacBook, and it is stuck in the restore loop. When I attempt to restore via i

  • Master/detail and problem with selected row when errors on detail row

    I'm using JDeveloper 10.1.3.3 I have a very simple master/detail screen (JSF JSP) where master is departments and detail is employees in the selected department. Some of the attributes in employees are required. To department A I take away the value

  • Moving pages and masterpages

    hello, can somebody help please? I have two documents that have same master pages. when i copy (drag and drop) two pages from one file into the other i get a master page copy over the page that i have copied. what is going on??? many thanks!