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?
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?
3
Yes, it is possible:
setLayout(null)
in the target component.MouseListener
in the component.mouseClicked
:
add
.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 java jframe
You are not signed in. Login or sign up in order to post.