How to generate html for text in JTextArea? - java

I have a problem in generating html code for a given string which is from
JTextArea textArea=new JTextArea(10,10);
String textToHtml=textArea.getText();
In this generated html code, it should contain with all html tags which are related to the given string.
Like <p>something like this</p>, <br> and etc.
Also this is not a web application. If you have any idea how do this. Suggest me. Thanks.
Update
For an example, if I type a text with line breaks, it should automatically insert <br> or <p>. This kind of function is available in Dreamweaver. It automatically inserts the code when you start filling the content in the webpage. The issue is so I don't want the non-technical usres to type the HTML code when they are writing paragraphs, because by default the tag and all are inserted. I will be emailing this directly to the user after this text is typed, so this formatting is essential.
It is important to note that I don't know what the user will type, it is all upto him. so whatever the method I use should be capable of identfying the places where it could put tags (like paragraph tag) and move on

For an example, if I type a text with line breaks, it should automatically insert <br> or <p>
The basic requirement would be to use a DocumentFilter to inject your markup when ever they type enter
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class TestMarkup {
public static void main(String[] args) {
new TestMarkup();
}
public TestMarkup() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
JTextArea ta = new JTextArea(10, 20);
add(new JScrollPane(ta));
((AbstractDocument) ta.getDocument()).setDocumentFilter(new DocumentFilter() {
#Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (text.endsWith("\n")) {
super.replace(fb, offset, 0, "<br>", attrs);
offset += 4;
}
super.replace(fb, offset, length, text, attrs);
}
});
}
}
}
Inserting <p>/</p> "might" be more difficult, but, if you assume that your first line starts with <p>, it's just a matter of inject </p> before the newline and <p> after it, then append the remaining text...
Updated with Paragraph support and pasting
Apparently I just can't walk away...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.StringJoiner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.Element;
public class TestMarkup {
public static void main(String[] args) {
new TestMarkup();
}
public TestMarkup() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
JTextArea ta = new JTextArea(10, 20);
add(new JScrollPane(ta));
((AbstractDocument) ta.getDocument()).setDocumentFilter(new DocumentFilter() {
protected String getLastLineOfText(Document document) throws BadLocationException {
// Find the last line of text...
Element rootElem = document.getDefaultRootElement();
int numLines = rootElem.getElementCount();
Element lineElem = rootElem.getElement(numLines - 1);
int lineStart = lineElem.getStartOffset();
int lineEnd = lineElem.getEndOffset();
String lineText = document.getText(lineStart, lineEnd - lineStart);
return lineText;
}
#Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if (text.length() > 1) {
String lastLineOfText = getLastLineOfText(fb.getDocument());
if (!lastLineOfText.startsWith("<p>")) {
if (!text.startsWith("<p>")) {
text = "<p>" + text;
}
}
// Replace any line breaks with a new line
String[] lines = text.split("\n");
if (lines.length > 0) {
StringJoiner sj = new StringJoiner("<br>\n");
for (String line : lines) {
sj.add(line);
}
text = sj.toString();
}
if (!text.endsWith("</p>")) {
text += "</p>";
}
super.replace(fb, offset, length, text, attrs);
} else {
String postInsert = null;
if (text.endsWith("\n")) {
// Find the last line of text...
String lastLineOfText = getLastLineOfText(fb.getDocument());
lastLineOfText = lastLineOfText.substring(0, lastLineOfText.length() - 1);
postInsert = "<p>";
if (!lastLineOfText.endsWith("</p>")) {
super.replace(fb, offset, 0, "</p>", attrs);
offset += 4;
}
}
super.replace(fb, offset, length, text, attrs);
if (postInsert != null) {
offset += text.length();
super.replace(fb, offset, 0, "<p>", attrs);
}
}
}
});
}
}
}

Maybe you need something like this:
String textToHtml="something like this";
textToHtml = "<p>".concat(textToHtml).concat("</p>").concat("<br>");

Related

how replace last word text area with some word?

