Moving both text and icons from one JTextPane to another - java

I'm currently making a GUI for a chat room. I've made it so the user enters text and can pick images that end up in a JTextPane. After the user presses enter I want to display it in another JTextPane though. Is there an easy way to move both text and icons from one JTextPane to another at the same time? I've only managed to move one of them at a time.

You can use an ElementIterator to copy over a JTextPane’s StyledDocument element by element, with all styling, including icons:
static void copy(Document source,
Document dest) {
try {
dest.remove(0, dest.getLength());
ElementIterator iterator = new ElementIterator(source);
Element element;
while ((element = iterator.next()) != null) {
if (element.isLeaf()) {
int start = element.getStartOffset();
int end = element.getEndOffset();
String text = source.getText(start, end - start);
dest.insertString(dest.getLength(), text,
element.getAttributes());
}
}
} catch (BadLocationException e) {
throw new RuntimeException(e);
}
}

Related

SceneBuilder JavaFX using a Textbox, create a new line as per comma, from data received

I am building a tradebot, and I created my own UI. I gather data about my account via the API, and setText into a text field (as image shows). What I want to do, is be able to create a new line using the commas as a break, or be able to make some sort of excel table to separate the data and make it easy to use.
When I call for the data, it just dumps everything into a long, line of text.
Any suggestions on how to achieve this?
thanks,
Arthur
#FXML
void onPositionClick(ActionEvent event)
{
Context ctx = new Context("https://api-fxpractice.oanda.com", "XXXXXXXXXXXXXXXXXXXXXX-YYYYYYYYYYYYYYYYYYYYYYYY");
try
{
AccountSummary summary = ctx.account.summary(
new AccountID("101-XXX-XXXXXX-XXX")).getAccount();
String summaryString = String.valueOf(summary);
displayResults.setText(summaryString);
} //end try
catch (Exception e)
{
e.printStackTrace();
}//end catch
I would use System.lineSeparator() because its system-dependent:
String text = "abc,de,fghi,jklmn,o";
String newText = text.replaceAll(",", System.lineSeparator());
System.out.println(newText);
Output:
abc
de
fghi
jklmn
o

Get current line when some previous lines was collapsed in my own eclipse editor

Im trying to get the current line of keyboard cursor.
StyledText styledText = (StyledText) getAdapter(Control.class);
styledText.addCaretListener(event -> {
try {
IDocument document = getDocumentProvider().getDocument(getEditorInput());
// This is the current line
int currentLine = document.getLineOfOffset(event.caretOffset);
} catch (BadLocationException e) {
}
});
But the method getLineOfOffset doesn't work when some previous lines are collapsed. The event.caretOffset change if the document was collapsed.
Im tryed to use this code:
ISelectionProvider selectionProvider = ((ITextEditor)editor).getSelectionProvider();
ISelection selection = selectionProvider.getSelection();
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection)selection;
return textSelection.getStartLine();
}
But this last code return the old line selected. I think the event of addCaretListener executes before the change line (not sure).
How can I get the current line even the document was collapsed in addCaretListener event?
If your editor is using ProjectionViewer as the source viewer you can
use the ITextViewerExtension5 widgetOffset2ModelOffset method:
ISourceViewer sourceViewer = getSourceViewer(); // Get your SourceViewer
StyledText styledText = sourceViewer.getTextWidget();
int docOffset = 0;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5)sourceViewer;
docOffset = extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
}
else {
int offset = sourceViewer.getVisibleRegion().getOffset();
docOffset = offset + styledText.getCaretOffset();
}
IDocument document = sourceViewer.getDocument();
int currentLine = document.getLineOfOffset(docOffset);
(adapted from the JDT JavaEditor).

How can I dynamically change the font colour within a JTextArea?

