Set newline in Java swing window - java

I am trying to set a couple newlines in a java swing window, but for some reason everything is printed on one line.
This is my code:
private JLabel lblOutput;
guess = 79;
numberOfTries = 5;
message = guess + " is correct. " + "\n" + "Let's play again! " + "\n" + "And it only took you " + numberOfTries + " number of tries!";
lblOutput.setText(message);
The output of the above is:
79 is correct. Let's play again! And it only took you 5 number of tries!
What am I doing wrong?

A label is designed to only display a single line of text.
However, you can use simple HTML to split the text on multiple lines:
label.setText("<html>line1<br>line2</html>");

If lblOutput is a JLabel, it only accepts a single line of text.
You can try using HTML formatting to get around it.

Related

How to define the JOptionPane showMessageDialog multiple lines; JRadioButton and JList together?

Now, I know only use JOptionPane.showMessageDialog with Text to fill blank box like this below.
enter code here JOptionPane.showMessageDialog
(null,"\n Desciption" +
"\n ID: " + txtAP_ID.getText() +
"\n Fullname: " + txtAP_NAME.getText() +
"\n Address: "+ txtAP_ADDRESS.getText());
But, I want to show multiple lines in frame that use JOptionPane.showMessageDialog code with the JRadioButton and JList that were the choices, I want to write the code next to that code above. How can I do?

Why does JavaFX ImageView snapshot shows a wrong size?

I have a large image that I'm loading from a file. I need to put it on two ImageView's (ivInput,ivLayer1) and resize it to 32x32. ivInput is resizing to 32x32 succesfully, but when I take its snapshot it has a wrong size (32x25).
Image imgLetterBox = loadFromFile("m1.png");
ivInput.setImage(imgLetterBox);
ivInput.setFitWidth(32);
ivInput.setFitHeight(32);
System.out.println("ImgInput:" + ivInput.getFitWidth() + ", " + ivInput.getFitHeight());//32x32, it's ok
Image imgLayer1 = ivInput.snapshot(null,null);
System.out.println("ImgLayer1:" + imgLayer1.getWidth() + ", " + imgLayer1.getHeight());//32x25. why?
Problem was in PreserveRatio property, it was on true value. I changed it on disable value and it is working well now.

Apache POI PPT (Java) - Updating TextShape keeping text formatting/shape formatting

