mbdavis
mbdavis

Reputation: 4010

Unwanted JPanel border in JFrame

I am trying to fill JFrame with a JPanel and colour that JPanel, but for some reason I get a border on the bottom right edges.

My code:

public class Main extends JFrame {

    public MyPanel myPanel = new MyPanel();

    public static void main(String args[])
    {
        Main main = new Main();
        main.init();
    }

    public void init()
    {
        this.setSize(300,400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setContentPane(myPanel);
        this.setVisible(true);
    }

    @Override
    public void paint(Graphics g)
    {
        myPanel.paintComponents(g);
    }

    class MyPanel extends JPanel
    {
        @Override
        public void paintComponents(Graphics g)
        {
            g.fillRect(0, 0, getWidth(), getHeight());
        }
    }
}

Shows:

enter image description here

Upvotes: 0

Views: 77

Answers (1)

Reimeus
Reimeus

Reputation: 159754

You're short-circuiting the paint chain with this method

@Override
public void paint(Graphics g) {
    myPanel.paintComponents(g);
}

This isnt really doing anything useful so you can remove it. Also you need to override paintComponent rather than paintComponents in MyPanel

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.fillRect(0, 0, getWidth(), getHeight());
    }

Aside:

  • You could have simply created a panel and called setBackground to get this functionality

Upvotes: 3

Related Questions