java - JLabel 不显示
问题描述
我正在尝试在 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);
解决方案
我创建了以下 GUI。
我使用了 a JFrame
、 aJPanel
和 a JLabel
。我调用了SwingUtilities
invokeLater
在 Event Dispatch Thread 上启动 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;
}
}
推荐阅读
- c# - 显示 400 的 ASP.NET Web 应用程序 (WebForms) 项目的 Api
- javascript - 拖放但替换为内联 svg
- excel - TXT 连接问题
- arrays - 有人告诉我这个 JSON 有多个根元素,帮助纠正
- keyboard-shortcuts - mc.keymap(午夜指挥官)中的“a1”、“c1”绑定是什么?
- swift - 无法覆盖preferredStatusBarStyle
- ios - 在 swiftUi 中跨视图更改结构内的数据
- azure-data-factory - 将“设置变量活动”的值保存在 Json 文件中
- node.js - 在 nodeJs 中导入 @turf 模块的问题
- parsing - 是否有一种解析器生成器可以处理所有确定性上下文无关文法?