Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I place a component in a JLayeredPane right below an existing component?

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);
}

enter image description here

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);
}

enter image description here

like image 977
Jonas Avatar asked Feb 23 '23 05:02

Jonas


1 Answers

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.

like image 157
camickr Avatar answered May 11 '23 03:05

camickr