-1

How can I add multiple labels to a frame when button pressed. I have a frame with some controls and I want to add some ("n" - number inserted by user in "textField") labels when "but" button is pressed.

My code is:

public class SwingDemo extends JFrame
{
protected static final JLabel[] JLabel = null;
static JLabel filozof1;
static JTextArea rezultat;
static JTextField textField;
static JButton but;
static JFrame frame;
public void start()
{
    frame = new JFrame("Filozofi chinezi");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(null);
    JLabel label = new JLabel("Numar folozofi :");
    label.setBounds(20, 20, 100, 20);
    filozof1=new JLabel();
    filozof1.setBounds(124, 50, 100, 20);
    rezultat=new JTextArea();
    rezultat.setBounds(50, 200, 700, 400);
    rezultat.setLineWrap(true);
    textField = new JTextField(2);
    textField.setBounds(124, 20, 100, 20);
    but=new JButton();
    but.setText("Start");
    but.setBounds(280, 20, 70, 20);
    frame.add(label);
    frame.add(filozof1);
    frame.add(rezultat);
    frame.add(textField);
    frame.add(but);
    frame.setSize(800,700);
    frame.setVisible(true);
}

public static void main(String args[])
{ 
    new SwingDemo().start();
    filozof1.setText("");
    rezultat.setText("");


    but.addActionListener(new ActionListener(){
                  public void actionPerformed( ActionEvent e){ 
                       Filozof[] F; int i; 
                       JLabel[] labels;
                       filozof1.setText("Button clicked");
                       n = Integer.parseInt(textField.getText());

                       labels= new JLabel[n];
                       for(i=0; i<n; i++) labels[i] = new JLabel("i");
                       for(i=0; i<n; i++) labels[i].setBounds(0, 0, 10, 10);
                       for(i=0; i<n; i++) labels.frame.add(eticheta[i]);}});
    }
}
  • 2
    Can you please remove compilation errors first ? for(i=0; i – Ninad Pingale Jun 12 '14 at 12:00
  • 3
    And also get rid of most all of your static modifiers. Your variables have no business being static. What you need to study on are how to use the Swing layout managers. Google `Java Swing Layout Manager Tutorial`. Click on the first hit. – Hovercraft Full Of Eels Jun 12 '14 at 12:17
  • 1
    Don't use null layouts, you don't control the rendering pipelines that effect the size a component needs. Consider calling revalidate, repaint after you've added the components – MadProgrammer Jun 12 '14 at 12:18
  • [This MCVE](http://stackoverflow.com/a/5630271/418556) shows how to add one label on button click. Do that in a loop. But for the number, use a `JSpinner` as seen [here](http://stackoverflow.com/a/10021773/418556). – Andrew Thompson Jun 12 '14 at 12:24

2 Answers2

1

this is a running version of your Code, but you should not use the NULL-Layout. Why are all variables static?

import java.awt.event.*;
import javax.swing.*;

public class SwingDemo extends JFrame {

    private JLabel filozof1;
    private JTextArea rezultat;
    private JTextField textField;
    private JButton but;

    public SwingDemo() {
        super("Filozofi chinezi");
        start();
    }

    public void start() {
        setLayout(null);
        JLabel label = new JLabel("Numar folozofi :");
        label.setBounds(20, 20, 100, 20);
        add(label);
        filozof1 = new JLabel();
        filozof1.setBounds(124, 50, 100, 20);
        rezultat = new JTextArea();
        rezultat.setBounds(50, 200, 700, 400);
        rezultat.setLineWrap(true);
        textField = new JTextField(2);
        textField.setBounds(124, 20, 100, 20);

        but = new JButton("Start");
        but.setBounds(280, 20, 70, 20);

        but.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = 1; i <= Integer.parseInt(textField.getText()); i++) {
                    rezultat.append(i + ". line\n");
                    // or
                    JLabel label = new JLabel(i + ". label");
                    label.setBounds(20 + (i * 25), 20 + (i * 25), 100, 20);
                    add(label);
                }
                revalidate();
                repaint();
            }
        });

        add(filozof1);
        add(rezultat);
        add(textField);
        add(but);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new SwingDemo();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setSize(800, 700);
                frame.setVisible(true);
            }
        });
    }
}
Khinsu
  • 1,487
  • 11
  • 27
0

enter image description here

Do not use null Layout. See the below Example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AddLabel extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    JPanel panel_1;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AddLabel frame = new AddLabel();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public AddLabel() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);

        JLabel lblNoOfLabels = new JLabel("Enter no of labels");

        textField = new JTextField();
        textField.setColumns(10);

        JButton btnAdd = new JButton("Add");
        GroupLayout gl_panel = new GroupLayout(panel);
        gl_panel.setHorizontalGroup(
            gl_panel.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel.createSequentialGroup()
                    .addComponent(lblNoOfLabels)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGap(32)
                    .addComponent(btnAdd)
                    .addContainerGap(157, Short.MAX_VALUE))
        );
        gl_panel.setVerticalGroup(
            gl_panel.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                        .addComponent(lblNoOfLabels)
                        .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnAdd)))
        );
        panel.setLayout(gl_panel);


        panel_1 = new JPanel();
        JScrollPane jsp = new JScrollPane(panel_1);
        jsp.setPreferredSize(new Dimension(getWidth(), 60));
        contentPane.add(jsp, BorderLayout.CENTER);

        GridBagLayout gbl_panel = new GridBagLayout();
        gbl_panel.columnWidths = new int[]{0, 0, 0, 0};
        gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
        gbl_panel.columnWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
        gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};

        panel_1.setLayout(gbl_panel);        
        panel_1.setBackground(Color.white);

        btnAdd.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(!textField.getText().equals(""))
                    addlabels(Integer.parseInt(textField.getText()));
                panel_1.revalidate();


            }
        });
        pack();
    }
    public void addlabels(int num)
    {
        for(int i=0;i<num;i++)
        {
            panel_1.add(new JLabel("Label "+i),new GridBagConstraints( 1,  i,  1,  1, 
                    1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));

        }

    }
}
Arijit
  • 1,633
  • 2
  • 21
  • 35