How to generate Jlabel or Jtextfield at mouse click?

Asked

Viewed 658 times

7

I wonder if there is a way to generate a JLabel or JTextField at the position where you click, on a JPanel or a JFrame.

It is possible?

1 answer

3


Yes, it is possible:

  1. Sets the layout with absolute positioning with setLayout(null) in the target component.
  2. Add a MouseListener in the component.
  3. Implement the event mouseClicked:
    1. Create the desired component.
    2. Add it to the target component with the method add.
    3. Sets the positioning and size with setBounds.

Here’s a simple example I did:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class TextFieldGeneratorTest {

    private static int contador = 0;

    public static void main(String[] args) {

        //janela
        final JFrame janela = new JFrame("Test JTextField Generation");

        //posicionamento sem nenhum layout, isto é, absoluto
        janela.getContentPane().setLayout(null);

        //adiciona listener do mouse
        janela.getContentPane().addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent event) {

                //adiciona dinamicamente no clique
                final JTextField textField = new JTextField("Caixa " + ++contador);
                textField.setBounds(event.getX(), event.getY(), 200, 30);
                janela.getContentPane().add(textField);

            }
        });

        //exibe a janela
        janela.setSize(600,  600);
        janela.setVisible(true);

    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.