1

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);
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3227258
  • 37
  • 3
  • 3
  • 9
  • 1
    You don't want to add a `JLabel` at runtime, you want to change the text of a `JLabel`. Doing both is similar and there's plenty of already existing [ques](http://stackoverflow.com/questions/6578205/swing-jlabel-text-change-on-the-running-application) [tions](http://stackoverflow.com/questions/4279435/java-how-would-i-dynamically-add-swing-component-to-gui-on-click) dealing with this. – Jonathan Drapeau Jan 23 '14 at 13:40
  • 2
    See [this answer](http://stackoverflow.com/a/5630271/418556) for tips. The labels on the lower left are added dynamically. – Andrew Thompson Jan 23 '14 at 13:43
  • 2
    1) Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). 2) A single blank line of white space in source code is *always* enough. Blank lines after `{` or before `}` are also typically redundant. – Andrew Thompson Jan 23 '14 at 13:45
  • 1
    As an aside. A `JLabel` will be invisible until text is added. You might add the label at start-up, then set text to it during run-time. – Andrew Thompson Jan 23 '14 at 13:48

1 Answers1

5
  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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319