java - Why aren't my label and button showing up in my JFrame? -
java - Why aren't my label and button showing up in my JFrame? -
i can not seem figure out life of me. excuse me if there redundant code kept trying , trying , couldn't figure out. jframe
shows button , label not appearing.
import javax.swing.*; import java.awt.event.*; import java.awt.*; public class ex03 { int w = 20; int h = 20; public ex03() { jframe fra = new jframe(""); fra.setbounds(10, 10, 200, 200); fra.setlayout(null); fra.setdefaultcloseoperation(jframe.exit_on_close); fra.setvisible(true); jpanel pan = new jpanel(); pan.setlayout(null); pan.setvisible(true); fra.getcontentpane().add(pan); jlabel lab = new jlabel(); lab.setbounds(10, 10, w, h); lab.setopaque(true); lab.setbackground(color.blue); lab.setvisible(true); jbutton = new jbutton("play"); but.setbounds(10, 10, 100, 35); but.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { w++; h++; } }); but.setvisible(true); pan.add(lab); pan.add(but); } public static void main (string[] args) { new ex03(); } }
the problem add together both button , label after top-level container (window) made visible. components hierarchy must revalidated in order create components visible well:
pan.add(lab); pan.add(but); pan.revalidate(); pan.repaint();
as per container#add(component comp) documentation:
this method changes layout-related information, , therefore, invalidates component hierarchy. if container has been displayed, hierarchy must validated thereafter in order display added component.
on other hand improve practice pack , create window visible after adding components, components hierarchy validated once.
pan.add(lab); pan.add(but); ... frame.add(pan); frame.pack(); frame.setvisible(true);
other comments please note swing designed work layout managers , methods such setbounds(...)
, setlocation(...)
, setxxxsize(...)
discouraged. components position , size layout manager's responsibility not developer's, unless have reason it. doing without layout manager (absolute positioning) section:
although possible without layout manager, should utilize layout manager if @ possible. layout manager makes easier adjust look-and-feel-dependent component appearances, different font sizes, container's changing size, , different locales. layout managers can reused other containers, other programs.
java swing user-interface jframe layout-manager
Comments
Post a Comment