简体   繁体   English

我不知道为什么 JLabel 没有显示

[英]I can't tell why JLabel is not showing

I have a main class that creates the instance of the JFrame and JPanel and I set the JPanel as public so I can access it from another class to add more things into it (I don't know if this is how it works, that's just my logic).我有一个主要的 class 创建JFrameJPanel的实例,我将JPanel设置为公共,因此我可以从另一个 class 访问它,以添加更多的东西,如果它是如何工作的我的逻辑)。

public class Main {

   private JFrame obj; 
   public Gameplay gamePlay; 

   public Main() {
      obj = new JFrame();
      gamePlay = new Gameplay();
   }

   public void execute() {
      //properties of the jframe
      obj.setBounds(10, 10, 700, 600);
      obj.setTitle("Brick breaker");
      obj.setResizable(false);
      obj.setVisible(true);
      obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      //add the jpanel inside the jframe
      obj.add(gamePlay);
   }

   public static void main(String[] args) {
      Main main = new Main();
      main.execute();
   }
}

Then, I have another class named Gameplay which extends JPanel .然后,我有另一个名为Gameplay的 class 扩展了JPanel One of the methods inside has to draw things inside the JPanel and add a label when a condition is true.其中一种方法必须在 JPanel 内绘制东西,并在条件为真时添加 label。

Note that the commented region at the end where "GAME OVER" is drawn by with graphics g it does work correctly, but I want to put a label instead because I want to use custom font.请注意,在“GAME OVER”末尾的注释区域用图形g绘制它确实可以正常工作,但我想使用 label 代替,因为我想使用自定义字体。 The label never shows up. label 从未出现。 All the other things that the method pait() has to paint also work fine.方法pait()必须绘制的所有其他内容也可以正常工作。

public void paint(Graphics g) {
    //background
    g.setColor(Color.black);
    g.fillRect(1, 1, 692, 592);
    
    //more code of drawing things
    //...
    
    if(ballposY > 570) {
        play = false;
        ballXdir = 0;
        ballYdir = 0;
        
        lblGameOver = new JLabel("GAME OVER");
        lblGameOver.setForeground(Color.green);
        lblGameOver.setFont(pixels);//custom font
        Main main = new Main();
        main.gamePlay.add(lblGameOver);

        //g.setColor(Color.green);
        //g.setFont(new Font("serif", Font.BOLD, 30));
        //g.drawString("GAME OVER", 250, 300);
    }
    g.dispose();
}

You are need to add this line to your code:您需要将此行添加到您的代码中:

lblGameOver.setOpaque(true); lblGameOver.setOpaque(true); It's will add your BackGroud and make that methode works well lblGameOver.setForeground(Color.green);它将添加您的 BackGroud 并使该方法运行良好 lblGameOver.setForeground(Color.green);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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