When I came across this problem at first I found out that I could just store everything I wish to display in a list and then display it from that list, problem is I am not really sure how that is done since the problem of my old graphics disappearing still persists. Here are the 2 files I am having a problem with Main file:
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class probvam extends JPanel {
public static void Game(){
JFrame window = new JFrame();
window.add(new Field(0, 0, 560/3, 560/3));
window.add(new Field(560/3, 0, 560/3, 560/3));
window.setTitle("zvunqt mi po iphona");
window.setSize(560, 560);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setVisible(true);
}
public static void main(String[] args) {
Game();
}
}
And the second file containing the list and paint method:
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class Field extends JPanel{
public ArrayList<Field> ground = new ArrayList<>();
int width, height, x, y;
public Field(int x, int y, int w, int h) {
this.width = w;
this.height = h;
this.x = x;
this.y = y;
ground.add(this);
}
@Override
public void paintComponent (Graphics g){
for(Field f: ground){
g.drawRect(f.x, f.y, f.width, f.height);
}
}
}
The idea of this is to get it to display 9 rectangles as their own objects as I wish to make a tic tac toe game where each square is an object but I cant seem to display them all at the same time. The paint function is really a pain.