I have a board game (think Monopoly) where multiple game pieces can be located on a single tile. I got 4 circles drawn on a green background, but the circles are not centered and when I resize them the circles move all over the place instead of staying with the tile.
CirclePanel:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class CirclePanel extends JPanel {
public static final Dimension SIZE = new Dimension(35, 35);
public CirclePanel() {
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.RED);
g.fillOval(0, 0, 35, 35);
System.out.println(getSize());
}
@Override
public Dimension getPreferredSize() {
return SIZE;
}
}
GraphicsTile:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
@SuppressWarnings("serial")
public class GraphicsTile extends JPanel {
public static final Dimension SIZE = new Dimension(140, 140);
public static final GridLayout MGR = new GridLayout(2, 2);
public GraphicsTile() {
super();
setLayout(MGR);
add(new CirclePanel());
add(new CirclePanel());
add(new CirclePanel());
add(new CirclePanel());
}
@Override
public Dimension getPreferredSize() {
return SIZE;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, 140, 140);
}
}
GraphicsRunner:
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
public class GraphicsRunner {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(4, 0, 5, 5));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1280, 720);
frame.setPreferredSize(new Dimension(140, 140));
frame.add(new GraphicsTile());
frame.add(new GraphicsTile());
frame.setVisible(true);
}
}