I'm trying to make a chat client to Swing. I need that message in the history of correspondence were formatted in HTML.
The problem I tried to solve with JTextPane, as it supports HTML formatting. When I did, just text display, in principle everything was normal.
But when I added emoticons using the HTML tag <img>, each time a new message, all text in the window of correspondence started twitching.
How I did it:
jTextPane.setText ("message");
When it was, the new message, I did so
jTextPane.setText ("message" + "new message"); etc.
The result had been the principle of "snake" of Tetris. As a result, I did not like how it works.
So please tell me whether it is possible to deduce that new messages using JLabel adding them to JScrollpane? How to make every new post was a separate element?
String[] split = text.split("\t\t");
String time = split[0].split("\t")[2].split(", ")[1];
String sender = split[0].split("\t")[3];
String message = split[1];
if (!jTextPane.getText().equals("Please log in!")) {
oldMsg = jTextPane.getText().substring(jTextPane.getText().indexOf("<body>") + 6, jTextPane.getText().lastIndexOf("</body>"));
if(sender.equalsIgnoreCase(login.getText())) {
msg = "<div style=\"text-align:right\">" + checkMsgOnSmile(message) + " " + "<b>" + " :" + checkSenderOnColor(sender) + "</b>" + "<span style=\"font-size:10pt\">[" + time + "]</span></div>";
} else {
msg = "<div style=\"\"><span style=\"font-size:10pt\">[" + time + "]</span> " + "<b>" + checkSenderOnColor(sender) + ":" + "</b>" + " " + checkMsgOnSmile(message);
}
String[] check = (oldMsg + msg).split("<br>");
if (check.length > 99) {
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(check));
arrayList.remove(0);
String str = "";
for (int i = 0; i < arrayList.size(); i++) {
str = str + arrayList.get(i).toString() + "<br>";
}
jTextPane.setText(str);
} else {
oldMsg = oldMsg.replaceAll("<span><font size=\"10pt\">", "<span style=\"font-size:10pt\">");
oldMsg = oldMsg.replaceAll("</font></span>", "</span>");
jTextPane.setText(oldMsg + msg + "<br>");
}
}
Can it be replaced by a JLabel and JScrollPane?
If you just need to display text with different colors, fonts etc.., then I find working with text and attributes is easier than using HTML. A simple example would be code like:
JTextPane textPane = new JTextPane();
textPane.setText( "Hello:" );
textPane.setEditable(false);
StyledDocument doc = textPane.getStyledDocument();
// Define a keyword attribute
Simple AttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);
StyleConstants.setBackground(keyWord, Color.YELLOW);
StyleConstants.setBold(keyWord, true);
// Add some text
try
{
doc.insertString(doc.getLength(), "\nAnother line of text", keyWord );
}
catch(Exception e) {}
Related
I have never done anything in java before so I really am a newb but while building the program I have ran into a snag that i just can't figure out. I will try to explain and show to the best of my abilities.
Here is what I am building
The UI
Here is the code I have so far to make it work.
private void jButtonGenerateActionPerformed(java.awt.event.ActionEvent evt) {
String ObjectName = jtObjectName.getText();
String ObjectBase = jcbBaseNPC.getSelectedItem().toString();
String NPCName = jtNPCName.getText();
String MinLevel = jtMinLevel.getText();
if (MinLevel != null && MinLevel.isEmpty())
MinLevel = MinLevel.replace(MinLevel, "minLevel" + MinLevel);{
}
//Alignment Combo Box Start
String Alignment = jcbAlignment.getSelectedItem().toString();
if (Alignment.contains("Good")) {
Alignment = Alignment.replace("Good", "255");
}
if (Alignment.contains("Neutral")) {
Alignment = Alignment.replace("Neutral", "127");
}
if (Alignment.contains("Evil")) {
Alignment = Alignment.replace("Evil", "0");
}
//Alignment Combo Box End
// Print to Output Box
jaOutput.append("object" + " " + ObjectName + " " + "of" + " " + ObjectBase +
"\n\tproperties" + "\n\tname" +" " + "\"" + NPCName + "\"" + MinLevel
);
What I can not understand it how to check to see if there is something entered in a String and if there is I need to add to it so the output looks like this.
minLevel 1100
maxLevel 1500
only thing I will be adding is the numbers so i need to add something like
minLevel + MinLevel
and if it is empty just skip it all together. If I add it to the append and its empty I will just get minLevel and i can't have it like that.
Any tips would be great.
Thank you all
Donald
I'm trying to bold some text in a setter, but when it's displayed, it's not working. I'll just jump into some code so it makes sense...
private static class Spell {
private final String name;
private final String school;
private final String display_class;
//etc.
.
Text t = new Text("TEST: ");
t.setStyle("-fx-font-weight: bold;");
this.name = name + "\n\n";
this.school = school + "\n";
this.display_class = t + display_class + " " + spell_level + "\n";
//etc.
Displaying the list:
if (!newValue.isHeader()) {
tooltip.setText(newValue.getName() + newValue.getSchool() + newValue.getDisplay_Class() //etc.
The text is displayed within a ScrollPane as a Text object: Text tooltip = new Text();
The list displays values like Level: 0 Range: 25ft etc. With this setup, is it at all possible to make just the "Level:" and "Range:" parts bold? Currently, what is displayed when it prints t is Text[text="TEST: ",x=0.0,y=0.0, alignment=LEFT, origin=BASELINE, boundsType=LOGICAL...etc. etc, yet when adding t to a pane and displaying it that way, it shows up correctly bolded. I don't know what to do at this point.
Text t = new Text("TEST: ");
...
this.display_class = t + display_class + " " + spell_level + "\n";
In the line above, you are concatenating the output of toString() of your Text object instance (t) with other strings, that where your extra junk comes from, and it is not probably what you wanted to do.
Unfortunately Text won't support multistyle text strings.
I am currently struggling to comment an existing line with JDom, best I would like to comment an entire node.
SAXBuilder jdomBuild = new SAXBuilder();
jdomDoc = jdomBuild.build(fileLocation);
Element root = jdomDoc.getRootElement();
Element header = root.getChild("header_info")
// how can I comment the lines now?
And the document :
<xml_report>
<header_info>
<bla1></bla1>
<bla2></bla2>
<bla3></bla3>
<bla4></bla4>
<bla5></bla5>
<bla6></bla6>
</header_info>
<random_things>
<random></random>
</random_things>
</xml_report>
I would like to comment the whole header but I can't find the solution anywhere...
Could I have some advice and explainations please?
Replace the header element with a Comment containing the content of the element. Example:
XMLOutputter outputter = new XMLOutputter();
outputter.getFormat().setExpandEmptyElements(true);
SAXBuilder jdomBuild = new SAXBuilder();
Document jdomDoc = jdomBuild.build(new ByteArrayInputStream(("<xml_report>\n"
+ "\n"
+ " <header_info>\n"
+ " <bla1></bla1>\n"
+ " <bla2></bla2>\n"
+ " <bla3></bla3>\n"
+ " <bla4></bla4>\n"
+ " <bla5></bla5>\n"
+ " <bla6></bla6>\n"
+ " </header_info>\n"
+ "\n"
+ " <random_things>\n"
+ " <random/>\n"
+ " </random_things>\n"
+ "\n"
+ "</xml_report>").getBytes(StandardCharsets.UTF_8)));
Element root = jdomDoc.getRootElement();
Element header = root.getChild("header_info");
Comment comment = new Comment(outputter.outputString(header));
root.setContent(root.indexOf(header), comment);
outputter.output(jdomDoc, System.out);
Output:
<?xml version="1.0" encoding="UTF-8"?>
<xml_report>
<!--<header_info>
<bla1></bla1>
<bla2></bla2>
<bla3></bla3>
<bla4></bla4>
<bla5></bla5>
<bla6></bla6>
</header_info>-->
<random_things>
<random></random>
</random_things>
</xml_report>
Note that you cannot preserve the fromatting with JDOM for every possible input, since the formatting information is removed during the parsing.
Also note that you cannot put a comment around a block containing a comment, since this would end the comment sooner. In fact JDOM does not allow -- to occur as substring in a comment. You could simply break up those substings inside comments using
private static final Pattern PATTERN = Pattern.compile("-{2,}");
private static String fix(String string) {
StringBuilder sb = new StringBuilder();
Matcher m = PATTERN.matcher(string);
int lastEnd = 0;
while (m.find()) {
System.out.println(m.group());
sb.append(string.subSequence(lastEnd, m.start())).append('-');
lastEnd = m.end();
for (int i = lastEnd - m.start(); i > 1; i--) {
sb.append(" -");
}
}
if (lastEnd < string.length()) {
sb.append(string.subSequence(lastEnd, string.length()));
}
return sb.toString();
}
Comment comment = new Comment(fix(outputter.outputString(header)));
Anything else would get compicated, since you'd need to take <![CDATA[]]> into account too.
I've this piece of html code. I want to replace the link placeholders for the content mentioned in three separate attributes. This is what I've tried so far:
String texto2 = "url(\"primeiro url\")\n" +
"url('2 url')\n" +
"href=\"1 href\"\n" +
"src=\"1 src\"\n" +
"src='2 src'\n" +
"url('3 url')\n" +
"\n" +
".camera_target_content .camera_link {\n" +
" background: url(../images/blank.gif);\n" +
" display: block;\n" +
" height: 100%;\n" +
" text-decoration: none;\n" +
"}";
String exp = "(?:href|src)=[\"'](.+)[\"']+|(?:url)\\([\"']*(.*)[\"']*\\)";
// expressão para pegar os links do src e do href
Pattern pattern = Pattern.compile(exp);
// preparando expressao
Matcher matcher = pattern.matcher(texto2);
// pegando urls e guardando na lista
while(matcher.find()) {
System.out.println(texto2.substring(matcher.start(), matcher.end()));
}
So far, so good - It works with find just that I need to get the clean link, something like this:
img/image.gif
and not:
href = "img/image.gif"
src = "img/image.gif"
url (img/image.gif)
I want to replace one placeholder using one variable; this is what I've tried so far:
String texto2 = "url(\"primeiro url\")\n" +
"url('2 url')\n" +
"href=\"1 href\"\n" +
"src=\"1 src\"\n" +
"src='2 src'\n" +
"url('3 url')\n" +
"\n" +
".camera_target_content .camera_link {\n" +
" background: url(../images/blank.gif);\n" +
" display: block;\n" +
" height: 100%;\n" +
" text-decoration: none;\n" +
"}";
String exp = "(?:href|src)=[\"'](.+)[\"']+|(?:url)\\([\"']*(.*)[\"']*\\)";
// expressão para pegar os links do src e do href
Pattern pattern = Pattern.compile(exp);
// preparando expressao
Matcher matcher = pattern.matcher(texto2);
// pegando urls e guardando na lista
while(matcher.find()) {
String s = matcher.group(2);
System.out.println(s);
}
It turns out that this version does not work. It grabs the url perfectly; can someone help me spot the problem?
Use jsoup. Parse the HTML string into a DOM and you can then use CSS selectors to pull out the values as you would with jQuery in JavaScript. Note that this will only work if you're actually working with HTML; the string at the top of your example is not HTML.
Can you tell me how I can make only part of the text bold:
TextArea dataPane = new TextArea();
dataPane.appendText("Product Version: " + "1.0");
dataPane.appendText("\nJava: " + "7");
dataPane.appendText("\nRuntime: " + "7");
dataPane.appendText("\nSystem: " + "Linux");
dataPane.appendText("\nUser directory: " + "/home/dir");
I want to make only these strings bold: Product Version, Java, Runtime, System, User directory? What will be the easiest way to do this?
UPDATE
I also tested this code:
TextArea dataPane = new TextArea();
dataPane.setPrefRowCount(10);
Text wd = new Text("Version");
wd.setFont(Font.font ("Verdana", FontWeight.BOLD, 20));
dataPane.appendText(wd + "1.0");
dataPane.appendText("\nJava: " + "7");
dataPane.appendText("\nRuntime: " + "7");
dataPane.appendText("\nSystem: " + "Linux");
dataPane.appendText("\nUser directory: " + "/home/dir");
I get this: Text#149e84241.0
The text is not properly formatted.
You could use an editor pane with the content type set to html instead of a text area. I threw an editor pane into a scratch project really quick and just used the default variable names and object properties. Here's how I produced what I believe you're looking for:
jEditorPane1.setContentType("text/html"); //by default this is text/plain
//use margin-top and margin-bottom to prevent gaps between paragraphs
//or actually customize them to create space if you desire so
jEditorPane1.setText("<p style='margin-top:0pt;'><b>Product Version:</b> 1.0</p>" +
"<p style='margin-top:0pt; margin-bottom:0pt;'><b>Java:</b> 7</p>" +
"<p style='margin-top:0pt; margin-bottom:0pt;'><b>Runtime:</b> 7</p>" +
"<p style='margin-top:0pt; margin-bottom:0pt;'><b>System:</b> Linux</p>" +
"<p style='margin-top:0pt; margin-bottom:0pt;'><b>User directory:</b> /home/dir</p>");