Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Can't see why this tool for making graphics in Java isn't being precise

I'm trying to explore how a graphics app would be made in Java. I'm having a problem where the combination below of JFrame, JLabel and BufferedImage causes an incorrect number of pixels to be drawn, i.e., rather than a single pixel being drawn in a 5x5 frame—as the code below would lead you to think—it draws something like a 7x8 frame with 2 pixels drawn. The picture found in the Dropbox link at the bottom of this post shows this happening, using GIMP to zoom in to the pixel-level to see what's going-on. Obviously that's not good enough, and there must be a precise way of allocating pixels just because good graphics exist in 2024.

JLabel label = new JLabel(); 
JFrame frame = new JFrame(); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
BufferedImage image = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB); 
Graphics2D g;
g = image.createGraphics();
Color background = new Color(0, 0, 0);
Color c = new Color(0.5f, 0.5f, 0.5f);
g.setPaint(background); g.fillRect(0, 0, 5, 5); g.dispose();

frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true); 

image.setRGB(2, 3, c.getRGB());
label.setIcon(new ImageIcon(image)); 
frame.getContentPane().add(label, BorderLayout.CENTER);

https://www.dropbox.com/scl/fi/2nc6dkx3drgjskb01uk2p/Screenshot-1928.png?rlkey=jq7ximmjhzktuexa1oefzh023&st=ilnw2o6g&dl=0