Program for dynamically creating and adding JLabels

In this tutorial, we will create a JFrame that contains JTextField, JPanel and JLabels. We have to add the number of JLabels that are entered in JTextField. For example, if we have entered number 4 then four labels will be added in JPanel.





To accomplish this task we have used here CaretListener interface and its method caretUpdate( ).

SOURCE CODE
import java.awt.Color;
import javax.swing.*;
import javax.swing.event.*;

class CreateLabelsDynamically extends JFrame implements CaretListener {
 
 JTextField jtf;
 JPanel jpan;
 
 public CreateLabelsDynamically() {
  
  jtf = new JTextField(10);
  jpan = new JPanel();
  
  setLayout(null);
  
  jtf.setBounds(50, 20, 50, 30);
  jtf.addCaretListener(this);
  
  jpan.setBounds(50, 80, 200, 200);
  jpan.setOpaque(true);
  jpan.setBackground(Color.CYAN);
  
  add(jtf);
  add(jpan);
 }
 
 public void caretUpdate(CaretEvent ce)  {
  
  String str = jtf.getText();
  
  jpan.removeAll();
  
  if(!str.equals("")) {
   int num = Integer.parseInt(str);
   JLabel jlabels[] = new JLabel[num];
   
   for(int i = 0; i < jlabels.length; i++) {
    jlabels[i] = new JLabel("Label" + i);
    jpan.add(jlabels[i]);
   }
  }
  jpan.validate();
  jpan.repaint();
 }
 
 public static void main(String args[]) {
  
  CreateLabelsDynamically c = new CreateLabelsDynamically();
  c.setTitle("My Frame");
  c.setSize(300,350);
  c.setVisible(true);
 }
}

OUTPUT 

C:\>javac CreateLabelsDynamically.java 
C:\>java CreateLabelsDynamically


Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative