Search code examples
javaswingjframejlabel

JLabel doesn't display anything in JFrame


I think and hope this is a minor issue.

I have a JFrame which gets displayed in a snake game. The text, e.g "Game Over, your snake is crashed" or something, will display in a JLabel.

The problem is my JLabel is always empty!

Here's the code:

package ch.gibb.snake1;

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class endFrame extends JFrame {

        /**
         * Auto-generated VersionUID
         */
        private static final long serialVersionUID = -6535942219723507798L;

        public static void main(String[] args) {
            displayFrame();
        }
        public static void displayFrame() {

            JFrame frame = new JFrame("Game Over");
            JLabel info = new JLabel("My 127.0.0.1 is my castle", JLabel.CENTER);

            int height = 670;
            int width = 630;

            Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
            int ex = (screen.width / 2) - (width / 4); // Center horizontally.
            int ey = (screen.height / 2) - (height / 4); // Center vertically.

            frame.setTitle("Game Over");
            frame.setBounds(ex, ey, width / 2, height / 2);
            frame.setLayout(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            info.setBounds(ex, ey, width/2, height/2);

            frame.add(info);
            frame.setVisible(true);
        }
    }

Solution

  •     frame.setTitle("Game Over");
        frame.setBounds(ex, ey, width / 2, height / 2);
        //frame.setLayout(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        //info.setBounds(ex, ey, width / 2, height / 2);
    

    End result:

    End Game