0
I’m having a hard time adding Abels in different positions, relative to a field (JTextField
). I’d like to put one label
before the field, the left, and a second label
under the JTextField
.
I tried to use some layout managers, including the GridBagConstraints
, however, not being able to do what I wanted. Someone could give me at least one direction how to do ?
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TesteLabel extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(()
-> {
TesteLabel testeLabel = new TesteLabel();
});
}
public TesteLabel() {
add(addComponent());
setSize(500, 200);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JComponent addComponent() {
JPanel painelPrincipal = new JPanel();
JPanel painel = new JPanel();
painel.setLayout(new FlowLayout());
JLabel labelLateral = new JLabel("Label Lateral: ");
JLabel labelInferior = new JLabel("Label Inferior: ");
JTextField jTextField = new JTextField();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 1;
gbc.gridx = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.insets = new Insets(5, 5, 5, 5);
//painel.add(labelLateral, jTextField);
painel.add(labelLateral);
painel.add(jTextField);
painel.add(labelInferior, gbc);
jTextField.setPreferredSize(new Dimension(200, 25));
painelPrincipal.add(painel);
return painelPrincipal;
}
}