Search code examples
javaswingjpanellayout-managerjava-2d

Having trouble adding graphics to JPanel


I have looked online, but I am still having trouble understanding how to add graphics to a JPanel

Here is the code for my panel class:

public class GamePanel extends JPanel {

    public GamePanel(){

    }

    public void paintComponent(Graphics g) {

        g.drawString("asd", 5, 5);
    }

}

And my main method:

public static void main(String[] args) {

    frame.setLayout(new FlowLayout());
    frame.getContentPane().setBackground(Color.WHITE);

    //i is an instance of GamePanel
    frame.add(i);

    frame.setPreferredSize(new Dimension(500, 500));
    frame.pack();
    frame.setVisible(true);

}

Text will only appear in a very tiny section of the screen (this applies to any graphics object I try to draw). What am I doing wrong?


Solution

  • FlowLayout respects preferred sizes of components. Therefore override getPreferredSize to give your JPanel a visible size rather than the default zero size Dimension that the panel currently has after JFrame#pack is called:

    class GamePanel extends JPanel {
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g); // added to paint child components
            g.drawString("asd", 5, 20);
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 300);
        }
    }
    

    Edit:

    To eliminate gap between JPanel and its containing JFrame, set the vertical gap to 0:

    frame.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));