0

i am not able to set the dynamically created JPanel size by using setPreferredSize function. Is there any other method ?

main_panel.removeAll();
        main_panel.revalidate();
        main_panel.repaint();
        panel = new JPanel[100];
        Login.session = Login.sessionfactory.openSession();
        Login.session.beginTransaction();
        String select_n_p_4 = "select a.triage_id from PC_TRIAGE_MASTER_POJO a";
        org.hibernate.Query query1 = Login.session.createQuery(select_n_p_4);
        List l3 = query1.list();
        Iterator it3 = l3.iterator();
        while (it3.hasNext()) {
            Object a4 = (Object) it3.next();
            int f = (int) a4;
            main_panel.setLayout(new GridLayout(0, 1, 1, 10));
            panel[ind] = new JPanel();
            panel[ind].setPreferredSize(new Dimension(10, 10));
            panel[ind].setBorder(triage_boder);
            count++;
            main_panel.add(panel[ind]);
            main_panel.revalidate();
            main_panel.repaint();
            ind++;
        }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Akarsha
  • 29
  • 2
  • 7
  • Lets start with `[Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi)` then ask what `main_panel` is using for a layout manager – MadProgrammer Mar 25 '15 at 04:05
  • Why are you not able? – Mordechai Mar 25 '15 at 04:05

1 Answers1

0

Your problem is the layout manager that you're using. GridLayout creates a uniform grid based on the size of the parent component and fits components into each cell manually. What your code seems to suggest is that you want to create a 10 x 10 JPanel for every element in l3, with each element rendered one on top of the other, separated by 10 pixels. Here's a possible approach in the context of your program using BoxLayout, which does use the sizes of individual components:

Dimension dim = new Dimension(10, 10);
main_panel.setLayout(new BoxLayout(main_panel, BoxLayout.PAGE_AXIS));
for (Iterator it3 = l3.iterator; it3.hasNext(); ) {
    panel[ind] = new JPanel();
    panel[ind].setPreferredSize(dim);
    panel[ind].setMaximumSize(dim);
    main_panel.add(panel);
    main_panel.add(Box.createRigidArea(dim));
    count++;
    ind++;
}
// you probably don't need this call
main_panel.revalidate();

In most cases, you should only set the layout of a component once, not every time you add a component. With revalidate/repaint, you should only have to call these methods if you add/remove components at runtime. Best of luck!

Community
  • 1
  • 1