I have a JTextField, and right below it I want to show a JLabel placed in a JLayeredPane (I will use it for autosuggestions later on).
How can I place my JLabel in JLayeredPane right below the JTextField?
Here is some code I have, and the current result shown in the screenshot below:
public static void main(String[] args) {
JTextField field = new JTextField();
JLabel lbl = new JLabel("Hello");
lbl.setBackground(Color.YELLOW);
lbl.setOpaque(true);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setLayout(new GridLayout(0,1));
layeredPane.add(lbl, (Integer) (JLayeredPane.POPUP_LAYER - 10));
layeredPane.setPreferredSize(field.getPreferredSize());
JPanel panel = new JPanel(new BorderLayout());
panel.add(field, BorderLayout.NORTH);
panel.add(layeredPane, BorderLayout.SOUTH);
JFrame frame = new JFrame();
frame.add(panel);
frame.setSize(200, 360);
frame.setVisible(true);
}
Second try:
public static void main(String[] args) {
JTextField field = new JTextField();
JLabel lbl = new JLabel("Hello");
lbl.setBackground(Color.YELLOW);
lbl.setOpaque(true);
lbl.setBounds(field.getBounds().x, field.getBounds().y,
field.getBounds().width, field.getBounds().height);
JPanel popPanel = new JPanel(new BorderLayout());
popPanel.add(lbl, BorderLayout.NORTH);
popPanel.setLocation(field.getLocation().x+10, field.getLocation().y+20);
popPanel.setPreferredSize(field.getPreferredSize());
JFrame frame = new JFrame();
JLayeredPane layeredPane = frame.getRootPane().getLayeredPane();
layeredPane.setLayout(new GridLayout(0,1));
layeredPane.add(popPanel, (Integer) (JLayeredPane.POPUP_LAYER - 10));
JPanel panel = new JPanel(new BorderLayout());
panel.add(field, BorderLayout.NORTH);
frame.add(panel);
frame.setSize(200, 360);
frame.setVisible(true);
}
Add the layeredPane to the "CENTER", not the SOUTH.
However, your understanding a layed pane seems to be a little confused. You use a layered pane when you want multiple components to be displayed on top (stacked?) of one another. You are still using the layered pane in 2 dimensions which is unnecessary. YOu can just use a panel for this.
If you want to popup a list of suggestions then you should just use a JPopupMenu and position it below the text field. Read the section from the Swing tutorial on Bringing up Popup Menus.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With