I'm writing a script for a code editor and I want dynamic commands.
So, if the user types "class" it will change the colour of "class".
How do I do this?
// This is the main focus part of the code.
textarea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
word += evt.getKeyChar();
if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
word = "";
line = "";
lineInMemory = line;
}
if(evt.getKeyCode() == KeyEvent.VK_SPACE) {
word = word.replaceAll("null","");
line += word;
word = "";
String text = textarea.getText();
String[] words = line.split(" ");
if(word.toLowerCase().equals("class")) {
// What the heck do I put here?!
}
}
}
});
I already have key listeners that read the keys, put them into words, and then the words are put into sentences. I would like it so that they type the keyword and it automatically changes the colour of the keyword while they are still typing, a bit like what Sublime Text does.
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 might also be helpful (especially the second answer).
Here is an example:
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("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.

Getting JCheckBox selected box value

I want to ask is there a way to get information from JCheckBox without actionListener. In my code I scan a file of strings and each line has data which, if selected, should be added to an array in my program. Problem is that i will never know how many JCheckBoxes I will have, it depends from file.
So, my question is how to put selected strings to an array (or list) with a press of a button (ok) so i could do something else with them (in my case i need to get data from file or from hand input and put it in a red-black tree, so I will need to push selected strings to my putDataInTheTree method).
EDIT: Also, is it possible not to show those JCheckBoxes that already has been added to the program? I.E. if i choose fluids, next time I call input method fluids wont show in my panel?
Thanks in advance!
How it looks:
My code is so far:
public void input() {
try {
mainWindow.setEnabled(false);
fromFile = new JFrame("Input from file");
fromFile.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
fromFile.setLayout(new BorderLayout());
fromFile.setSize(300,200);
panelFromFile = new JPanel();
panelFromFile.setLayout(new java.awt.GridLayout(0,1));
JScrollPane scrollPane2 = new JScrollPane(panelFromFile);
scrollPane2.setMaximumSize(new Dimension(300, 180));
FileReader File = new FileReader(data);
BufferedReader Buffer = new BufferedReader(File);
while ((info = Buffer.readLine()) != null) {
if (info != null) {
JCheckBox check = new JCheckBox(info);
panelFromFile.add(check);
}
}
ok = new JButton("ok");
ok.addActionListener(this);
fromFile.add(scrollPane2, BorderLayout.CENTER);
fromFile.add(ok, BorderLayout.SOUTH);
fromFile.setLocationRelativeTo(null);
fromFile.setResizable(false);
fromFile.setVisible(true);
}
catch(Exception e) {
text.append("Error in INPUT method");
text.append(System.getProperty("line.separator"));
}
}
Add your checkboxes to a collection, and when the button is pressed, iterate through the checkboxes and get the text associated with each checked checkbox:
private List<JCheckBox> checkBoxes = new ArrayList<JCheckBox>();
...
while ((info = Buffer.readLine()) != null) {
if (info != null) {
JCheckBox check = new JCheckBox(info);
panelFromFile.add(check);
this.checkBoxes.add(check);
}
}
...
public void actionPerformed(ActionEvent e) {
List<String> infos = new ArrayList<String>();
for (JCheckBox checkBox : checkBoxes) {
if (checkBox.isSelected() {
infos.add(checkBox.getText());
}
}
// TODO do something with infos
}
If you store the checkboxes (e.g. in a List) you can loop over them and query their selected state when the OK button is pressed.
To obtain the String from the checkbox, you could opt to use the putClientProperty and getClientProperty methods, as explained in the class javadoc of JComponent

Is a text file in Java a GUI

Is it right to think that when you create a text file in Java, you are essentially creating a text file like the one that appears with programs like notepad?
I have a JComboBox menu with various selections. I also created a text file and had it so that the user selection will be written in the text file. So the question is, how can I have this text file that I've created to appear? (as a GUI or any other way...)
My Code:
static JFrame frame;
FileWriter f;
BufferedWriter bw;
int myAge;
String myStringAge;
for (int i = 1; i <= 100; ++i) {
ageList.add(i);
}
DefaultComboBoxModel modelAge = new DefaultComboBoxModel();
for (Integer i : ageList) {
modelAge.addElement(i);
}
JComboBox ageEntries = new JComboBox();
ageEntries.setModel(modelAge);
//Add ItemListener
ageEntries.addItemListener(new ageListener());
class ageListener implements ItemListener {
public void itemStateChanged(ItemEvent event){
myAge = (Integer) event.getItem();
myStringAge = Integer.toString(myAge);
try {
bw.write(myStringAge);
bw.close();
} catch (Exception e){
}
}
A text file is not a GUI. Use JTextArea to display text. Have a look at http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html
You can do so using JEditorPane. You might want to create a new JFrame for it. Don't forget to setContentType() to "text/plain". Then you can just create a FileReader for your file and pass it to the editor pane throught the read() method.
Start with Basic I/O. That should answer your question (and the next 9).

Categories