i got code from madprogrammer :
How to read last word or latest word in JTextArea
but i need to replace the last word in text area , maybe using document filtering or by space span(" ") between lastword and beforelastword.
can someone help me please? i search in google still didn't found the way.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Utilities;
public class TheLastWord {
public static void main(String[] args) {
new TheLastWord();
}
public TheLastWord() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
JTextArea ta = new JTextArea(10, 20);
add(new JScrollPane(ta));
JLabel lastWord = new JLabel("...");
add(lastWord, BorderLayout.SOUTH);
ta.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
checkLastWord();
}
#Override
public void removeUpdate(DocumentEvent e) {
checkLastWord();
}
#Override
public void changedUpdate(DocumentEvent e) {
checkLastWord();
}
protected void checkLastWord() {
try {
int start = Utilities.getWordStart(ta, ta.getCaretPosition());
int end = Utilities.getWordEnd(ta, ta.getCaretPosition());
String text = ta.getDocument().getText(start, end - start);
lastWord.setText(text);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
you could youse split. and get the last index and then insert with substrings like this
String sentence ="Meow test test hello test.";
String[] temp = sentence.split("[|!|\\?|.|\\s|\\n]");
String word = temp[temp.length-1];
int index = sentence.lastIndexOf(word);
String out = sentence.substring(0,index) + " INSERTED WORD" + sentence.substring(index+word.length(), sentence.length());
You can use a regex like this (\w+.?)$, which will match the last word of a string, even when it ends with a ..
String sentence = "I am a full sentence";
String replaced = sentence.replaceAll("(\\w+.?)$", "replaced");
System.out.println(replaced); // prints 'I am a full replaced'

How do I update a line already existing in JTextPane?

I would like to add a few lines to JTextPane, such as Joseph Red, Clarita Red, Bob Red, then later I would like to update both the name and color of a particular line, such as, I would like to change Joseph Red to Rudo Blue, or Bob Red to Molly Blue. Is there a way to do so? I wanted to record each line whenever adding a line to JTextPane and reference that particular line to update later on, but could not think of a way.
String color = "Red";
JTextPane textPanel = new JTextPane();
public void addToTextPane(String name) throws BadLocationException //Add each line to JTextPane
{
document = (StyledDocument) textPanel.getDocument();
document.insertString(document.getLength(), name + "" + color, null);
document.insertString(document.getLength(), "\n", null);
}
I am attempting to do something like the following (Update name and color of that a particular line that's already in the JTextPane):
if(...){
status = "Blue";
try
{
addTextPane("Jospeh"); //If I do this, it would not update the already exiting line and
//simply just add a new line with the name 'Joseph' and color 'Blue'
}
catch (BadLocationException e)
{
e.printStackTrace();
}
}
A for-loop in combination with Document#getText, Document#remove Document#insertString should do the trick...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextPane textPane;
private String fruit[] = {"Bananas", "Apples", "Oranges", "Kiwis"};
private int index;
public TestPane() {
StringBuilder text = new StringBuilder(64);
text.append("Bananas in pajamas are coming down the stairs\n").
append("Bananas in pajamas are coming down in pairs\n").
append("Bananas in pajamas are chasing teddy bears\n").
append("Cause on tuesdays they try to catch their man-o-wears");
textPane = new JTextPane();
textPane.setText(text.toString());
setLayout(new BorderLayout());
add(new JScrollPane(textPane));
JButton btn = new JButton("Update");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
index++;
String find = fruit[(index - 1) % fruit.length];
String replace = fruit[index % fruit.length];
System.out.println("Find: " + find);
System.out.println("Replace: " + replace);
Document doc = textPane.getDocument();
try {
for (int pos = 0; pos < doc.getLength() - find.length(); pos++) {
String text = doc.getText(pos, find.length());
if (find.equals(text)) {
doc.remove(pos, find.length());
doc.insertString(pos, replace, null);
}
}
} catch (BadLocationException exp) {
exp.printStackTrace();
}
}
});
add(btn, BorderLayout.SOUTH);
}
}
}

Alphabets validation of jtextfield

