Akos
Akos

Reputation: 220

JPanel still has buttons after removeall()

I'm working on a project which is using a JPanel populated with dynamically generated buttons, read from a list which is populated from a DB.
I have a next and a previous button to shuffle through the pages. Everything works fine on the first two pages, but on the third, when the remaining size of the list is less than 32(max buttons to fit perfectly on the page), and only 5 buttons remain to be "generated", the old buttons from the previous page show up, even though I call jPanel.removeAll(), and I tried to add jPanel.revalidate() also.

Note, the lists content does not change.

Here is the code:

private void loadCat(int catnr) { //loads second,third,etc. category page
    jMainPanel.removeAll();
    jMainPanel.revalidate();

    for (int i = catnr; i < engine.LoadItems.catlist.size(); i++) {
        if (i == catnr + 32) // more than 32 buttons do not fit per page
            break;
        final JButton btn = new JButton();
        btn.setPreferredSize(new Dimension(100, 50));
        btn.setText(engine.LoadItems.catlist.get(i));
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                //some code here (...)
            }
       });
       jMainPanel.add(btn);
       jMainPanel.setPreferredSize(new Dimension(436, 480));
       jMainPanel.revalidate();  
    }
}

Question: How do I get the panel to display only the remaining items on page 3(or on any page in the future)? What am I doing wrong?

Screenshots:

http://oi59.tinypic.com/2dqisug.jpg

http://oi60.tinypic.com/ifoqiu.jpg

Upvotes: 0

Views: 101

Answers (1)

StanislavL
StanislavL

Reputation: 57381

After adding add/remove components call

revalidate();
repaint();

revalidate calls layout manager to recalculate all the components' sizes and repaint repaints newly sized components.

Upvotes: 3

Related Questions