Adding jlabel to a jframe using components

混江龙づ霸主 提交于 2019-12-03 01:13:33

问题


I have 2 classes,

My main class creates a frame and I want another class to add content to it. A bit of reading arroudn told me I should use components to do this however when I run my code the frame is empty.

 public static void main(String[] args)
 {
    // create frame
    JFrame frame = new JFrame();
    final int FRAME_WIDTH = 800;
    final int FRAME_HEIGHT = 600;
    // set frame attributes
    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setTitle("My Frame");
    frame.setVisible(true);

    Component1 Com = new Component1();
    Component add = frame.add(Com);

}

My Component class creates a JLabel

public class Component1 extends JComponent {

   public void paintComponent()
   {
       JLabel label = new JLabel("<html>Some Text</html>");
   }
}

I don't get any compile errors, however I dont get any text in my JFrame.

Can anyone explain what I'm doing wrong?

Chris


回答1:


You need to add the JLabel. Also better to extend JPanel instead of JComponent as it has a default layout manager and will make any added components appear without the need to set component sizes. paintComponent is used for custom painting BTW.

public class Component1 extends JPanel {

   Component1() {
      JLabel label = new JLabel("<html>Some Text</html>");
      add(label);
   }
}



回答2:


No need to create a new Component. Just call frame.getContentPane().add(label). And initialize your label before this.



来源:https://stackoverflow.com/questions/13808329/adding-jlabel-to-a-jframe-using-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!