0

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.

  • 2
    *"I wish to make a tic tac toe game where each square is an object"* Use a 3x3 `GridLayout` of `JButton` components. Here is a [basic implementation](https://stackoverflow.com/a/67302034/418556) of what I mean. – Andrew Thompson Oct 26 '21 at 13:36
  • *my old graphics disappearing still persists* - you need to understand how layout managers work. The default layout of the JFrame is a BorderLayout. You can only add a single component to the `BorderLayout.CENTER` which is the default when you don't specify a constraint. Read the Swing tutorial on [Layout Managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) for more information. Your painting code is wrong. Read the section on [Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html). Keep a link to the tutorial handy for Swing basics. – camickr Oct 26 '21 at 14:21
  • Your ArrayList does nothing and is not needed. Why would you create an ArrayList to hold components when you only ever have a single component? Using existing components (JButton) is definitely an easier way to start to learn Swing. – camickr Oct 26 '21 at 14:22

0 Answers0