I am writing a 2D strategy game and require to be able to display hundreds of images at one time.
So far I have many classes, but I have one dilemma as I fear I do not understand the JFrame
components well enough. I have written a smaller 3 class program to show my problem:
First I have a main class which constructs the frame:
import javax.swing.JFrame;
public class MainClass {
static JFrame Frame = new JFrame("MainFrame");
public static void main(String[] args){
Frame.add(new Board());
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setSize(1024, 500);
Frame.setVisible(true);
Frame.setResizable(false);
}
}
Currently the board class is the class which sits at the center of the program and pulls all of the strings to make the program run. Previously all of the tutorials I have seen on the internet have pointed towards having the paint(Graphics g)
method inside the board class, but this gives me the main dilemma. Currently I have to type out manually every time I want something painted to the screen:
public board{
//......code....
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(b.getImage(0), 0, 0, null);//Black
g2d.drawImage(b.getImage(1), GameMachanic.getCurrentPosX(), GameMachanic.getCurrentPosY(), null);//background
g2d.drawImage(b.getImage(3), GameMachanic.getCurrentPosX(), GameMachanic.getCurrentPosY(), null);//background
//...more paint to screen code
}
//......code......
}
This method is repainted every few milliseconds and everything is great! except... now I have gotten to the point where I need hundreds of different elements painted to the screen at one time, from different classes and with this current method U have to type out manually each and every paint command, making the code ineffective and frankly pointless.
Therefore I tried making a class that replaces the need of this manual labour, making the method reusable, but I am finding it extremely hard to make it work:
public class GraphicsPaint extends JFrame{
public void paint(Graphics g, ){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(b.getImage(0), 0, 0, null);//image
}
}
But how do I implement this class into my code, do I add it as a component? (And if so, how?) Because I have tried this and it just throws an error at me, and I have tried using a few layouts but they just glitch up for some reason.
Do I add them to Panels? I have no idea how that would pan out..
Other than that I am clueless as I have spent the whole day looking at this problem.