How to add JLabel at run time in Swing?

蓝咒 提交于 2020-07-20 01:17:50

问题


I am making am window application on Java. I want to add label name at run time in my Swing application. How can I do this using Java Swing?

public class Component1 extends JPanel {

   Component1() {
      JLabel label = new JLabel("dd");
      label.setBounds(370, 340, 150, 20);
     // label.setText("labeVVl");
      add(label);
}

 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);
}
}

回答1:


  1. this code should be works by add revalidate() and repaint() as notifiers for LayoutManager

  2. don't to use NullLayout, use default FlowLayout implemented for JPanel in API do that the same way

  3. see Initial Thread

  4. for example



来源:https://stackoverflow.com/questions/21309627/how-to-add-jlabel-at-run-time-in-swing

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