Search code examples
javaswinglinedrawgraphic

Why java swing drawLine doesn't correct width?


I am writing some simple java graphic app. This is my problem:

package graphic;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class TestFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private JPanel panel;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TestFrame frame = new TestFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public TestFrame() {
        setTitle("Test Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        panel = new JPanel(){
            private static final long serialVersionUID = 1L;

            @Override
            public void paintComponent(Graphics g){
                super.paintComponent(g);
                final int MAX = 100;

                //Draw grid
                for (int i = 0; i < MAX; i++)
                    if (i % 2 == 0){
                        g.drawLine(0, i, MAX, i);
                        g.drawLine(i, 0, i, MAX);
                    }

                g.setColor(Color.RED);
                g.drawLine(0, 0, 0, 0);//width = 1
                g.drawLine(0, 2, 1, 2);//width = 2
                g.drawLine(0, 4, 2, 4);//width = 3
                g.drawLine(0, 6, 3, 6);//width = 4


            }
        };

        panel.setBorder(new EmptyBorder(5, 5, 5, 5));
        panel.setLayout(new BorderLayout(0, 0));
        setContentPane(panel);

    }

}

I draw 4 lines in the JPanel. The result is as follows: enter image description here But the second line take 3 "square pixel", while x1 = 0, x2 = 1 then line width is 2 square only? There is the same problem with the 3rd and 4th line. Any one can explain for me? Thanks


Solution

  • Either

    1. Something is messed up with your graphics system. Perhaps you have some kind of magnification or scaling on your screen going on.

    2. There's a bug in your runtime implementation. If so you may want to file a bug and specify your os and runtime.

    This is the result on my system:

    enter image description here