Search code examples
javaswingjpaneljbuttonpaintcomponent

JPanel showing only rectangle but not JButton


void setUpGUI() {
    JFrame frame = new JFrame();
    frame.setContentPane(new Board());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setVisible(true);
}

class Board extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        setLayout(new GridLayout(10, 9));
        JButton b = new JButton("hello");
        add(b);
        g.setColor(Color.orange);
        g.fillRect(20, 50, 100, 100);
    }
}

For some reason the code only shows the rectangle, not the JButton. What am I doing wrong? Thanks!


Solution

  • The paintComponent() method is for painting only. You never create and add components to a panel in a painting method. Get rid of that code.

    Also add a super.paintComponent() at the start of the method.

    To add components to a panel you do something like:

    Board board = new Board();
    board.setLayout(...)
    board.add(...);
    

    or in the constructor of the board class you can set the layout and add components.