Question

Hi I have a small problem. I have a JFrame with a JComponent I use to display graphics.

The component's preferable size is 800x600 and I create the JFrame with the JComponent like this (GC being the component):

public static void main(String[] args) {

  mainframe = new JFrame();
  mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  mainframe.add(GC);
  mainframe.pack();
  mainframe.setResizable(false);
  mainframe.setVisible(true);

}

Then I paint graphics like this:

public void paintComponent(final Graphics g)
{
    //temp bg
    g.setColor(Color.red);
    g.fillRect(Global.leftborder, 0, 600, 600);

            //code code.....
    }

Problem is that it leaves 10pixels of white at the button of the component even though the component is 600 pixels in height. I've realized this is because (0,0) is at the top-left of the whole window rather than on the component.

Is there a way to fix this without having to add 10pixels to the height and width each time I draw something?

Was it helpful?

Solution

You should override the components paintComponent method and not the frames. This way the translations should already have been made correctly.


Full example:

public class Test {
    public static void main(String[] args) {

        JFrame frame = new JFrame("Test");

        frame.add(new TestComponent());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    static class TestComponent extends JComponent {
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(800, 600);
        }

        @Override
        protected void paintComponent(Graphics g) {
            g.setColor(Color.red);
            g.fillRect(10, 0, 600, 600);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top