Write a 2D Array in JFrame java

So, I was wondering that I am new to java, but I know how to do this, but I wanted to make a 2d game. Now I heard that you can do this with a 2nd array to make a map. But how did you draw a map on the screen, JFrame, like photos? So, an example of an array / map here:

1111111111 1011011001 1001100011 0000100011 0000000000 2222222222 0 = blueSky.png 1 = cloud.png 2 = grass.png 

Thanks! EDIT 2 So now I have this:

 import javax.swing.*; import java.awt.*; public class Game extends JFrame { private static final long serialVersionUID = 1L; public static void main(String[] args) { ImageIcon sky = new ImageIcon ("/Users/pro/Desktop/sky.png"); JPanel grid = new JPanel(); grid.setLayout(new GridLayout(25, 25)); for (int i = 0; i < 25; i++) { for (int n = 0; n < 25; n++) { grid.add(new JLabel(sky)); } } JFrame frame = new JFrame("Map"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //frame.setPreferredSize(new Dimension(640, 400)); frame.add(grid); frame.pack(); frame.setVisible(true); } } 

it prints some sky tiles, but how to make the bottom line a different picture?

+4
source share
2 answers

I would consider the 2D array as a model different from the GUI, that the data itself is likely to be stored in some kind of data file, possibly in a text file, that there will be methods for reading the data that the 2D array should be stored, maybe ints, possibly custom Cell classes (again, still not a GUI). Then the GUI would have to interpret the model and display the data incorrectly. Perhaps this can be done by creating a JLabels 2D grid stored in JPAnel that uses GridLayout, and then use ImageIcons to store the images and set the icon of each JLabel based on the state of the model.

Change 1
Thus, the classes used include:

  • TileType: an enumeration that associates the concept of a tile with the numbers stored in a data file
  • TileCell: not a GUI class, contains a TileType field, can also contain a list of elements that can be found in a cell (if the game needs it). May have information about their neighbors.
  • TileCellGrid: A non-GUI class containing a TileCells 2D mesh.
  • GridDataIO: utility class for reading and writing grid data to a file.
  • GameGrid: A GUI class that will contain a GridLayout, using a JPanel that contains JLabels, whose ImageIcons display the images that you list in your OP.

Edit 2
regarding your question:

Ok, how can I set the correct image for each tag?

I would use an observable / observable pattern and add a listener to the model. Whenever a model changes, it should thus notify the GUI or view. Then the view requests an array of data, will pass through it and will change the icons of the images that need to be changed when it passes through the array.

+5
source

I suggest you use JLabel with icons and lay them out using GridLayout .

Related question / answer with sample code and screenshot:

+4
source

All Articles