I have been trying to just display the alphabets in the jtextfield.Even though the other keys are pressed the jtextfield should not display them only the alphabets are to be displayed.can you please help me with this..
Start by taking a look at Implementing a Document Filter
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class TestFilter {
public static void main(String[] args) {
new TestFilter();
}
public TestFilter() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JTextField field = new JTextField(10);
((AbstractDocument)field.getDocument()).setDocumentFilter(new CharFilter());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class CharFilter extends DocumentFilter {
#Override
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
StringBuilder buffer = new StringBuilder(string);
for (int i = buffer.length() - 1; i >= 0; i--) {
char ch = buffer.charAt(i);
if (!Character.isAlphabetic(ch)) {
buffer.deleteCharAt(i);
}
}
super.insertString(fb, offset, buffer.toString(), attr);
}
#Override
public void replace(DocumentFilter.FilterBypass fb,
int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
}
You ma also find DocumentFilter Examples helpful
here is a solution if you want only alphabets to be entered to a jtextfield,and no other keys should be entered even though they get pressed.in your jframe just select your jtextfield rightclick on jtextfield you will find events and then go to events click on keyTyped event and then write the following code to enter only the alphabets into your jtextfield.
private void tfempidKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
char key = evt.getKeyChar();
if (key > '0' && key < '9') {
evt.consume();
}

Trying to use key Listener

I have a program that implements keyListener. What I'm trying to do is only allow digits, backspace key, decimal key, and back arrow key to be pressed. Everything works except when I pressed the back arrow key it deletes the numbers I input`
public void keyReleased(KeyEvent e) {
try{
if(!Character.isDigit(e.getKeyChar()) && e.getKeyChar() != '.' && e.getKeyChar() != e.VK_BACK_SPACE && e.getKeyChar() != KeyEvent.VK_LEFT){
String input = inputIncome.getText();
inputIncome.setText(input.substring(input.length()-1));
}
}
catch(Exception arg){
}`
KeyListener rules...
Don't use KeyListener for components which don't require focus to be activated, even then, use Key Bindings instead
Don't use KeyListener on text components, use a DocumentFilter instead
Based on the fact that you seem to be changing the contents of, what I assume is, a JTextField or text component, you should be using a DocumentFilter to filter the changes been sent to the fields Document, for example...
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
public class DocumentFilterExample {
public static void main(String[] args) {
new DocumentFilterExample();
}
public DocumentFilterExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(10);
((AbstractDocument)field.getDocument()).setDocumentFilter(new DecimalDocumentFilter());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DecimalDocumentFilter extends DocumentFilter {
#Override
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr)
throws BadLocationException {
Document doc = fb.getDocument();
boolean hasDot = doc.getText(0, doc.getLength()).contains(".");
StringBuilder buffer = new StringBuilder(text);
for (int i = buffer.length() - 1; i >= 0; i--) {
char ch = buffer.charAt(i);
if (!Character.isDigit(ch)) {
if ((ch == '.' && !hasDot)) {
hasDot = true;
} else {
buffer.deleteCharAt(i);
}
}
}
super.insertString(fb, offset, buffer.toString(), attr);
}
#Override
public void replace(DocumentFilter.FilterBypass fb,
int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
}
This is based on the examples here.
There are number of reasons for not using a KeyListener in this way, for example...
You can't guarantee the order in which the listeners are activated, it's entirely possible that the event may be consumed before it reaches you or the content has not yet been added to the field's Document
It doesn't take into account what happens when you paste text into the field
It could cause a mutation exception as the document is been updated while you're trying to change it...
Just to name a few

Java string replaceAll()

I've been wondering if for example:
JTextPane chatTextArea = new JTextPane();
s.replaceAll(":\\)", emoticon());
public String emoticon(){
chatTextArea.insertIcon(new ImageIcon(ChatFrame.class.getResource("/smile.png")));
return "`";
}
can put a picture and a "`" everywhere ":)" is found. When I run it like this if s contains a ":)" then the whole s gets replaced just by the icon.
Is there a way to do it?
Here is a small example I made (+1 to #StanislavL for the original), simply uses DocumentListener and checks when a matching sequence for an emoticon is entered and replaces it with appropriate image:
NB: SPACE must be pressed or another character/emoticon typed to show image
import java.awt.Dimension;
import java.awt.Image;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.Utilities;
public class JTextPaneWithEmoticon {
private JFrame frame;
private JTextPane textPane;
static ImageIcon smiley, sad;
static final String SMILEY_EMOTICON = ":)", SAD_EMOTICON = ":(";
String[] emoticons = {SMILEY_EMOTICON, SAD_EMOTICON};
private void initComponents() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textPane = new JTextPane();
//add docuemntlistener to check for emoticon insert i.e :)
((AbstractDocument) textPane.getDocument()).addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(final DocumentEvent de) {
//We should surround our code with SwingUtilities.invokeLater() because we cannot change document during mutation intercepted in the listener.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
StyledDocument doc = (StyledDocument) de.getDocument();
int start = Utilities.getRowStart(textPane, Math.max(0, de.getOffset() - 1));
int end = Utilities.getWordStart(textPane, de.getOffset() + de.getLength());
String text = doc.getText(start, end - start);
for (String emoticon : emoticons) {//for each emoticon
int i = text.indexOf(emoticon);
while (i >= 0) {
final SimpleAttributeSet attrs = new SimpleAttributeSet(doc.getCharacterElement(start + i).getAttributes());
if (StyleConstants.getIcon(attrs) == null) {
switch (emoticon) {//check which emtoticon picture to apply
case SMILEY_EMOTICON:
StyleConstants.setIcon(attrs, smiley);
break;
case SAD_EMOTICON:
StyleConstants.setIcon(attrs, sad);
break;
}
doc.remove(start + i, emoticon.length());
doc.insertString(start + i, emoticon, attrs);
}
i = text.indexOf(emoticon, i + emoticon.length());
}
}
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(300, 300));
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {//attempt to get icon for emoticons
smiley = new ImageIcon(ImageIO.read(new URL("http://facelets.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/e/m/emoticons0001.png")).getScaledInstance(24, 24, Image.SCALE_SMOOTH));
sad = new ImageIcon(ImageIO.read(new URL("http://zambia.primaryblogger.co.uk/files/2012/04/sad.jpg")).getScaledInstance(24, 24, Image.SCALE_SMOOTH));
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JTextPaneWithEmoticon().initComponents();
}
});
}
}
References:
How to add smileys in java swing?

Categories