Drawing Rectangle in Java Shows Pixel Anomaly

java, swing

Solution

For sake of an answer in case anyone comes across this question

The problem seemed to be with the Java 8 pre-release version. This code works fine with Java 7.

Note: This conclusion was taken from the comments section and I did not contribute to the answer. :-)

Problem

I have a very simple java program that draws a rectangle but when I closely examine the rendered shape, I see two extra pixels that shouldn't be there ... You can see one extra pixel at below left and one at below right. I am using Windows 7 Professional 64-BIT using JDK 1.8.0. Here is the program ... ``` import java.awt.Graphics; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JPanel; public class JavaBug { public JavaBug() throws IOException { JFrame frame = new JFrame(); frame.add( new JPanel() { private static final long serialVersionUID = 1L; public void paintComponent( Graphics g ) { super.paintComponent(g); g.drawRect(50, 50, 20, 20); } }); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible( true ); } public static void main(String [] args) throws IOException { new JavaBug(); } } ```

Original source