簡體   English   中英

JLabel在JFrame中不顯示任何內容

[英]JLabel doesn't display anything in JFrame

我認為並希望這是一個小問題。

我有一個在蛇游戲中顯示的JFrame 諸如"Game Over, your snake is crashed"的文本將顯示在JLabel

問題是我的JLabel總是空的!

這是代碼:

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

最終結果:

結束游戲

當您在此處將X和Y坐標設置為不在JFrames尺寸之外時, JLabel不會顯示:

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

您需要在JFrame上設置進行此調用。

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

同樣,使用布局管理器將消除對子組件本身設置邊界的需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM