How to generate JLabel or JTextField on mouse click?

7

I would like to know if there is a way to generate a JLabel or JTextField in the position where you click, in JPanel or JFrame .

Is it possible?

    
asked by anonymous 19.02.2014 / 17:51

1 answer

3

Yes, it is possible:

  • Defines layout with absolute positioning with setLayout(null) on target component.
  • Add a MouseListener to the component.
  • Implement the mouseClicked event:
  • Create the desired component.
  • Add it to the target component with the add method.
  • Defines positioning and size with setBounds .
  • Here is 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);
    
        }
    
    }
    
        
    19.02.2014 / 18:55