doc = (StyledDocument) textPane.getDocument();
err = textPaneError.getStyledDocument();
try {
textPane.setText("\b");
doc.insertString(textPane.getCaretPosition(), (String) stack.pop(), styleT);
doc.insertString(textPane.getCaretPosition()-1, "\n", styleB);
} catch (BadLocationException e1) {
try {
err.insertString(0, "There is no opened tag", styleR);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
I am trying to print all the exception in a JTextPane. This is my code, it doesn't work. Can somebody told me where is the problem?
Thanks
package printexception;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
public class PrintException extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new PrintException().setVisible(true); }
}
);
}
private final JTextPane text = new JTextPane();
public PrintException() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(400, 300);
initComponents();
}
private void initComponents() {
JToolBar toolbar = new JToolBar();
toolbar.add(new CreateException());
getContentPane().add(toolbar, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(text));
}
private class CreateException extends AbstractAction {
CreateException() {
putValue(NAME, "Print Exception");
}
#Override
public void actionPerformed(ActionEvent evt) {
Exception ex = new Exception();
AttributeSet attr = null;
StyledDocument doc = text.getStyledDocument();
for (StackTraceElement trace : ex.getStackTrace()) {
try {
doc.insertString(doc.getLength(), trace.toString() + '\n', attr);
} catch (BadLocationException ex1) {
ex1.printStackTrace();
}
}
}
}
}
Related
What else can be optimized how to use JTextField default text prompt function
Thank you all for your answers
=============================================================================
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;[enter image description here][1]
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
class WindowActionEvent extends JFrame {
JTextField text;
JTextArea textShow;
JButton button;
ReaderListen listener;
public WindowActionEvent() throws HeadlessException {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
setLayout(new FlowLayout());
text = new JTextField(10);
button = new JButton("读取");
textShow = new JTextArea(25,50);
textShow.setEditable(false);
listener = new ReaderListen();
listener.setJTextField(text);
listener.setJTextArea(textShow);
text.addActionListener(listener);
button.addActionListener(listener);
add(text);
add(button);
add(new JScrollPane(textShow));
}
}
class ReaderListen implements ActionListener {
JTextField text;
JTextArea textShow;
public void setJTextField(JTextField text) {
this.text = text;
}
public void setJTextArea(JTextArea textShow) {
this.textShow = textShow;
}
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File(text.getText()); //getDocument()
FileReader inOne = new FileReader(file);
BufferedReader inTwo = new BufferedReader(inOne);
String s = null;
while ((s = inTwo.readLine()) != null) {
textShow.append(s+"\n");
}
inOne.close();
inTwo.close();
} catch (Throwable e2) {
e2.printStackTrace();
}
}
}
public class Matematiktest extends WindowActionEvent {
public static void main(String[] args) {
WindowActionEvent win = new WindowActionEvent();
win.setBounds(100,100,1000,500);
win.setTitle("处理ActionEvent事件");
}
}
This is the code I checked about the default text prompt function of JTextField but I don’t know where it should be placed or used
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class JTextFieldHintListener implements FocusListener {
private String hintText;
private JTextField textField;
public JTextFieldHintListener(JTextField jTextField,String hintText) {
this.textField = jTextField;
this.hintText = hintText;
jTextField.setText(hintText); //默认直接显示
jTextField.setForeground(Color.GRAY);
}
#Override
public void focusGained(FocusEvent e) {
//获取焦点时,清空提示内容
String temp = textField.getText();
if(temp.equals(hintText)) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
}
#Override
public void focusLost(FocusEvent e) {
//失去焦点时,没有输入内容,显示提示内容
String temp = textField.getText();
if(temp.equals("")) {
textField.setForeground(Color.GRAY);
textField.setText(hintText);
}
}
}
I am trying to get a progress bar to accurately reflect my SwingWorker. But I really can't figure out how to do it. I got the bar to just do a static animation until the operation has completed but I want a real active bar.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package frglauncher;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
/**
*
* #author KYLE-LAPTOP
*/
class DownloadWorker extends SwingWorker<String, Object> {
private String game;
private JProgressBar bar;
private JLabel label;
public DownloadWorker(JProgressBar bar, String game, JLabel label) {
this.game = game;
this.bar = bar;
this.label = label;
}
#Override
public String doInBackground() {
// Download here
label.setText("test");
try {
// ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
String URL_LOCATION = "http://www.futureretrogaming.tk/gamefiles/ProfessorPhys.jar";
String LOCAL_FILE = ("\\" + game + "\\");
File localfile = new File(LOCAL_FILE);
if (localfile.exists()) {
System.out.println("Directory exists!");
}
else {
System.out.println("Directory doesn't exist! Creating...");
localfile.mkdir();
if (localfile.exists()) {
System.out.println("Directory created!");
}
}
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE + "\\ProfessorPhys.jar\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
RandomAccessFile randomAccessFile = null;
File file = new File(LOCAL_FILE + "ProfessorPhys.jar\\");
JarFile jar = new JarFile(file);
Enumeration enum1 = jar.entries();
while (enum1.hasMoreElements()) {
JarEntry file1 = (JarEntry) enum1.nextElement();
System.out.println("Directory to extract: " + LOCAL_FILE);
System.out.println("\n" + file1.getName() + "\n");
File f = new File(file1.getName());
if (file1.isDirectory()) { // If it's a directory, create it
f.mkdir();
continue;
}
try (InputStream is1 = jar.getInputStream(file1)) {
FileOutputStream fos1 = new FileOutputStream(f);
while (is1.available() > 0) { // Write contents of 'is' to 'fos'
fos1.write(is1.read());
}
fos1.close();
}
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(DownloadWorker.class.getName()).log(Level.SEVERE, null, ex);
}
catch (MalformedURLException ex) {
Logger.getLogger(DownloadWorker.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(DownloadWorker.class.getName()).log(Level.SEVERE, null, ex);
}
return "done";
}
#Override
protected void done() {
// Done
label.setText("Download of " + game + "is done.");
System.exit(0);
}
}
Several things:
There are four rules to follow with SwingWorker. You can refer to this diagram: .
So, this code:
#Override
public String doInBackground() {
//download here
label.setText("test");
violates that rule. Your label.setText() should be moved to the constructor.
To send "updates" to Swing components (like your progress bar) you want to use the process() method, which you invoke using publish() from inside your doInBackground(). Your second SwingWorker parameter reflects the type of value you want to pass. I've attached two SSCCEs. One passes an Integer to the process() method, the other passes a String. Should give you an idea of what's going on.
SSCCE using Integer:
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
/**
*
* #author Ryan
*/
public class Test {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
go();
}
});
}
public static void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel("Loading...");
JProgressBar jpb = new JProgressBar();
jpb.setIndeterminate(false);
int max = 1000;
jpb.setMaximum(max);
panel.add(label);
panel.add(jpb);
frame.add(panel);
frame.pack();
frame.setSize(200,90);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Task_IntegerUpdate(jpb, max, label).execute();
}
static class Task_IntegerUpdate extends SwingWorker<Void, Integer> {
JProgressBar jpb;
int max;
JLabel label;
public Task_IntegerUpdate(JProgressBar jpb, int max, JLabel label) {
this.jpb = jpb;
this.max = max;
this.label = label;
}
#Override
protected void process(List<Integer> chunks) {
int i = chunks.get(chunks.size()-1);
jpb.setValue(i); // The last value in this array is all we care about.
System.out.println(i);
label.setText("Loading " + i + " of " + max);
}
#Override
protected Void doInBackground() throws Exception {
for(int i = 0; i < max; i++) {
Thread.sleep(10); // Illustrating long-running code.
publish(i);
}
return null;
}
#Override
protected void done() {
try {
get();
JOptionPane.showMessageDialog(jpb.getParent(), "Success", "Success", JOptionPane.INFORMATION_MESSAGE);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
SSCCE using String:
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
/**
*
* #author Ryan
*/
public class Test2 {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
go();
}
});
}
public static void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel("Loading...");
JProgressBar jpb = new JProgressBar();
jpb.setIndeterminate(true);
panel.add(label);
panel.add(jpb);
frame.add(panel);
frame.pack();
frame.setSize(200,90);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Task_StringUpdate(label).execute();
}
static class Task_StringUpdate extends SwingWorker<Void, String> {
JLabel jlabel;
public Task_StringUpdate(JLabel jlabel) {
this.jlabel = jlabel;
}
#Override
protected void process(List<String> chunks) {
jlabel.setText(chunks.get(chunks.size()-1)); // The last value in this array is all we care about.
System.out.println(chunks.get(chunks.size()-1));
}
#Override
protected Void doInBackground() throws Exception {
publish("Loading Step 1...");
Thread.sleep(1000);
publish("Loading Step 2...");
Thread.sleep(1000);
publish("Loading Step 3...");
Thread.sleep(1000);
publish("Loading Step 4...");
Thread.sleep(1000);
return null;
}
#Override
protected void done() {
try {
get();
JOptionPane.showMessageDialog(jlabel.getParent(), "Success", "Success", JOptionPane.INFORMATION_MESSAGE);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
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) {
}
}
}
I want to get the event like crtl+c or right click copy in windows , that could do the event to java application running ,
that means if someone copies some text , that should be pasted into the java application textarea...
i have made the java application and it can accept arguments through main method.
but how to trigger event from windows to java..
The simplest way is to monitor changes to the Toolkit.getSystemClipboard
There are two ways to do this. You can monitor changes to the DataFlavour, but this will only help if the data flavor changes, not the content and/or you could monitor the contents of the clipboard and update your view when it's content changes...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ClipboardMonitor {
public static void main(String[] args) {
new ClipboardMonitor();
}
public ClipboardMonitor() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
public TestPane() {
textArea = new JTextArea(10, 10);
setLayout(new BorderLayout());
add(new JScrollPane(textArea));
Toolkit.getDefaultToolkit().getSystemClipboard().addFlavorListener(new FlavorListener() {
#Override
public void flavorsChanged(FlavorEvent e) {
setText(getClipboardContents());
}
});
Thread t = new Thread(new ContentsMonitor());
t.setDaemon(true);
t.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected String getClipboardContents() {
String text = null;
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
try {
Transferable contents = clipboard.getContents(TestPane.this);
text = (String) contents.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException ex) {
ex.printStackTrace();
}
}
return text;
}
protected void setText(final String text) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
textArea.setText(text);
}
});
}
public class ContentsMonitor implements Runnable {
#Override
public void run() {
String previous = getClipboardContents();
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
String text = getClipboardContents();
if (text != null && !text.equals(previous)) {
setText(text);
previous = text;
}
}
}
}
}
}
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?