How do I update a line already existing in JTextPane? - java

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

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 to read last word or latest word in JTextArea

I am making a Source code Editor using JtextArea.In that I want to do the following task." While user typing on Editor window(JtextArea),each and every time the updated text(last word) should compare with the set of words in the database, if it matches any one of the word then the definition will be open in new popup frame."
My coding is like following
String str = textarea.getText();
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String stm="select url from pingatabl where functn=?";
PreparedStatement st = conn.prepareStatement(stm);
st.setString(1, str);
//Excuting Query
ResultSet rs = st.executeQuery();
if (rs.next()) {
String s = rs.getString(1);
//Sets Records in frame
JFrame fm = new JFrame();
fm.setVisible(true);
fm.setSize(500,750);
JEditorPane jm = new JEditorPane();
fm.add(jm);
jm.setPage(ClassLoader.getSystemResource(s));
In the above coding String str = textarea.getText(); reads all the text in the textarea.. but i need to get last word only. How can i get latest word from JTextArea..
Use a DocumentListener to monitor for changes to the text component and use javax.swing.text.Utilities to calculate the start/end index of the word in the Document, from which you can the extract the result
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 can use following code block if you want to get the last word in the testarea
String[] wordsArray = textarea.getText().split("\\s+");
String lastWord = wordsArray[wordsArray.length - 1];
But if you want to get the last updated word then you have to use a Listener for that.
Check on DocumentListener and DocumentEvent
http://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentListener.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentEvent.html
To get the last line in your JEditorPane, split the text in the editor on \n as shown below:
String text = editor.getText();
String[] lines = text.split("\n");
String lastLine = lines[lines.length-1];
System.out.println("Last line: " + lastLine);
Similarly, to get the last word, split the last line on space.
Here a code of method that returns the last word of a text
public static String getLastWord(String s) {
int endOfLine = s.length() - 1;
boolean start = false;
while (!start && endOfLine >= 0) {
if (!Character.isLetter(s.charAt(endOfLine))) {
endOfLine--;
} else {
start = true;
}
}
final StringBuilder lastWord = new StringBuilder("");
while (start && endOfLine >= 0) {
if (!Character.isLetter(s.charAt(endOfLine))) {
start = false;
} else {
lastWord.insert(0, s.charAt(endOfLine));
endOfLine--;
}
}
return lastWord.toString();
}

Close JFrame after certain time

So I'm making a game with 3 difficulties:
Beginner
Intermediate
Expert
In the Expert level I want to close the JFrame after 60 seconds, either clicking a button to start or any other way, doesn't need to be fancy. I've tried many ways but I keep not getting what I want.
This is my code:
package battleship;
import static battleship.Countdown.interval;
import static battleship.Countdown.timer;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
static int interval;
static Timer timer;
public static void main(String[] args) {
new Test();
Scanner sc = new Scanner(System.in);
System.out.print("Input seconds => : ");
String secs = sc.nextLine();
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = Integer.parseInt(secs);
System.out.println(secs);
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private void setIcon1() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("ramboo.png")));
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
setInterval();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("BATALLA NAVAL - NIVEL PRINCIPIANTE" );
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setPreferredSize(new Dimension(900, 700));
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
void setVisible(boolean b) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private void setIconImage(Image image) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public class TestPane extends JPanel {
public TestPane() {
try {
for (int i=0; i<=1; i++){
add(crearespacios());
}
for (int i=0; i<=1; i++){
add(crearbombas());
}
//agregar frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
catch (IOException exp) {
exp.printStackTrace();
}
}
protected JToggleButton crearbombas() throws IOException {
JToggleButton btn = new JToggleButton();
btn.setModel(new StickyModel());
btn.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("botondefault.png"))));
btn.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("bombaa.png"))));
return btn;
}
protected JToggleButton crearespacios() throws IOException {
JToggleButton btn = new JToggleButton();
btn.setModel(new StickyModel());
btn.setBounds(5, 5, 50, 50);
btn.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("botondefault.png"))));
btn.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("botondefault.png"))));
return btn;
}
protected JButton Instructions() throws IOException {
JButton btnX = new JButton();
btnX.setModel(new StickyModel());
btnX.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("rambofinal.png"))));
btnX.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("rambofinal.png"))));
return btnX;
}
protected JTextField Instrucciones() throws IOException {
JTextField jtxt = new JTextField();
JTextField jtxt2 = new JTextField();
jtxt.setText("Existen 18 espacios, 5 barcos ocupan 6 de ellos.");
jtxt2.setText("Tenes 16 clicks.");
return jtxt;
}
}
private static final int setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
public class StickyModel extends JToggleButton.ToggleButtonModel {
public void reset() {
super.setSelected(false);
}
#Override
public void setSelected(boolean b) {
if (!isSelected()) {
super.setSelected(b);
}
}
}
}
Tried using System.exit(0) and System.runfinalization; here but it only showed me the "Console output(?)" and not also the Frame
Without timer:
package battleship;
import java.util.Timer;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
private void setIcon1() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("ramboo.png")));
}
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("BATALLA NAVAL - NIVEL PRINCIPIANTE" );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setPreferredSize(new Dimension(900, 700));
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
void setVisible(boolean b) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private void setIconImage(Image image) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public class TestPane extends JPanel {
public TestPane() {
try {
for (int i=0; i<=1; i++){
add(crearespacios());
}
for (int i=0; i<=1; i++){
add(crearbombas());
}
//agregar frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
catch (IOException exp) {
exp.printStackTrace();
}
}
protected JToggleButton crearbombas() throws IOException {
JToggleButton btn = new JToggleButton();
btn.setModel(new StickyModel());
btn.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("botondefault.png"))));
btn.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("bombaa.png"))));
return btn;
}
protected JToggleButton crearespacios() throws IOException {
JToggleButton btn = new JToggleButton();
btn.setModel(new StickyModel());
btn.setBounds(5, 5, 50, 50);
btn.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("botondefault.png"))));
btn.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("botondefault.png"))));
return btn;
}
protected JButton Instructions() throws IOException {
JButton btnX = new JButton();
btnX.setModel(new StickyModel());
btnX.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("rambofinal.png"))));
btnX.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("rambofinal.png"))));
return btnX;
}
protected JTextField Instrucciones() throws IOException {
JTextField jtxt = new JTextField();
JTextField jtxt2 = new JTextField();
jtxt.setText("Existen 18 espacios, 5 barcos ocupan 6 de ellos.");
jtxt2.setText("Tenes 16 clicks.");
return jtxt;
}
}
public class StickyModel extends JToggleButton.ToggleButtonModel {
public void reset() {
super.setSelected(false);
}
#Override
public void setSelected(boolean b) {
if (!isSelected()) {
super.setSelected(b);
}
}
}
}
BTW... the game is battleship and I have a custom button created in that code, that's why I need the timer in the same Frame.java as the buttons.

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?

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