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.
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 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) {}
This question already has answers here:
How to capitalize the first letter of a String in Java?
(59 answers)
Closed 8 years ago.
what I'm trying to do is write a method that has one argument and returns a new string that capitalises that string and returns in its parameter.
this is my code so far:
public void input(){
this.printmessage("Dillon", "Francis", "chimes", "chimes from hudson mohawke", "2", "$69.00", "$420.00", "$1337.00");
}
public void printmessage(String firstName, String lastname, String product, String company, String number, String retail, String price, String saving){
UI.println("text " + firstName + ",");
UI.println(text + " " + product + "s text, text text text text -");
UI.println(" ");
}
What I want to do is capitalise the product parameter (chimes) and then return into into the printMessage capitalized if it is used at the beginning of a sentence.
Will something like this work?
public String capitalise(String product){
return Character.toUpperCase(product.charAt(0)) + product.substring(1);
}
I'm really stuck and would love some help.
Thanks.
I've tried this
String pls = (product + " example");
if ( pls.startsWith(product) ) {
product = capitalise(product);
}
UI.println(pls);
but it doesnt print out the capitalised version.
change this line :
UI.println(text + " " + product + "s text, text text text text -");
to:
UI.println(text + " " + capitalize(product) + "s text, text text text text -");
But your code needs a bit more structuring. Focus on even indentation. And if you need the capitalized product later on, you'd better save it before you use it, like
...
product = capitalize(product);
UI.println(text + " " + product + "s text, text text text text -");
...
EDIT:
For this I'm assuming the line is contained in a String called line.
First check if the line begins with product. Then capitalize it.
...
String line = text + " " + product + "s text, text text text text -";
line = line.trim(); // removes whitespaces.
if ( line.startsWith( product ) ) {
product = capitalize ( product ); //or whatever.
}
UI.println(line);
...
I need some help writing a program
Using this code I am able to enter in a track name, artist, etc.
I have a problem that I cannot now show this information in JOptionPane to display all of my info
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TestTrack
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
System.out.println("Track name");
String name = myScan.nextLine();
System.out.println("Artist");
String Artist = myScan.nextLine();
System.out.println("Track length seconds");
String seconds = myScan.nextLine();
System.out.println("Album");
String Album = myScan.nextLine();
JOptionPane.showMessageDialog(null,"Trackinfo:")
}
}
So I guess I would want the pop out window to say
Track Name: "blank"
Artist: blank
Another question I have is how to ask this question multiple times by using "while" and asking if I would like to add another track
Sorry if I am using any terminology incorrectly I just started to learn Java
This line: JOptionPane.showMessageDialog(null,"Trackinfo:")
Contains what the pop-up window will contain. You pass in what you want its contents to be as the 2nd parameter, which is currently "Trackinfo".
To incorporate a while loop, you'll have to have a loop control variable, or a condition that will break the loop. In my example I used a string. My example uses a while loop that will continue as long as the string is not equal to "quit".
String test = "";
while( ! test.equals("quit") ) {
//use Scanner to get the next value the user enters
//ask for track info
//display that info in a message box
}
To obtain this:
Note: the texts of the OK and Cancel buttons are localized, if your computer is set to US locale you doesn't see 'Annuler"... ;-)
code this:
int answer = 0;
do {
/*----------------------------------------------------------------------------
Here you put the code which set the variables name, artist, seconds... (1)
----------------------------------------------------------------------------*/
final String title = "Track info";
final String message =
"<html><table>" +
"<tr><td>Track name" + "</td><td>" + name + "</td></tr>" +
"<tr><td>Artist" + "</td><td>" + artist + "</td></tr>" +
"<tr><td>Track length seconds</td><td>" + seconds + "</td></tr>" +
"<tr><td>Album" + "</td><td>" + album + "</td></tr>" +
"</table>";
answer =
JOptionPane.showConfirmDialog(
null, message, title, JOptionPane.OK_CANCEL_OPTION );
} while( answer == JOptionPane.OK_OPTION );
(1) You may choose Scanner or GUI whith JOptionPane.showInputDialog()
JOptionPane.showMessageDialog(null,"Trackinfo:" + "\nArtist: " + Artist + "\nseconds: " + seconds + "\nAlbum: " + Album)
Each '\n' means a new line. for doing this multiple times, you should place your code in a while loop, something like this:
while(!(Artist == "end")) {
//your code
}
Use myScan.next() instead of myScan.nextLine()
To output the information into the Message Dialog, use
String trackInfo = "Track Name: " + name + " | Artist : " +artist+ " | Track Length: " + seconds + " | Album: " + album;
JOptionPane.showMessageDialog(null, trackInfo, "Trackinfo", JOptionPane.INFORMATION_MESSAGE);
I want to print Strings in JTextArea and align them properly. Its hard to explain so I will upload the screen shot of what I am trying to achieve.
So Strings printed in each line are printed from Paper object which has parameters (id, title, author, date, rank). The data is read from a text file and is stored in a LinkedList using loadPaper() function.
Then displayPapers() function is used to display content of the Paper object to the JTextArea.
displayPapers() is listed below:
/** Print all Paper object present in the LinkedList paperList to textArea */
public void displayPapers(){
// clear textArea before displaying new content
displayTxtArea.setText("");
Paper currentPaper;
ListIterator<Paper> iter = paperList.listIterator();
while(iter.hasNext()){
currentPaper = iter.next();
String line = currentPaper.toString();
if("".equals(line)){
continue;
} // end if
String[] words = line.split(",");
displayTxtArea.append (" "
+ padString(words[0],30)
+ padString(words[1],30)
+ " "
+ padString(words[2],30)
+ " "
+ padString(words[3],30)
+ padString(words[4],30)
+ "\n");
System.out.println(words);
//displayTxtArea.append(currentPaper.toString());
} // end while
displayTxtArea.append(" Total " + noOfPapers + " entries!");
} // end showAllPaper
The padString() function adds spaces to the String so that all of them have same number of words. PadString() is listed below:
/** Add spaces to Strings so that all of the are of same number of characters
* #param str String to be padded
* #param n total number words String should be padded to
* #return str Padded string
*/
private String padString(String str, int n){
if(str.length() < n){
for(int j = str.length(); j < n; j++){
str += " ";
} // end for
} // end if
return str;
} // end padString
I have worked on this for a while but still cant get the solution. As you can notice the above picture not everything is perfectly aligned as intended.
How do I align them perfectly so that it looks nicer? Thanks.
Output will be aligned "properly" in your JTextArea only if you use a mono-spaced font. "Andale Mono 14" for example would do the trick.
Also, in order to make your life easier and avoid the padding hell, use String.format with it's syntax.
String format = "%1$5s %2$-40s %3$-20s";
String someLine;
while (whatEver...) {
...
someLine = String.format(format, aNum, aName, aDate);
jTextArea1.append(someLine + "\n");
}
Use a JTable instead (for what is apparently tabular information). See How To Use Tables for more details & working examples.
You may use HTML with swing component or use JEditorPane.
JLabel jt=new JLabel();
jt.setText("<html>
<table border='1'>
<tr><th>No</th><th>Name</th></tr>
<tr><td>1</td><td>Mr.A</td></tr></table></html>");
You can also change the font of the JTextArea if it is allowed in your problem
textArea.setFont(new Font("monospaced", Font.PLAIN, 12));