java swing redrawing buttons -
i pasting following code here. puzzled at: why there no jbuttons added jpanel, though event correctly listened , responded.
thank help.
import java.awt.component; import java.awt.toolkit; import java.awt.event.keyadapter; import java.awt.event.keyevent; import javax.swing.boxlayout; import javax.swing.grouplayout; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.jtextfield; public class panelcontrolbuttons extends jframe { private jpanel jpanel1 = new jpanel(); private jpanel jpanel2 = new jpanel(); private jpanel jpanel = new jpanel(); private jtextfield jtf = new jtextfield(20); public panelcontrolbuttons() { setsize(400, 300); getcontentpane().add(jpanel); jpanel.setlayout(new boxlayout(jpanel, boxlayout.x_axis)); jpanel2.setlayout(new boxlayout(jpanel2, boxlayout.x_axis)); jpanel.add(jpanel1); jpanel.add(jpanel2); jpanel2.add(new jbutton("abc")); (int = 0; < 3; i++) { jpanel2.add(new jbutton(integer.tostring(i))); } jpanel1.add(jtf); jpanel2.setlayout(new boxlayout(jpanel2, boxlayout.x_axis)); jtf.addkeylistener(new keyadapter() { public void keypressed(keyevent e) { int key = e.getkeycode(); if (key == keyevent.vk_enter) { system.out.println("enter pressed"); int n = integer.parseint(jtf.gettext()); system.out.println(n); (int = 0; < n; i++) { jpanel2.add(new jbutton(integer.tostring(i))); } } } }); setvisible(true); } public static void main(string[] args) { panelcontrolbuttons panelcontrolbuttons = new panelcontrolbuttons(); } }
anytime add new component on container, should call revalidate , repaint:
(int = 0; < n; i++) { jpanel2.add(new jbutton(integer.tostring(i))); } jpanel2.revalidate(); jpanel2.repaint();
the first tell layout managers thing, second have java paint manager repaint container redraw dirty bits.
edit
revalidate , repaint methods moved out of loop per mkorbel's excellent recommendation.
Comments
Post a Comment