I am trying to produce several reports (i.e. N PPTX files) based on different inputs/for different users on the same PPTX template I created.
I have several preformatted XSLFTextShape on the PPTX template that contains a single XSLFTextParagraph already formatted (i.e. both the shape and the text). Each shape contains a particular placeholder that I need to substitute with a dynimic value. I have this value in a Map (placeholder,newValue). I am successful in updating the placeholder with the new value using:
textShape.clearText();
XSLFTextRun run = paragraph.addNewTextRun();
run.setText(newText);
So, when I produce the PPTX in output the text is updated but font color, font formatting, font size are changed compared to those I defined in the template. How can I keep the same formatting?
Any solutions to simply change the text while keeping original formatting?
Thanks in advance!
For everybody which may be interested in this topic in the future - I post the solution (working if one TextBox has a single Paragraph). This solution loops on all text boxes and in the case one contain one of the vales specified in the Placeholder->newValue map, it will update it maintaining the formatting.
public static void updateTextBoxesWithDesiredValues(XMLSlideShow ppt, Map<String, String> placeHolderDefinedValue) {
logger.info("ElapsedTime: " + tM.getTimeElapsedReadableFormat() + " ########## Updating single text box content...");
List<XSLFSlide> allSlides = ppt.getSlides();
int updatedElements = 0;
for (XSLFSlide currentSlide : allSlides) {
for (XSLFShape shape : currentSlide.getShapes()) {
if (shape instanceof XSLFTextShape) {
XSLFTextShape textBox = (XSLFTextShape) shape;
String elementTextContent = textBox.getText();
for (Object key : placeHolderDefinedValue.keySet()) {
if (elementTextContent.equals(key)) {
List<XSLFTextParagraph> textBoxParagraphs = textBox.getTextParagraphs();
List<XSLFTextRun> textBoxParagraphTextRuns = textBoxParagraphs.get(0).getTextRuns();
//System.out.println("########################## check paragraph number in textbox: " + textBoxParagraphs.size() + " - TextRuns: " + textBoxParagraphs.get(0).getTextRuns().size());
logger.info("ElapsedTime: " + tM.getTimeElapsedReadableFormat() + updatedElements + ") Updating: " + textBox.getText() + " --> " + placeHolderDefinedValue.get(key));
for (XSLFTextRun r : textBoxParagraphTextRuns) {
r.setText(placeHolderDefinedValue.get(key));
}
updatedElements++;
//break;
}
}
}
}
}
logger.info("ElapsedTime: " + tM.getTimeElapsedReadableFormat() + " Total Text Element Content Updated: " + updatedElements + " #########################");
}
It's kind of horrible - but yeah there's a reason they called it "POI".
Here's my approach to "only reset text" of an existing XSLFTextShape (that must have at least some text pre-set!):
textShape.getTextParagraphs().get(0).getTextRuns().get(0).setText(text);
for (int i = 1; i < textShape.getTextParagraphs().get(0).getTextRuns().size(); i++) {
textShape.getTextParagraphs().get(0).getTextRuns().get(i).setText("");
}
for (int i = 1; i < textShape.getTextParagraphs().size(); i++) {
textShape.getTextParagraphs().get(i).getTextRuns().stream().filter(tr -> !tr.getRawText().equals("\n")).forEach(tr -> tr.setText(""));
}
It will replace all existing text(paragraphs/runs) with "empty" text, but linebreaks can't be replaced for some reason. So this might leave you with some trailing lines - as they usually(!) are transparent this won't really hurt a lot.
.clearText / removing paragraphs either destoyed the formatting for me, or didn't work. Trying to reset the style (fontColor, fontFamily, fontSize, isBold, isItalit, ...) didn't result in satisfying results :(

JLabel: using HTML and method call together

When using JLabel, is there a way to use HTML and method call together?
For example:
JLabel speedLabel = new JLabel("<html><b>Speed: </b></html>" + plane.getSpeed());
This doesn't work.
It only shows Speed: and ignores the rest.
Try to change your code to this:
JLabel speedLabel = new JLabel("<html><b>Speed: " + plane.getSpeed() + " </b></html>");
The text, or in your case the airplane speed, that is probably a double, must be in between the <html> and </html> tags, to be recognized.
it is discarding the values after html close tag if you something like this it will work JLabel speedLabel = new JLabel("<html><b>Speed: " + plane.getSpeed() + "</b></html>");

How to insert line break into excel using java?

I am read from a database column which stores data like
testing\n
testing\n
I am then using the jxl.write.WritableWorkbook methods to generate the excel file that will read from this column.
However when being displyed as excel There are no line break in the column data.
What is the reason and how should i resolve this?
You might try: WritableCellFormat.setWrap(true)
Look here: http://jexcelapi.sourceforge.net/resources/faq/
I searched the internet since i needed an answer and here it is...
From JExcel API FAQ:
How do I add a newline or carriage-return to a Label cell?
Use "\012" or "\n". Also make sure to turn on cell wrapping with WritableCellFormat.setWrap(true) or the newline will show up as a square (unknown character).
I tested it and it worked for "\012" or "\n" as i put also .setWrap(true) and i tested it with
WritableCellFormat times16format =
new WritableCellFormat(times16font);
times16format.setWrap(true);
times16format.setAlignment(Alignment.RIGHT);
times16format.setBorder(Border.ALL, BorderLineStyle.HAIR);
//Merge col[0-2] and row[0]
sheet.mergeCells(0, 0, 2, 0);
Label leftPartLabel =
new Label(
0,
0,
reportKingdomData + "\012" + dateData + " " + MyDateFormat.format(new Date()) + timeData + "\n" + MyTimeFormat.format(new Date()),
times16format);
sheet.addCell(leftPartLabel);
Insert Line In jxl JExcel API
Try this:
for (int row = 0; row<100; row++)
{
sheet.addCell(new Label(0,row,"Testing "+row);
}
Feel comfortable to let me know, if you are facing problem and don't forget to mark/upvote correct answer.

Categories