I've been for a while searching through here and other Java forums. Also googling it, but I haven't found anything that matches my expectations (a line break, basically). I've achieved this:
public final void messageRoom (String message, Boolean bold, Color color) {
StyledDocument document = new DefaultStyledDocument();
SimpleAttributeSet attributes = new SimpleAttributeSet();
if(bold) {
attributes.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE);
}
attributes.addAttribute(StyleConstants.CharacterConstants.Foreground, color);
try {
document.insertString(document.getLength(), message, attributes);
} catch (BadLocationException ex) {
System.out.println("ex");
}
chatArea.setStyledDocument(document);
}
That allows me to send messages to a chat room I'm creating, how can I make the line break to go to the next line?
Thank you all! (Similar but not equal posts: First post and The second one)
how can I make the line break to go to the next line?
Maybe I don't understand the question. The text in a text pane will "wrap" automatically.
If you are attempting to start each message on a new line then you just use "\n" as the new line character.
Maybe something like:
document.insertString(document.getLength(), "\n" + message, attributes);
Of course you wouldn't want to add a new line for the first message.
public final void messageRoom (String message, Boolean bold, Color color)
Don't use an Object when a primitive variable will do. Just use a "Boolean" parameter.
Related
I am trying to replace a word one occurrence at a time. I have been looking through other answers here, but I think what I have coded so far would be much simpler. I want to replace a word that a user selects with another word that the user also selects. I will have two text fields and a button and every time the user clicks the button, we will get the text out of both text fields and replace the word that needs to be replaced in the text area. My issue is that when the replace button is clicked, any other text that is in the text area is deleted and we are left only with the word that is doing the replacing. I know my issue is because I am setting the text of the text area to just that one word, but I do not know how to fix it. Here is my code: Any help is appreciated.
replaceButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String findText = textField.getText();
String replaceText = textField2.getText();
String text = textArea.getText();
text += text.replaceFirst(findText, replaceText);
textArea.setText(replaceText);
}
});
Like you said. You are setting the text in textArea to the text you want to replace. So set the text in textArea to the updated text returned from text.replaceFirst(findText, replaceText). Also you don't need to concatenate the result.
Try this.
replaceButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//the text you want to replace
String findText = textField.getText();
//what you want to replace it with
String replaceText = textField2.getText();
//all the text in the text area
String text = textArea.getText();
//replace first occurrence of "findText" with "replaceText"
//returns the altered string
text = text.replaceFirst(findText, replaceText);
//set text in textArea to newly updated text
textArea.setText(text);
}
});
To make sure I understand you correctly you want something like this.
Original text: I like cats, cats are cool.
find: cats; replace: dogs.
First click output: I like dogs, cats are cool.
Second click output: I like dogs, dogs are cool.
I am making a Java program, but I've run into a problem.
First, let me show you the code:
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerSendMessage%$%##")){
pSmsgc.setSelected(true);
}else{
pSmsg.setEnabled(false);
}
}
if (DFileLoader.getMethod(pathToSaveAs).size() <= 0){
pSmsg.setEnabled(false);
}
}else{
pSmsg.setEnabled(false);
}
pSmsgc.setFont(fDisp);
pSmsgc.setBounds(new Rectangle(50, 135, 140, 30));
pSmsg.setBounds(new Rectangle(175, 135, 150, 30));
pSmsgc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (pSmsgc.isSelected()) pSmsg.setEnabled(true);
else pSmsg.setEnabled(false);
}
});
pane.add(pSmsgc);
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerSendMessage%$%##")){
String[] d = s.split("%$%##");
String text;
if (d.length <= 1) text = "";
else text = d[1];
pSmsg.setText(text);
}
}
}
pane.add(pSmsg);
Here are some things to know about this:
When I use "getMethod(path)", its just returning a String List (List) which includes each line of the TXT file.
pSmsgc is a JCheckBox and pSmsg is a JTextField.
I have it so when the box is not checked, the text field is grayed out, which works fine.
If the file has a line that starts with "playerSendMessage%$%##", the box will be checked, which works.
The thing that isn't working is where it sets the text field's text to the second substring of that line.
For example, the file's line could be "playerSendMessage%$%##Hello!". This would cause the box to be checked, and the field to says "Hello!"
Everything works except for the part where the field says the text.
It might be just a simple thing that I am overlooking, or maybe not. Can anyone please help?
Your file's line name contains the character '$' which means end of a line on RegExp patterns.
So the solution would be to escaping with \\ the character in conflict with RegExp syntax like this:
String[] d = s.split("%\\$%##");
I want to code a program, and I would recolor specific words.
Like this:
Hey there I like carrots with bones.
I want to let carrots automatically while it is typed, make it blue.
Wow do I do that in code?
I already tried this:
public void getWord(String whatword){
if(jtextarea.contains(whatword){
//Stuck on here
}
For example:
If I type this:
I like carrots and tuna.
I want to change the color from carrots and tuna to blue.
And the other words need to stay black.
Now I don't know how to recolor the word, and if this if statement even works.
So, how do I fix this?
Sorry, I am dutch, so you need to do it with this language, I think
A JTextArea is only meant to contain plain text and cannot color certain words. If you want to be able to color different words, you need to use a JTextPane or a JEditorPane.
For more information, see this question. This question may also be helpful
Here is an example:
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("I'm a Style", null);
StyleConstants.setForeground(style, Color.red);
String word = "Hello";
if (word.equals("Hello") {
try {
doc.insertString(doc.getLength(), word, style);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
} else {
StyleConstants.setForeground(style, Color.blue);
try {
doc.insertString(doc.getLength(), word, style);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
This makes a String word. If word is "Hello" it will be displayed in red, otherwise it will be displayed in blue.
I am working with netbeans on an applet. My problem is that I want to take multiple lines input (possibly from text area) and then output to another (text area).
My code in an application would look something like this. How to use the same concept with an applet?
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i=0;i<size;i++)
{
picks[i]=br.readLine();
picks[i] = picks[i].toUpperCase(); //picks is an array
}
/*
.
Some computations is happening here for picks[]
.
*/
for (int p=0;p<size;p++)
{
System.out.print(picks[p]);
System.out.print("\n"); }
}
I need to take each inputed line on its own and store it in the array and do the same with the output.
Thanks
"I am working with netbeans on an applet. My problem is that I want to take multiple lines input (possibly from text area) and then output to another (text area)."
Ok so you have two JTextAreas. You probably want a button to click to transfer the text. So lets add the actionPerformed code as you would been in Netbeans
Right-click on the button (from design view) and select Events -> Action -> actionPerformed. The following code will be auto-generated:
public void jButton1aActionPerformed(java.awt.event.ActionEvent evt) {
}
Now all you need is a one-liner
public void jButton1aActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea2.setText(jTextArea1.getText());
}
If you really, really want to store the text into an array, then just .split with the nex-line carriage character "\n"
String[] lines = jtextField1.getText().split("\\n");
I'm trying to programatically convert a Java source file into an HTML file using PrintWriter to write to a seperate .html file
Example source file may look like this.
HelloWorld.java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
while (true) {
System.out.println("Hello World!");
// Disregard this ridiculous example
}
}
}
All My printing works fine except I have a problem with indentation. Everyting is aligned left.
HelloWorld.html (as seen in browser):
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
while (true) {
System.out.println("Hello World!");
// Disregard this ridiculous example
}
}
}
Program Source Code Snippet: I want this program to determine for me, which line in the java source code should get indentation when it is being converted to HTML. I don't want to do it manually, because then I'd have to write a different program for every source file
PrintWriter output = new PrintWriter(newFile);
output.print("<!DOCTYPE html><html><head>"
+ "<style>"
+ ".keyword { font-weight: bold; color: blue}"
+ "</style></head><body>");
while (input.hasNextLine()) {
String line = input.nextLine();
String[] tokens = line.split(" ");
for (int i = 0; i < tokens.length; i++) {
if (keywordSet.contains(tokens[i])) {
// Gives Java keyword bold blue font
output.print("<span class=\"keyword\">");
output.print(tokens[i] + " ");
output.print("</span>");
} else {
output.print(tokens[i] + " ");
}
}
output.print("<br/>");
}
output.print("</body><html>");
output.close();
Note: The reason I split() each line is because certain keywords that may be in that line, are doing to be highlighted in the html file, which I do with a <span>, as noted in my code
In the program source code, I obviously don't have any indenting implementation, so I know why I don't have indentation in the html file. I really don't know how to go about implementing this.
How do I determine which line gets indentation, and how much indentation?
EDIT:
My Guess: Determine how much whitespace is in the line before splitting it, save the into a variable, then print those spaces in for form of  's before I print anything else in the line. But how do I determine how much whitespace is at the beginning of the line?
You can use a CSS class with white-space: pre or pre-line or pre-wrap.
You can wrap each line in a <p> with a calculated margin-left. It could be a multiple of 10px, for example. This would let you also change brace styles.
Basically, you'll have to keep a variable, indentLevel. Increment it for each { not in a string or a comment, and decrement it for each } not in a string or a comment. Indent each line, say 10px times the indent level. Test; do you want continuation lines indented more?
Use pre tag.
The tag defines preformatted text.
Text in a element is displayed in a fixed-width font (usually
Courier), and it preserves both spaces and line breaks.
You don't need to dermine which line needs to be indented because pre tag preserves ALL spaces, carriage returns and line feeds 'as-is' from the original HTML source code.
If you check the HTML that is rendered in StackOverflow in something marked as code you will see that it uses this tag.
Maybe it's better to first prepare String with your source code adding needed HTML, and replacing spaces with . This can be done with String.replace() method - iterate over you keywordSet and replace all keywords with its wrapped versions. Then you will able to write full string into your stream.
I figure out what I was trying to accomplish
...
int whiteSpace = 0;
while (whiteSpace < line.length() && Character.isWhitespace(line.charAt(j))) {
whiteSpace++;
}
String[] tokens = line.split(" ");
// Print white space
for (int i = 0; i < whiteSpace; i++) {
output.print(" ");
}
...