简体   繁体   中英

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, eg "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);
        }
    }
    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:

结束游戏

The JLabel doesnt display as you have set the X & Y co-ordinates to be outside of the JFrames dimensions here:

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

You need to set make this call on the JFrame .

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

Also using a layout manager will remove the need to set bounds on child components themselves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM