Multiline Text output in javafx - java

I need to output 5-8 lines to my window. I managed that with a TextArea, BUT, i don't want the user to be able to write inside it, AND I also can't use my keyboard to navigate between buttons and other elements on the page.
Lets say that there is a String named text, which field type do you think i should write it out into? Text is good but only lets me use a single line.
Text actiontarget3;
String text = new String(" something \n Second line something");
actiontarget4.setText(text);
Because I use FXML to design the menu page, the relevant part is:
<Text fx:id="actiontarget3"
GridPane.columnIndex="1" GridPane.rowIndex="1"/>
Basically, I managed to get the info from a ping test, added it to an ArrayList<String>
and I want to display the results on the Graphic User Interface. But the above example covers my problems without having to copy paste here the entire code.

You can make it so a TextArea is not editable.
JTextArea ta = new JTextArea();
ta.setEditable(false);
You may also want to look into using a JTextPane.

Related

JavaFX: How to store and format multiple paragraphs in some kind of text area?

I am currently creating a small chat program (mainly for the purpose of getting some experience with RMI and JavaFX). The chat itself is already finished, now I'm working on the GUI.
I want every chat message to be printed in some kind of text area similar to this:
Alice <19:21:35>: Hello World!
These are my problems/questions:
What JavaFX class to use for this? I found a class called TextFlow that seems to be able to do what I want, but I didn't understand how exactly it works by now. Or is a simple TextArea enough?
How can I use different formattings within one line? Using HTML?
How should I keep the received text messages within the client? Just always append them to the text area (and have them saved implicitly by the GUI)? Or should I use some kind of ObservableList that buffers the messages and the text area synchronizes with it?
The messages are received as Message objects. These objects basically just store username, message, and timestamp; each of them in a seperate attribute.
The simplest way of doing it would be through a TextArea, although there wouldn't be any neat text formatting, it would just look like a bland NotePad like program. I would recommend using a VBox and Texts. One VBox could be used to store all the Texts, and you could put the VBox in a ScrollPane for scrolling. Then, for every message, put an HBox consisting of 3 Texts. Here is an example
//Put this method in your Application class
public static void addMessage(Message message){
Text username = new Text(message.getUsername());
username.setFont(Font.font("Verdana", FontWeight.BOLD, 14));
Text date = new Text(message.getTimestamp());
date.setFont(Font.font("Verdana", FontWeight.ITALIC, 12));
date.setFill(Color.GRAY);
Text message = new Text(message.getMessage());
date.setFont(Font.font("Courier New", 12));
mainBox.getChildren().Add(new HBox(username, date, message)); //mainBox being a VBox that stores all your HBoxes.
}
Obviously, change this to suit your needs, and please change the styling. I just gave an example. This is what I have done before, and with the right styling, it looks a lot nicer than just slopping on a TextArea.
If your formatting requirements are fixed, then Text and TextFlow would be a good place to start. Each text node can be assigned a style either in code or via CSS. Put multiple text nodes together into a TextFlow. Put the TextFlow node into a layout container. Start with a VBox for testing, but I would suggest using a TableView once you get the basics working. The javadoc for TextFlow has snippets of sample code that should get you going.
For a pure JavaFX solution then use multiple Text nodes, styled with CSS. Either set formatting properties on each node, or assign a style and use an external .css file. Or if you want to consider third-party components, then something like this: https://github.com/TomasMikula/RichTextFX might be a good place to start.
You definitely want to separate your data model from your display model (or view, if you want to use that terminology). Build a data class (e.g, Message). If you hold your message data in an ObservableList of Message objects then you can bind it to a TableView, and have the table automatically update as you add or remove entries in the list. Add code to the table cell factories to control how you render each cell from your data model (e.g., by creating a TextFlow to draw the content).

Highlight different text in jtextarea

These are the following things i want to know:
I want to highlight different text in jtextarea by selecting them by mouse.
I also want to get all the highlighted text later.
I also want to know how to remove particular highlighted line.
What code can i use ?
You need to use a Highlighter:
Highlighter hl = textArea.getHighlighter();
Read the API for the methods that allow you add, remove and display the highlights.

How can I create a new line in JTextField to type in?

I want to make a Swing program that writes updates on what you have done. It writes all the information on an uneditable JTextField.
For example:
You have changed the text to BLUE.
You have changed the text to RED.
The problem is that I can't make the two lines separate.
What I get is this:
You have changed the text to BLUE. You have changed the text to RED.
What I've tried is this: (This does not work)
TF_BetInfo.setText(TF_BetInfo.getText() + "\nYou have changed the text to BLUE.");
TF_BetInfo.setText(TF_BetInfo.getText() + "\nYou have changed the text to RED.");
you can't have multiple lines with JTextField , you can use JTextArea for that purpose , and the code wouldn't be much different too , you can still use the same code or you can just
TF_BetInfo.append("\nyou have ...... ");
where TF_Betinfo is a JTextArea rather than a JTextField .
You can't use JTextField for this. JTextField is sinle-line edit control. That is why you got all your output in one line.
If you want several lines to be printed in edit use JTextArea. In your case you can use jTextArea.append(string) (note: jTextArea is an object of class JTextArea, and string is an object of class String).
You can't actually use several lines in a JTextField, but what you can do, is using a JTextArea of the wanted size, and then use the following:
yourJTextArea.setLineWrap(true);
This will automatically detect when the JTextArea needs to use another line and add it, pretty cool, useful and you only need one code line to do it.
JTextArea is more flexible but if you really want flexibility read about JTextPane or JEditorPane, you can show URLS, internet pages and everything that comes to your mind.

Making words different colors in JTextField/JTextPane/?

I'm trying and failing to understand how to use Java's text editor components to colorize text as you insert it. I don't want or need a fully featured syntax highlighting library.
Basically, I have a JTextField (or some other JText... component), and a list of words. I want any words in the field that appear in the list to be red, and the rest of the words be green. So for example, if "fire" is in the list, "fir" would appear green and "fire" would appear red.
I've tried using a JTextPane and a DefaultStyledDocument, using a KeyListener to go over the text in the document and using AbstractStyledDocument.replace to replace the existing words with versions that have the correct attributes. This didn't do anything. What am I doing wrong?
Neither JTextPane nor JTextField isn't able to present formatted text, i.e text having more than one format. For text-editor-like capabilities like you'd find in WordPad or HTML, the component to use is the JEditorPane or its descendant, JTextPane.
The simplest thing you can do is set the ContentType of the JEditorPane to "text/html" and simply set its text to a string containing HTML. The Java structured text components are surprisingly competent with HTML; you can display tables and/or DIVs, and there is support for much of CSS2. Simplest to do your styles inline, but you can even do external style hrefs.
If you want to get fancy programmatically, you can access the DocumentModel and create text from spans of text each having their own formatting. The DocumentModel works essentially like a programmable text editor.
EDIT: Re-reading your question, I see my answer doesn't quite address it. Since you want multi-colored text JEditorPane is your only option; but rather than just piping in pre-colored text via HTML or such, you'll have to put a listener on your document model to catch changes introduced when you type; and after every document change you'll want to examine the text (again from the Document model) for text that should or should not be highlighted, and you'll want to apply formatting to certain runs of text.
There are devils in the details, but this should get you started.

Java JEditorPane Format

im trying to implement a Chat feature in my application. i have used 2 JEditorPane. one for holding chat history and the other for sending chat to the previous JEditorPane.
the JEditorPane is text/html type.
the problem i am having is when i put more than one space between characters it is automatically removed by the parser because it is HTML!
how can i make it so, that the spaces are not stripped?
example: hello world
becomes: hello world
also i am having to parse the html tags so the new messages can be added to the history window.
is there a better option than using JEditorPane? if i used JTextPane would it be easier to implement?
i would like the chat boxes/panes to be able to handle bold, URL embedding for now.
thank you and look forward to your guidance.
EDIT: im trying to replace " " with a relavent char.
newHome[1] = newHome[1].replace(" ", newChar)
what should be the newChar value?
EDIT: im trying:
newHome[1] = newHome[1].replaceAll(" ", " ");
but it is not producing the results. any ideas?
EDIT: #Thomas - thanks! for some reason i can post a note to your answer.
Using HTML markup is a quick way to get simple text formatting done in a Swing text component. However, it's not the only way.
A more sophisticated method is to use a javax.swing.text.StyledDocument to which you can attach different "styles" (hence the name). A style is basically a set of attributes, for instance, whether the text should be in bold or italics or what Color it should have.
JTextPane provides a number of convenience methods to deal with styles, and it is a subclass of JEditorPane which means it should integrate rather seamlessly into your existing code. As an example, to mark a portion of the text within a JTextPane as bold, you could use something like this:
JTextPane textPane = new JTextPane();
Style bold = textPane.addStyle("bold", null);
StyleConstants.setBold(bold, true);
textPane.setText("I'll be bold.");
textPane.getStyledDocument().setCharacterAttributes(8, 4, bold, true);
Similarly, you could define a second style that e.g. uses a blue, underlined font and which you could use to display hyperlinks.
Unfortunately, the downside is that you will have to take care of the mechanics of the links yourself. Although you can use the existing infrastructure of javax.swing.event.HyperlinkListener et al., you will be responsible for detecting mouse clicks. The same goes for hovering and changing the Cursor into a hand-symbol etc.

Categories