I am having an issue with a custom drawn image rendered on the JPanel with Graphics2D. If I try to draw a 1×1 pixel for every x/y the width and length of the panel with fillRect
it will create a bunch of different sized rects of 1×1, 1×2, and 2×2 in a pattern. I’ve tried playing with the Graphics2D rendering hints but could not figure out what is causing this to happen.
Here is a zoomed in view of what is happening, the rect sizing appears to create a pattern as well.
Here is a minimally viable example that should be printing 1×1 rects.
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
class Scratch {
public static final int WIDTH = 400;
public static final int HEIGHT = 400;
public static void main(String[] args) {
BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2d = img.createGraphics();
JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D panel2d = (Graphics2D) g;
// Black bg
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
int c = 0;
for (int x = 0; x < getWidth(); x++) {
for (int y = 0; y < getHeight(); y++) {
g2d.setColor(new Color((c += 13) % 255, (c += 17) % 255, (c += 23) % 255));
g2d.fillRect(x, y, 1, 1);
}
}
panel2d.drawImage(img, null, 0, 0);
}
};
JFrame frame = new JFrame("Scratch");
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.getContentPane().setPreferredSize(new Dimension(WIDTH, HEIGHT));
frame.pack();
}
}
Or should I be using something other than Graphics2D to do this?