Take JTextField text and display it on JTextarea in real time - java

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

Related

action listener doesnt work

I am new in java swing unfortunately when i want to set action listener to one of the button that it has to get the textArea content and send that to another class it doesn't work in a way that i expect and instead it works when i change the text area's content, i don't know What's happened?
first button i named Button and the same problem happened when i use another action listener inside the Button's action listener named Clac
here is my code:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class FFT_Main_Frame extends JFrame {
JLabel label;
JButton button;
TextPanel txtPanel;
JButton Button;
JLabel label1;
// JTextArea[] BoxArray;
makePolynomial mp;
JButton Calc;
Complex[] Nums;
Complex[] Result;
int input;
FFT_Main fft_main;
ShowResult shr;
public FFT_Main_Frame() {
Button.addActionListener(new ActionListener() {
// Test t;
// Integer content;
#Override
public void actionPerformed(ActionEvent arg0) {
try {
Integer content = new Integer(Integer.parseInt(txtPanel.getTextArea()));
input = content;
System.out.println(input);
// inputt=input;
mp = new makePolynomial(content);
setLayout(new FlowLayout());
add(mp);
// setLayout(new BorderLayout());
add(Calc);
Nums = new Complex[input + 1];
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
for (int i = input; i >= 0; i--) {
Nums[i] = new Complex(Double.parseDouble(mp.BoxArray[2 * (i + 1) - 1].getText()),
Double.parseDouble(mp.BoxArray[2 * i].getText()));
}
for (int i = 0; i <= input; i++) {
System.out.println(Nums[i]);
}
fft_main = new FFT_Main();
Result = new Complex[input];
Result = fft_main.Recursive_FFT(Nums);
shr = new ShowResult(Result);
setLayout(new BorderLayout());
add(shr, BorderLayout.CENTER);
System.out.println("Result\n\n");
for (int i = 0; i <= input; i++) {
System.out.println(Result[i]);
}
}
});
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "Please Enter Just Numbers! ", "Wrong Value",
JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
thanks for your help
You are using action listener wrong way here is an example how to use it
public FFT_Main_Frame() {
JButton Button = new JButton("Button");
Button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
// Code Here
}catch(Exception e) {
// Code Here
}
});
JButton Calc = new JButton("Calc");
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// Code Here
}
});
}
}
Some tutorials on how to use action listener
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
http://www.tutorialspoint.com/swing/swing_action_listener.htm

Set Text in Editor Component in Combobox

My goal is to create a filtered combobox.
I create an editable combobox. When the user enters text, the code searches matching items in the model. When the user leaves the combobox, the code selects the selected item from the list. Further, the text from the editor component gets the value of the selected item.
When the focus goes back to the combobox via shift + tab, the editor component gets the text of the selected element. After releasing the shift key, the keylistener runs. In this case, the editor component contains the text entered previously, e.g., the value set when the focus is lost.
How can I set the text of the editorComponent to make it persist?
Here's the code:
package de.ccw.reports.gui.incomingOrder.MyComboBox;
import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.text.JTextComponent;
import de.ccw.commons.ui.comp.XComboBox;
public class FilterableComboBox<E> extends XComboBox<E> {
ComboBoxModel<E> originalModel;
DefaultComboBoxModel<E> filteredModel;
JTextComponent editorComp;
JList<E> list;
public FilterableComboBox(ComboBoxModel<E> aModel) {
super();
receivePopupList();
originalModel = aModel;
filteredModel = new DefaultComboBoxModel<>();
setModel(filteredModel);
editorComp = (JTextComponent) getEditor().getEditorComponent();
editorComp.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
System.out.println("focusLostStart=" + getSelectedItem() + "|" + editorComp.getText());
String text = editorComp.getText();
editorComp.setText("");
setSelectedItem(null);
if(list.getSelectedIndex() != -1 && text.isEmpty() == false){
setSelectedIndex(list.getSelectedIndex());
editorComp.setText(getSelectedItem().toString());
}
System.out.println("focusLostEnd=" + getSelectedItem() + "|" + editorComp.getText());
}
#Override
public void focusGained(FocusEvent e) {
System.out.println("focusGainedStart=" + getSelectedItem() + "|" + editorComp.getText());
E element = getSelectedItem();
String text = editorComp.getText();
performModelFilter(null);
showPopup();
setSelectedItem(element);
editorComp.setText(text);
editorComp.selectAll();
System.out.println("focusGainedEnd=" + getSelectedItem() + "|" + editorComp.getText());
}
});
editorComp.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
}
String filterBkp = "";
#Override
public void keyReleased(KeyEvent e) {
String filter = editorComp.getText();
System.out.println("keyReleased-" + filterBkp + filter);
if(filter.equals(filterBkp) == false)
refreshModel();
filterBkp = filter;
}
#Override
public void keyPressed(KeyEvent e) {
}
});
setEditable(true);
}
#SuppressWarnings("unchecked")
private void receivePopupList() {
BasicComboPopup popup = (BasicComboPopup) getAccessibleContext().getAccessibleChild(0);
list = popup.getList();
}
private void refreshModel() {
String filter = editorComp.getText();
performModelFilter(filter);
editorComp.setText(filter);
}
private void performModelFilter(String filter) {
System.out.println("performModelFilter-" + filter);
filteredModel.removeAllElements();
for(int i = 0; i < originalModel.getSize(); i++){
E element = originalModel.getElementAt(i);
String value = element.toString().toUpperCase();
if (filter == null || value.contains(filter.toUpperCase())) {
filteredModel.addElement(element);
}
}
}
public static void main(String args[]){
FilterableComboBox<String> combo = new FilterableComboBox<>(new DefaultComboBoxModel<>(new String[]{"abc", "def", "ghi", "jkl", "mnoabc", "pqrdef"}));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(new JTextField(20));
frame.add(combo);
frame.add(new JTextField(20));
frame.pack();
frame.setVisible(true);
}
}

