I am trying to add a linebreak in a JLabel. '\n' does not work and I have found that using HTML should be a solution, but whenever I try anything with HTML it causes my JFrame to disappear or not be visible anymore. I am using NetBeans 8.2 and Java JDK 1.8.0_251. Is there any solution to this? Thank you
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);
I created the following GUI.
I used a JFrame
, a JPanel
, and a JLabel
. I called the SwingUtilities
invokeLater
method to start the Swing GUI on the Event Dispatch Thread,
I used Swing layout managers.
Here's the complete runnable code.
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;
}
}