I want to set a background for my game.
Scenario:
First of all, I have to read from a text file, and then draw my tile map and images on it base on that texts. Second, my map is 3600*2400 pixels and it's larger than my screen so I have to scroll it. Third, there must be a mini map on the corner of my screen showing me where i am. (I guess I should use panels and awt.container
.)
Here is my code:
public class bkg extends Panel implements ImageObserver {
//i Initialize my variables here
// then read my images with image buffer in constructor
public static void main(String[] args) {
//my three panels and frame settings
Frame frame = new Frame();
frame.setLayout(null);
frame.setSize(1350, 700);
frame.setTitle("age of empires");
frame.setVisible(true);
frame.setLayout(null);
Panel p1 = new Panel();
Panel p2 = new Panel();
p2.setLayout(null);
JPanel p3 = new JPanel();
p3.setLayout(null);
p1.setSize(1350, 700); // i divide my screen in to 3 parts , one biggest panel, and two small. the biggest one is for main map
p1.setLayout(null);
p2.setBackground(Color.cyan);//just wanna test showing my panel.
p2.setSize(675, 350);
p3.setSize(675, 350);
p1.setLocation(0, 0);
p2.setLocation(0, 350);// this small panel must be under the main pannel.
p3.setLocation(675, 350);// this is with p2.
frame.add(p1);
p1.add(p2);
p2.add(p3);
tilemap = new int[60][75];// it creat my tilemap in console.
filereader();// it reads the text file.
}
@Override
public void paint(Graphics g) {
super.paint(g);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int mod_i = 100 * i;// based on images sizes
int mod_j = 50 * j;// based on images sizes
//now i start to draw images base on the text file numbers
switch (tilemap[i][j]) {
case 1:
g.drawImage(tree, mod_i, mod_j, null);
break;
.........
}
}
}
}
Question: Seems that my code can't even see the paint method. It doesn't draw any images on my panels. What's the problem?
Your code is so full of errors that I started from the beginning to create a GUI divided into 3 areas.
You must start a Swing application with a call to the SwingUtilities invokeLater method. This ensures that the Swing application starts on the Event Dispatch thread (EDT).
A Java class name starts with a capital letter. Java method names and variable names start with a lowercase letter.
Don't put everything in your main method. Break your code up into methods that do one thing well. My run method creates the JFrame. My createMainPanel method creates the main panel.
I used Swing layout managers to position the JPanels. Yes, using absolute positioning seems like it's easier, but you can't move your application to any other computer with a different screen resolution.
I decided to stop at this point. You would create further methods and / or classes to further define the 3 JPanels. In those JPanel methods / classes, you would override the paintComponent method, not the paint method.
Here's the code.