Java string replaceAll() - java

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?

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'

Take JTextField text and display it on JTextarea in real time

I made this program for discord. This program takes your text and puts it in this 'format' that allows discord to convert it to fancy letters. My problem is that while typing the text lags behind by 1 character. I am only a beginner and I don't know what to do to fix it.
Ps. I do not feel like using a button to convert the text!
My Code :
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
textArea.setText("");
separatedText = textField.getText().toLowerCase().toCharArray();
for(int i = 0; i < separatedText.length; i++) {
textArea.append(separate ? ":regional_indicator_" + separatedText[i] + ":\n" : ":regional_indicator_" + separatedText[i] + ":");
}
}
});
You can achieve this by adding a Document Listener to your JTextField. You don't give us what the "separate" boolean is, so i made the example in case this boolean is always true.
Small Preview:
Source Code:
package test;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class DocListenerTest extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DocListenerTest r = new DocListenerTest();
r.setVisible(true);
});
}
public DocListenerTest() {
super("test");
getContentPane().setLayout(new GridLayout(5, 2));
JTextField textField = new JTextField();
textField.setBorder(BorderFactory.createTitledBorder("TextField"));
getContentPane().add(textField);
JTextArea textArea = new JTextArea();
textArea.setBorder(BorderFactory.createTitledBorder("TextArea"));
JScrollPane sp = new JScrollPane(textArea);
getContentPane().add(sp);
setSize(400, 400);
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
addTextToArea();
}
private void addTextToArea() {
textArea.setText("");
char[] separatedText = textField.getText().toLowerCase().toCharArray();
boolean separate = true; //Don't know the value of this.
for (int i = 0; i < separatedText.length; i++) {
textArea.append(separate ? ":regional_indicator_" + separatedText[i] + ":\n"
: ":regional_indicator_" + separatedText[i] + ":");
}
}
#Override
public void insertUpdate(DocumentEvent e) {
addTextToArea();
}
#Override
public void changedUpdate(DocumentEvent e) {
addTextToArea();
}
});
}
}

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);
}
}
}

JEditorPane set foreground color for different words

I am currently working on a text editor, and I have this code which make the background of the specific word different from the others, but I want the foreground to edit color and not the background.
Here's the code I have:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class test {
final static JEditorPane jep = new JEditorPane();
static JButton button = new JButton("Refresh");
static JTextPane jTextPane1 = new JTextPane();
public static void main(String[] args) throws BadLocationException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jep.setText("Hello to the public place here are the public people");
frame.add(jep);
frame.pack();
frame.setSize(500, 500);
frame.add(button,BorderLayout.NORTH);
frame.setVisible(true);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
highlight(jep, "public");
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
highlight(jep, "public");
}
public static void highlight(JTextComponent textComp, String pattern) throws BadLocationException {
try {
final MyHighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);
Highlighter hilite = textComp.getHighlighter();
MutableAttributeSet mas = (MutableAttributeSet)new SimpleAttributeSet ();
StyleConstants.setForeground(mas, Color.red);
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= 0) {
hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);
pos += pattern.length();
}
}finally{
}
}
}
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
public MyHighlightPainter(Obect object) {
super((Color) object);
}
}
You need to take advantage of the editors StyledDocuemnt, for a simple example...
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Srap {
public static void main(String[] args) {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("I'm a Style", null);
StyleConstants.setForeground(style, Color.red);
try {
doc.insertString(doc.getLength(), "BLAH ", style);
} catch (BadLocationException ex) {
}
StyleConstants.setForeground(style, Color.blue);
try {
doc.insertString(doc.getLength(), "BLEH", style);
} catch (BadLocationException e) {
}
}
}

JTextPane: How to set the font size

Please have a look at the following code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Form extends JFrame
{
private JTextPane textPane;
private JLabel results;
private JPanel center,south;
private FlowLayout flow;
private ArrayList array;
private Color color;
private StyledDocument doc;
private Style style, fontSize;
public Form()
{
textPane = new JTextPane();
textPane.setMinimumSize(new Dimension(100,100));
doc = textPane.getStyledDocument();
doc.addDocumentListener(new TextActions());
results = new JLabel("Number of letters: ");
array = new ArrayList();
array.add("public");
array.add("static");
array.add("void");
array.add("private");
array.add("protected");
color = new Color(185,224,247);
//Adding styles
style = doc.addStyle("blue", null);
StyleConstants.setForeground(style, color);
fontSize = doc.addStyle("fontSize", null);
StyleConstants.setFontSize(fontSize, 25);
//Setting the font Size
doc.setCharacterAttributes(0, doc.getLength(), fontSize, false);
center = new JPanel();
flow = new FlowLayout();
center.setLayout(flow);
center.add(textPane);
south = new JPanel();
south.setLayout(new FlowLayout());
south.add(results);
getContentPane().add(textPane,"Center");
getContentPane().add(south,"South");
}
private class TextActions implements DocumentListener
{
#Override
public void insertUpdate(DocumentEvent e)
{
try {
highlighat();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
#Override
public void removeUpdate(DocumentEvent e)
{
try {
highlighat();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
#Override
public void changedUpdate(DocumentEvent e)
{
}
}
private void highlighat() throws BadLocationException
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
String text = "";
String content = null;
try {
content = doc.getText(0, doc.getLength()).toLowerCase();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
int last=0;
for(int i=0;i<array.size();i++)
{
text = array.get(i).toString();
if(content.contains(text))
{
while((last=content.indexOf(text,last))!=-1)
{
int end = last+text.length();
doc.setCharacterAttributes(last, end, textPane.getStyle("blue"), true);
last++;
}
}
}
}
}
);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e)
{
}
Form f = new Form();
f.setVisible(true);
f.setSize(800,600);
f.validate();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
In there, I am also trying to set the font size to 25, but as you can see, it is not working. "textPane.setFont()" also didn't work. How can I set the font size correctly? Please help..
Sure, you can create a font object and use it to set the font of your text pane.
Instantiate it like this:
Font f = new Font(Font.SANS_SERIF, 3, 5);
Maybe this code will help you, about Highlighter and StyledDocument, rest is described in the tutorial about JTextPane / EditorPane

Categories