I placed two components inside a JLayeredPane
but I can't make them visible. Here is a fairly MCV
code. How do I see my JTextField
and JLabel
inside the layeredPane
?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
public class GUI extends JFrame {
JFrame mainframe = new JFrame();
JPanel centrejPanel = new JPanel();
JTextField keyText;
JLabel jLabel;
public GUI() {
mainframe.setLayout(new BorderLayout());
mainframe.setSize(1200, 700);
mainframe.getContentPane().add(centrejPanel, BorderLayout.CENTER);
keyText = new JTextField("hello");
keyText.setOpaque(false);
keyText.setCaretColor(Color.BLACK);
keyText.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
jLabel = new JLabel("hello");
jLabel.setFont(new Font("Palatino", Font.BOLD, 18));
jLabel.setVerticalAlignment(JLabel.TOP);
jLabel.setForeground(Color.GRAY);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.add(keyText, 1);
layeredPane.add(jLabel, 0);
centrejPanel.getRootPane().add(layeredPane);
mainframe.setVisible(true);
}
}
public class Main {
public static void main(String[] args) {
GUI gui = new GUI();
}
}
//mainframe.setLayout(new BorderLayout());
Not needed. The default layout manager of the content pane of the frame is a BorderLayout.
//mainframe.getContentPane().add(centrejPanel, BorderLayout.CENTER);
Don't add an empty panel to the content pane of the frame. Just add the LayeredPane directly to the content pane.
keyText.setBounds(0, 50, 100, 20);
...
jLabel.setBounds(0, 150, 100, 20);
A JLayeredPane uses a null layout so it is your responsibility to set the size and location of each component added to the layered pane.
//centrejPanel.getRootPane().add(layeredPane);
Don't add the layered pane to the root pane. Don't even know if this will work but in any case the content pane will just cover the layered pane.
Read the section from the Swing tutorial on Using Top Level Containers to see how all the frame layers are structured.
mainframe.add(layeredPane);
Just add the layered pane directly to the content pane of the frame. Read the Swing tutorial on How to Use LayeredPane for more information and working examples.
Always start with examples from the tutorial when learning a new concept or component.