Sunday, 5 February 2017

Program to 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


No comments:

Post a Comment