Can't access variables for SwingWorker

I am trying to get this SwingWorker to function correctly. However,the variables that need to be accessed seem to be not global. What do I do? I tried adding static but it creates more errors and complications later about accessing static from non static. The variables that are not working in the SwingWorker are the LOCAL_FILE and URL_LOCATION variables.
package professorphysinstall;
//Imports
import com.sun.jmx.snmp.tasks.Task;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import javax.tools.FileObject;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
public class ProfessorPhysInstall {
/**
* #param args the command line arguments
*/
static class Global {
public String location;
}
public static void main(String[] args) {
// TODO code application logic here
//Variables
final JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
final JPanel cards = new JPanel(new CardLayout());
final CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(TextPaneScreen1);
JTextArea TextAreaScreen1 = new JTextArea();
JScrollPane sbrText = new JScrollPane(TextAreaScreen1);
TextAreaScreen1.setRows(15);
TextAreaScreen1.setColumns(40);
TextAreaScreen1.setEditable(false);
TextAreaScreen1.setText("stuff");
TextAreaScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextAreaScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(sbrText);
final JCheckBox Acceptance = new JCheckBox();
Acceptance.setText("I Accept The EULA Agreenment.");
screen1.add(Acceptance);
final JButton NextScreen1 = new JButton();
NextScreen1.setText("Next");
NextScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.next(cards);
}
});
screen1.add(NextScreen1);
JButton CancelScreen1 = new JButton();
CancelScreen1.setText("Cancel");
CancelScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen1.add(CancelScreen1);
cards.add(screen1);
//Screen2
final JPanel screen2 = new JPanel();
JPanel screen3 = new JPanel();
JTextPane TextPaneScreen2 = new JTextPane();
TextPaneScreen2.setEditable(false);
TextPaneScreen2.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher. Professor Phys will be installed there.");
TextPaneScreen2.setSize(358, 48);
TextPaneScreen2.setLocation(0, 0);
TextPaneScreen2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen2.setMargin(new Insets(4,4,4,4));
screen2.add(TextPaneScreen2);
JLabel screen2instructions = new JLabel();
screen2instructions.setText("Launcher Location: ");
screen2.add(screen2instructions);
final JTextField folderlocation = new JTextField(25);
screen2.add(folderlocation);
final JButton Browse = new JButton();
final JLabel filelocation = new JLabel();
final JLabel filename = new JLabel();
Browse.setText("Browse");
Browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Create a file chooser
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(screen2);
folderlocation.setText(fc.getSelectedFile().getAbsolutePath());
filelocation.setText(fc.getCurrentDirectory().getAbsolutePath());
filename.setText(fc.getSelectedFile().getName());
}
});
screen2.add(filelocation);
screen2.add(filename);
screen3.add(filelocation);
filelocation.setVisible(false);
filename.setVisible(false);
screen2.add(Browse);
final JButton BackScreen2 = new JButton();
BackScreen2.setText("Back");
BackScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen2.add(BackScreen2);
final JButton NextScreen2 = new JButton();
NextScreen2.setText("Next");
NextScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Checking Code
String correctname = "Future_Retro_Gaming_Launcher.jar";
if (filename.getText().equals(correctname))
{
cl.next(cards);
}
else
{
JFrame popup = new JFrame();
popup.setBounds(0, 0, 380, 100);
Label error = new Label();
error.setText("Sorry you must select your Future_Retro_Gaming_Launcher.jar");
popup.add(error);
popup.show();
}
}
});
screen2.add(NextScreen2);
JButton CancelScreen2 = new JButton();
CancelScreen2.setText("Cancel");
CancelScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen2.add(CancelScreen2);
cards.add(screen2);
//Screen3
JTextPane TextPaneScreen3 = new JTextPane();
TextPaneScreen3.setEditable(false);
TextPaneScreen3.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen3.setText("Professor Phys will be instaleld in the directory you have chosen. Please make sure\nyour launcher is in that folder or the game will not work.\nClick next to begin the install process.");
TextPaneScreen3.setSize(358, 48);
TextPaneScreen3.setLocation(0, 0);
TextPaneScreen3.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen3.setMargin(new Insets(4,4,4,4));
screen3.add(TextPaneScreen3);
final JButton BackScreen3 = new JButton();
BackScreen3.setText("Back");
BackScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen3.add(BackScreen2);
final JButton NextScreen3 = new JButton();
NextScreen3.setText("Next");
NextScreen3.addActionListener(new ActionListener() {
#Override
#SuppressWarnings({"null", "ConstantConditions"})
public void actionPerformed(ActionEvent ae) {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(filelocation.getText());
String URL_LOCATION = "https://dl.dropboxusercontent.com/u/10429987/Future%20Retro%20Gaming/ProfessorPhys.iso";
String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(LOCAL_FILE+"professorphys.iso", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
});
screen3.add(NextScreen3);
JButton CancelScreen3 = new JButton();
CancelScreen3.setText("Cancel");
CancelScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen3.add(CancelScreen3);
System.out.println("Done");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
screen3.add(progress);
cards.add(screen3);
mainframe.add(cards);
mainframe.setVisible(true);
}
}
class DownloadWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Your program is mostly a huge static main method. You're kind of getting the cart in front of the horse trying to do advanced programming such as with SwingWorker before first creating clean OOP code. In other words -- start over and do it right. Then the connections between classes will be much more natural and it will be much easier to get things to work right. The main method should only concern itself with starting the Swing event thread, creating a GUI object in that thread, and displaying it. Everything else should be in classes that create objects.
Also, on a more practical level, you have yet to tell us what variables are causing you trouble or what errors you might be seeing. Also, where are you trying to create and execute the SwingWorker?
Edit
One tip that will likely help: Give your SwingWorker class a constructor, and pass important parameters into your SwingWorker object via constructor parameters. Then use those parameters to initialize class fields that will be used in the SwingWorker's doInBackground method.
e.g.,
class DownloadWorker extends SwingWorker<Integer, Integer>
{
private String urlLocation;
private String localFile;
public DownLoadWorker(String urlLocation, String localFile) {
this.urlLocation = urlLocation;
this.localFile = localFile;
}
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(urlLocation);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(localFile +"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

working with Swing timer : creating mess

Just want the color of the letters to change with a little pauses (pause may vary as per the time given for a word and length of the word).
The following code works fine for me.But I think I have created a mess with my logic.I can understand, but it should be easy for my team mates to understand.
Code:
import java.awt.Color;
import java.lang.reflect.InvocationTargetException;
import java.awt.Toolkit;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Reminder
{
static JFrame frame;
Toolkit toolkit;
Timer timer;
int point=0,temp=0,hil=0,point2=0;long time1=0,time2=0;
static StyledDocument doc;
static JTextPane textpane;
String[] arr={"Tes"," hiiii"," what"," happpn"};
int i=0;
int[] a=new int[5];
public Reminder()
{
a[0]=1000;
a[1]=900;
a[2]=300;
a[3]=1500;
a[4]=1700;
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent)
{
point =arr[i].length();
temp=point+1;
time1=System.currentTimeMillis();
new Thread(new t1()).start();
}
};
timer = new Timer(a[i], actionListener);
timer.setInitialDelay(0);
timer.start();
}
public class t1 implements Runnable
{ /* true idea to use current time is beacuse i want to check and make
sure that the time taken since the timer started, and the present time should
not exceed the time given in the array in any case*/
public void run()
{
try
{
time2=System.currentTimeMillis();
while(time2-time1<=a[i]-200){Thread.sleep((long) (a[i] / (arr[i].length() * 4)));
if(hil<=temp-1)
{
doc.setCharacterAttributes(point2,hil, textpane.getStyle("Red"), true);}
hil++;
time2=System.currentTimeMillis();
}
doc.setCharacterAttributes(point2,point+1, textpane.getStyle("Red"), true);
point2+=point;hil=0;i++;
timer.setDelay(a[i]);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void newcompo()
{
JPanel panel = new JPanel();
doc = (StyledDocument) new DefaultStyledDocument();
textpane = new JTextPane(doc);
textpane.setText("Test hiiii what happpn");
javax.swing.text.Style style = textpane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
panel.add(textpane);
frame.add(panel);
frame.pack();
}
public static void main(String args[]) throws InterruptedException
, InvocationTargetException
{
SwingUtilities.invokeAndWait(new Runnable()
{
#Override
public void run()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
newcompo();
Reminder aa= new Reminder();
}
});
}
}
Any suggestions?How can I simplify?
UPDATE FOR ERROR
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class KaraokeTest {
private int[] timingsArray = {1000, 900, 300, 1500};//word/letters timings
private String[] individualWordsToHighlight = {"Tes", " hiiii", " what", " happpn"};//each individual word/letters to highlight
private int count = 0;
private final JTextPane jtp = new JTextPane();
private final JButton startButton = new JButton("Start");
private final JFrame frame = new JFrame();
public KaraokeTest() {
initComponents();
}
private void initComponents() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
for (String s : individualWordsToHighlight) {
String tmp = jtp.getText();
jtp.setText(tmp + s);
}
jtp.setEditable(false);
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
startButton.setEnabled(false);
count = 0;
//create Arrays of individual letters and their timings
final ArrayList<String> chars = new ArrayList<>();
final ArrayList<Integer> charsTiming = new ArrayList<>();
for (String s : individualWordsToHighlight) {
for (int i = 0; i < s.length(); i++) {
chars.add(String.valueOf(s.charAt(i)));
System.out.println(String.valueOf(s.charAt(i)));
}
}
for (int x = 0; x < timingsArray.length; x++) {
for (int i = 0; i < individualWordsToHighlight[x].length(); i++) {
charsTiming.add(timingsArray[x] / individualWordsToHighlight[x].length());
System.out.println(timingsArray[x] / individualWordsToHighlight[x].length());
}
}
new Timer(1, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
if (count < charsTiming.size()) {
highlightNextWord();
//restart timer with new timings
((Timer) ae.getSource()).setInitialDelay(charsTiming.get(count));
((Timer) ae.getSource()).restart();
} else {//we are at the end of the array
reset();
((Timer) ae.getSource()).stop();//stop the timer
}
count++;//increment counter
}
}).start();
}
});
frame.add(jtp, BorderLayout.CENTER);
frame.add(startButton, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
private void reset() {
startButton.setEnabled(true);
jtp.setText("");
for (String s : individualWordsToHighlight) {
String tmp = jtp.getText();
jtp.setText(tmp + s);
}
JOptionPane.showMessageDialog(frame, "Done");
}
private void highlightNextWord() {
//we still have words to highlight
int sp = 0;
for (int i = 0; i < count + 1; i++) {//get count for number of letters in words (we add 1 because counter is only incrementd after this method is called)
sp += 1;
}
//highlight words
Style style = jtp.addStyle("RED", null);
StyleConstants.setForeground(style, Color.RED);
((StyledDocument) jtp.getDocument()).setCharacterAttributes(0, sp, style, true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new KaraokeTest();
}
});
}
}
Gives me Exception:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - illegal start of type
at KaraokeTest$1.actionPerformed(KaraokeTest.java:47)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
OK, here is a cleaned up version of your code which should approximatively perform the same thing:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Reminder {
private static final String TEXT = "Test hiiii what happpn";
private static final String[] WORDS = TEXT.split(" ");
private JFrame frame;
private Timer timer;
private StyledDocument doc;
private JTextPane textpane;
private List<Integer> times = Arrays.asList(1000, 900, 300, 1500);
private int stringIndex = 0;
private int index = 0;
public void startColoring() {
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
doc.setCharacterAttributes(stringIndex, 1, textpane.getStyle("Red"), true);
stringIndex++;
try {
if (stringIndex >= doc.getLength() || doc.getText(stringIndex, 1).equals(" ")) {
index++;
}
if (index < times.size()) {
double delay = times.get(index).doubleValue();
timer.setDelay((int) (delay / WORDS[index].length()));
} else {
timer.stop();
System.err.println("Timer stopped");
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
};
timer = new Timer(times.get(index), actionListener);
timer.setInitialDelay(0);
timer.start();
}
public void initUI() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
doc = new DefaultStyledDocument();
textpane = new JTextPane(doc);
textpane.setText(TEXT);
javax.swing.text.Style style = textpane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
panel.add(textpane);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
Reminder reminder = new Reminder();
reminder.initUI();
reminder.startColoring();
}
});
}
}
A few tricks to help others read and understand your code:
Use coherent and appropriate indentation (I personnally try to stick to default Sun Java conventions)
Follow the Java coding conventions (constants are in upper-case, class name starts with an upper-case, variables and methods start with a lower case, use camel case)
Use meaningful variable and method names
class member should be declared one by one (don't use int i, j, k; )
Use a single instruction per line (avoid stuffs like if(something) doSomething(); else {doSomethingElse1(); doSomethingElse2();} on a single line)
Avoid unnecessary usage of the static keyword (to the exception of constants)
Try to avoid coupling your code so much (try to make the minimum assumptions on how the rest of the code performs)
Add javadoc and comments in your code, this is always a good practice and it is of great help for you and others.
Your main cause for concern is that you not doing the updates related to JTextPane on the Event Dispatch Thread.
For a situation like this, when you really wanted to update a certain thingy from another Thread, always use EventQueue.invokeLater(...) or EvenQueue.invokeAndWait(), which can asynchronously (former)/synchronously (latter) update your request on the EDT, though care must be taken, as invokeAndWait() might can lead to deadlocks/run conditions if not used in the right sense.
Here is your updated code, that might work for your expectations. Hope you can modify the code, as per your liking.
import javax.swing.*;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 1/12/13
* Time: 5:55 PM
* To change this template use File | Settings | File Templates.
*/
public class ColouringText
{
private StyledDocument document;
private JTextPane textPane;
private String message;
private String[] parts;
private Timer timer;
private int counter;
private int start, end;
private Thread thread = new Thread()
{
#Override
public void run()
{
while (counter < parts.length)
{
final int len = parts[counter++].length();
try
{
EventQueue.invokeAndWait(new Runnable()
{
#Override
public void run()
{
document.setCharacterAttributes(
start, len, textPane.getStyle("RED"), true);
}
});
Thread.sleep(len * 1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
start += (len + 1);
}
}
};
public ColouringText()
{
document = (StyledDocument) new DefaultStyledDocument();
message = "Hello there... Joey Rohan. Had you ever thought about putting indentations before pasting your code.";
parts = message.split(" ");
counter = 0;
start = 0;
end = 6;
System.out.println("Message Length : " + message.length());
}
private void displayGUI()
{
JFrame frame = new JFrame("Colouring Text Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
textPane = new JTextPane(document);
textPane.setText(message);
Style style = textPane.addStyle("RED", null);
StyleConstants.setForeground(style, Color.RED);
contentPane.add(textPane);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
thread.start();
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ColouringText().displayGUI();
}
});
}
}
Having been the one who answered your 2 previous questions on a similar task:
highlighting words in java
highlighting the word in java
and others not agreeing on my close vote, I decided to work on this a bit.
I have taken my latest example and edited to simplify where possible etc to make things more readable for you to understand, which in turn should help you understand how to go about simplifying your own.
I dont understand why you start a new thread to make words highlight slowly. Simply use my other examples and supply single letters rather than multiple letters and their timings to highlight, thus they will be highlighted individually. Or just make a method to do this work for you and iterate through those arrays as the letters and timings.
The below example uses an array of integers which hold the timings for words to be highlighted. It also contains an array for each individual word/letters we would like to highlight:
private int[] timingsArray = {1000, 900, 300, 1500};//word/letters timings
private String[] individualWordsToHighlight = {"Tes", " hiiii", " what", " happpn"};//each individual word/letters to highlight
In our start button we have a method to convert the above to single timings/letters for each individual letter for a letter by letter highlight:
//create Arrays of individual letters and their timings
final ArrayList<String> chars = new ArrayList<>();
final ArrayList<Integer> charsTiming = new ArrayList<>();
for (String s : individualWordsToHighlight) {
for (int i = 0; i < s.length(); i++) {
chars.add(String.valueOf(s.charAt(i)));
System.out.println(String.valueOf(s.charAt(i)));
}
}
for (int x = 0; x < timingsArray.length; x++) {
for (int i = 0; i < individualWordsToHighlight[x].length(); i++) {
charsTiming.add(timingsArray[x] / individualWordsToHighlight[x].length());
System.out.println(timingsArray[x] / individualWordsToHighlight[x].length());
}
}
Next there is a single Timer which will be started when start button is pressed which will highlight words/letters and restart itself with a new delay each time until all words/letters have been highlighted:
new Timer(1, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
if (count < charsTiming.size()) {
highlightNextWord();
//restart timer with new timings
((Timer) ae.getSource()).setInitialDelay(charsTiming.get(count));
((Timer) ae.getSource()).restart();
} else {//we are at the end of the array
reset();
((Timer) ae.getSource()).stop();//stop the timer
}
count++;//increment counter
}
}).start();
Hope this helps.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class KaraokeTest {
private int[] timingsArray = {1000, 900, 300, 1500};//word/letters timings
private String[] individualWordsToHighlight = {"Tes", " hiiii", " what", " happpn"};//each individual word/letters to highlight
private int count = 0;
private final JTextPane jtp = new JTextPane();
private final JButton startButton = new JButton("Start");
private final JFrame frame = new JFrame();
public KaraokeTest() {
initComponents();
}
private void initComponents() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
for (String s : individualWordsToHighlight) {
String tmp = jtp.getText();
jtp.setText(tmp + s);
}
jtp.setEditable(false);
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
startButton.setEnabled(false);
count = 0;
//create Arrays of individual letters and their timings
final ArrayList<String> chars = new ArrayList<>();
final ArrayList<Integer> charsTiming = new ArrayList<>();
for (String s : individualWordsToHighlight) {
for (int i = 0; i < s.length(); i++) {
chars.add(String.valueOf(s.charAt(i)));
System.out.println(String.valueOf(s.charAt(i)));
}
}
for (int x = 0; x < timingsArray.length; x++) {
for (int i = 0; i < individualWordsToHighlight[x].length(); i++) {
charsTiming.add(timingsArray[x] / individualWordsToHighlight[x].length());
System.out.println(timingsArray[x] / individualWordsToHighlight[x].length());
}
}
new Timer(1, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
if (count < charsTiming.size()) {
highlightNextWord();
//restart timer with new timings
((Timer) ae.getSource()).setInitialDelay(charsTiming.get(count));
((Timer) ae.getSource()).restart();
} else {//we are at the end of the array
reset();
((Timer) ae.getSource()).stop();//stop the timer
}
count++;//increment counter
}
}).start();
}
});
frame.add(jtp, BorderLayout.CENTER);
frame.add(startButton, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
private void reset() {
startButton.setEnabled(true);
jtp.setText("");
for (String s : individualWordsToHighlight) {
String tmp = jtp.getText();
jtp.setText(tmp + s);
}
JOptionPane.showMessageDialog(frame, "Done");
}
private void highlightNextWord() {
//we still have words to highlight
int sp = 0;
for (int i = 0; i < count + 1; i++) {//get count for number of letters in words (we add 1 because counter is only incrementd after this method is called)
sp += 1;
}
//highlight words
Style style = jtp.addStyle("RED", null);
StyleConstants.setForeground(style, Color.RED);
((StyledDocument) jtp.getDocument()).setCharacterAttributes(0, sp, style, true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new KaraokeTest();
}
});
}
}
UPDATE
In response to your edited question.
Again the code complies fine for me, which brings me to the conclusion our java Runtimes differ and might be causing a problem. Mine is:
java version "1.7.0_10" Java(TM) SE Runtime Environment (build
1.7.0_10-b18) Java HotSpot(TM) 64-Bit Server VM (build 23.6-b04, mixed mode)
UPDATE 2:
As per your comment on your java version:
JDK 6, NetBeans 6.5.1
Have you tried:
final ArrayList<String> chars = new ArrayList<String>();
final ArrayList<Integer> charsTiming = new ArrayList<Integer>();
note i dont use <> anymore as Java 6 does not support the Diamond operator it would have to have the data type included i.e <Integer>.

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