Search code examples
javaswingjpaneljlabeljtextfield

JTextField and JLabel not appearing


My JLabel and JTextField are not appearing overtop the image and I'm not sure why. I've put the image on a JLabel and setOpaque(false) but no luck. Any advice? Thanks for the help in advance.

       private JTextField tf;
       private JLabel jl2;
       private JLabel jl3;

       public void window() {
           ImageIcon ic = new ImageIcon("hangman.png");
          JFrame gameFrame = new JFrame();
          JPanel jp = new JPanel();
          jp.setOpaque(false); //!!
          jp.setBorder(BorderFactory.createTitledBorder(""));
          JLabel img = new JLabel(ic, JLabel.CENTER);
          img.setOpaque(false);
          JLabel jl = new JLabel("Enter a Letter:");
          jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
          tf = new JTextField(1);
          jl2 = new JLabel("Letters Used:    ");
          jl3 = new JLabel();//blank spaces
          tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
          jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
          jp.add(jl);
          jp.add(tf);
          jp.add(jl2);
          jp.add(jl3);
          gameFrame.add(img);
          img.add(jp);
          gameFrame.setTitle("Hangman");
          gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          gameFrame.setIconImage(
          new ImageIcon("Hangman-Game-grey.png").getImage());
          gameFrame.setResizable(false);
          gameFrame.pack();
          gameFrame.setLocationRelativeTo(null);
          gameFrame.setVisible(true);

Solution

  • A JLabel doesn't use a layout manager by default so components added to the label will not be painted.

    Try setting the layout manager. Maybe:

    img.setLayout( new BorderLayout() );
    

    or choose a layout that meets your requirements.