as the title says: I need to fit a JLabel into a JFrame, but the text in the JLabel are too long, so I need to add some linebreaks. The text in the JLabel are obtained from an online XML file, so i cant just change the text to contain linebreaks.
This code extracts data from the XML-file
Element element = (Element)nodes1.item(i);
String vær = getElementValue(element,"body");
String v = vær.replaceAll("<.*>", "" );
String forecast = "Vær: " + v;
in this case the string I want to add some linebreaks to the string v. The String v contains the parsed data from the xml file. The String forecast is returned and set as a text to the JLabel.
Just ask if something is uncleared, thanks in advance!
As per @darren's answer, you simply need to wrap the string with <html> and </html> tags: myLabel. setText("<html>"+ myString +"</html>"); You do not need to hard-code any break tags.
You can set a fixed the size by setting the minimum, preferred and maximum size: setMinimumSize(width, height); setPreferredSize(width, height); setMaximumSize(width, height); As the Link from MadProgrammer, you need to override these methods, not using them from outside, based on the reasons mentioned in this link.
You can do that as follows, label. setText(label. getText() + "text u want to append");
JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel can display text, image or both . JLabel is only a display of text or image and it cannot get focus . JLabel is inactive to input events such a mouse focus or keyboard focus.
I suggest using a JTextArea
instead and turning wrapping on. The only way to do it in a JLabel
is to put line breaks <br />
, which wouldn't work (at least not easily) in your situation if you don't know the text beforehand.
JTextArea
is much more flexible. By default it looks different, but you can fiddle around with some of the display properties to make it look like a JLabel
.
A simple modified usage example taken from the How to Use Text Areas tutorial -
public class JTextAreaDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("JTextArea Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
JTextArea textArea = new JTextArea(
"If there is anything the nonconformist hates worse " +
"than a conformist, it's another nonconformist who " +
"doesn't conform to the prevailing standard of nonconformity.",
6,
20);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setOpaque(false);
textArea.setEditable(false);
panel.add(textArea);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With