There isn't enough context to provide a complete answer.
This is simply another possible solution to your problem....
If your intention is to try and place a component at a specific position, then why not just set its background color instead of trying to fill it using custom painting?
If you intention is to paint lots of little squares, then you don't need a separate component for each...
Swing is designed to utilise the layout manager API, it's at the core of how the framework works.
While I'll be the first to admit there are times a null
layout is useful, I'd try a lot of things first (personally).
The following example uses a single component, but allows you to draw multiple boxes onto at varying positions and sizes...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GraphicsExample {
public static void main(String[] args) {
new GraphicsExample();
}
public GraphicsExample() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
TestPane tp = new TestPane();
tp.add(50, 50, 40, 40);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private List<Rectangle> boxes;
public TestPane() {
boxes = new ArrayList<Rectangle>(25);
}
public void add(int x, int y, int width, int height) {
boxes.add(new Rectangle(x, y, width, height));
repaint();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
for (Rectangle box : boxes) {
g2d.fill(box);
}
g2d.dispose();
}
}
}
One of the other things you are doing wrong is not honouring the paint chain. When you override one of the paint
methods, you must call super.paintXxx
to ensure that the paint chain isn't broken. This methods do a lot of important work and are very unforgiving if you forget to include them ;)
Check out Performing Custom Painting for more details