JLabel 不显示

JLabel not displaying

我正在尝试在 JLabel 中添加一个换行符。 '\n' 不起作用,我发现使用 HTML 应该是一个解决方案,但每当我尝试使用 HTML 进行任何操作时,它都会导致我的 JFrame 消失或不再可见。我正在使用 NetBeans 8.2 和 Java JDK 1.8.0_251。有什么解决办法吗?谢谢

 WindowMain = new JFrame("Spasitel");
   WindowMain.setSize(960, 720);
   WindowMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   WindowMain.getContentPane().setBackground(Color.BLACK);
   //WindowMain.getContentPane().setFont(Courier New);
   WindowMain.setLayout(null);
   WindowMain.setResizable(false);
   WindowMain.setVisible(true);
   Toolkit toolkit = Toolkit.getDefaultToolkit();
   Dimension size = toolkit.getScreenSize();
   WindowMain.setLocation(size.width/2 - WindowMain.getWidth()/2, size.height/2 - WindowMain.getHeight()/2);

   JPanel TitleFrame = new JPanel();
   TitleFrame.setBounds(50,50, 860, 200);
   TitleFrame.setBackground(Color.WHITE);
   JLabel TitleText = new JLabel ("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);
   //TitleText.setFont("Courier New", Font.PLAIN, 18);
   TitleFrame.add(TitleText);
   TitleFrame.setForeground(Color.GREEN);
   TitleFrame.show();
   TitleFrame.setVisible(true);
   WindowMain.add(TitleFrame);

With HTML

Without HTML

我创建了以下 GUI。

我用了一个 JFrame、一个 JPanel 和一个 JLabel。我调用了 SwingUtilities invokeLater 方法在事件调度线程上启动 Swing GUI,

我使用了 Swing 布局管理器。

这是完整的可运行代码。

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JLabelExample implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new JLabelExample());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("JLabel Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(createMainPanel(), BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        String s = "<html>This is a test of the emergency broadcast system.  ";
        s += "<br />This is only a test.";
        
        JLabel label = new JLabel(s);
        panel.add(label);
        
        return panel;
    }

}

您不能使用具有空布局的 html 标签,请尝试设置布局。

例如:

WindowMain.setLayout(new GridBagLayout());