From jtextpane to jeditorpane

I'd like to create a complete text editor so, i made these two code, but the first it's based on jtextpane and the second on a jeditorpane. I want to link toghether the second with the firt code , to have a cpmplete text editor. The problem is that i don't know how to do this. The fisrt think i thought to do was transform the jtext in the fisrt code in a jeditor but jeditor don't recognize the function 'append' .. Could someone help me? Thanks
* To change this template, choose Tools | Templates
* and open the template in the editor.
package GUI;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
* @author Elena
public class Form extends javax.swing.JFrame {
String ClipboardData = "";
private Object CurrentFileDirectory;
* Creates new form Form
public Form() {
initComponents();
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
editorpane = new javax.swing.JEditorPane();
jMenuBar1 = new javax.swing.JMenuBar();
Open = new javax.swing.JMenu();
New = new javax.swing.JMenuItem();
Openfile = new javax.swing.JMenuItem();
Save = new javax.swing.JMenuItem();
SaveAs = new javax.swing.JMenuItem();
Exit = new javax.swing.JMenuItem();
Cut = new javax.swing.JMenu();
jMenuItem6 = new javax.swing.JMenuItem();
Copy = new javax.swing.JMenuItem();
Paste = new javax.swing.JMenuItem();
Delete = new javax.swing.JMenuItem();
SelectAll = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Java Text Editor");
jScrollPane2.setViewportView(editorpane);
Open.setText("File");
New.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
New.setText("New");
New.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NewActionPerformed(evt);
Open.add(New);
Openfile.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
Openfile.setText("Open...");
Openfile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenfileActionPerformed(evt);
Open.add(Openfile);
Save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
Save.setText("Save");
Save.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveActionPerformed(evt);
Open.add(Save);
SaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
SaveAs.setText("Save As...");
SaveAs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveAsActionPerformed(evt);
Open.add(SaveAs);
Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_0, java.awt.event.InputEvent.CTRL_MASK));
Exit.setText("Exit");
Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitActionPerformed(evt);
Open.add(Exit);
jMenuBar1.add(Open);
Cut.setText("Edit");
jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem6.setText("Cut");
jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem6ActionPerformed(evt);
Cut.add(jMenuItem6);
Copy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
Copy.setText("Copy");
Copy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CopyActionPerformed(evt);
Cut.add(Copy);
Paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
Paste.setText("Paste");
Paste.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PasteActionPerformed(evt);
Cut.add(Paste);
Delete.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
Delete.setText("Delete");
Delete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DeleteActionPerformed(evt);
Cut.add(Delete);
SelectAll.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
SelectAll.setText("Select All");
SelectAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SelectAllActionPerformed(evt);
Cut.add(SelectAll);
jMenuBar1.add(Cut);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
pack();
}// </editor-fold>
private void NewActionPerformed(java.awt.event.ActionEvent evt) {                                   
editorpane.setText("");
private void ExitActionPerformed(java.awt.event.ActionEvent evt) {                                    
System.exit(0);
private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {                                      
editorpane.replaceSelection("");
private void SaveAsActionPerformed(java.awt.event.ActionEvent evt) {                                      
JFileChooser sdChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX File", "txt");
sdChooser.setFileFilter(filter);
int returnVal = sdChooser.showSaveDialog(null);
try{
if(returnVal == JFileChooser.APPROVE_OPTION){
File directory = sdChooser.getCurrentDirectory();
String path = directory.getAbsolutePath();
String fileName = sdChooser.getSelectedFile().getName();
if(fileName.contains(".docx")){
}else{
fileName = fileName + ".docx";
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
bw.write(editorpane.getText());
bw.close();
} catch(IOException e){
JOptionPane.showMessageDialog(null, "ERROR!");
private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {                                          
ClipboardData = editorpane.getSelectedText();
StringSelection stringSelection = new StringSelection(ClipboardData);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
editorpane.replaceSelection("");
private void CopyActionPerformed(java.awt.event.ActionEvent evt) {                                    
ClipboardData = editorpane.getSelectedText();
StringSelection stringSelection = new StringSelection(ClipboardData);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
private void PasteActionPerformed(java.awt.event.ActionEvent evt) {                                     
editorpane.append(ClipboardData);
private void SelectAllActionPerformed(java.awt.event.ActionEvent evt) {                                         
editorpane.selectAll();
private void OpenfileActionPerformed(java.awt.event.ActionEvent evt) {                                        
JFileChooser opChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
opChooser.setFileFilter(filter);
int returnval = opChooser.showOpenDialog(null);
File chosenFile = opChooser.getSelectedFile();
try {
if(returnval == JFileChooser.APPROVE_OPTION){
BufferedReader br = new BufferedReader(new FileReader(chosenFile));
editorpane.setText("");
String data;
while((data = br.readLine()) != null) {
editorpane.append(data + "\n");}
br.close();
}catch(IOException e){
JOptionPane.showMessageDialog(null, "ERROR!" );
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {                                    
if("".equals(CurrentFileDirectory)){
JFileChooser sdChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
sdChooser.setFileFilter(filter);
int returnval = sdChooser.showOpenDialog(null);
try{
if(returnval == JFileChooser.APPROVE_OPTION){
File directory = sdChooser.getCurrentDirectory();
String path = directory.getAbsolutePath();
String fileName = sdChooser.getSelectedFile().getName();
if(fileName.contains(".docx")){
}else{
fileName = fileName + ".docx";
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
bw.write(editorpane.getText());
bw.close();}
}catch(IOException e){     
JOptionPane.showMessageDialog(null, "ERROR!");
* @param args the command line arguments
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Form().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JMenuItem Copy;
private javax.swing.JMenu Cut;
private javax.swing.JMenuItem Delete;
private javax.swing.JMenuItem Exit;
private javax.swing.JMenuItem New;
private javax.swing.JMenu Open;
private javax.swing.JMenuItem Openfile;
private javax.swing.JMenuItem Paste;
private javax.swing.JMenuItem Save;
private javax.swing.JMenuItem SaveAs;
private javax.swing.JMenuItem SelectAll;
private javax.swing.JEditorPane editorpane;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
public class Colore {
public Colore() {
JFrame frame = new JFrame();
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
JPanel north = new JPanel();
JMenuBar menu = new JMenuBar();
JMenu styleMenu = new JMenu();
styleMenu.setText("Style");
Action boldAction = new BoldAction();
boldAction.putValue(Action.NAME, "Bold");
styleMenu.add(boldAction);
Action italicAction = new ItalicAction();
italicAction.putValue(Action.NAME, "Italic");
styleMenu.add(italicAction);
Action foregroundAction = new ForegroundAction();
foregroundAction.putValue(Action.NAME, "Color");
styleMenu.add(foregroundAction);
Action formatTextAction = new FontAndSizeAction();
formatTextAction.putValue(Action.NAME, "Font and Size");
styleMenu.add(formatTextAction);
menu.add(styleMenu);
north.add(menu);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(north, BorderLayout.NORTH);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(800, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
public static void main(String[] args) {
new Culo();
class BoldAction extends StyledEditorKit.StyledTextAction {
private static final long serialVersionUID = 9174670038684056758L;
public BoldAction() {
super("font-bold");
public String toString() {
return "Bold";
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
StyledEditorKit kit = getStyledEditorKit(editor);
MutableAttributeSet attr = kit.getInputAttributes();
boolean bold = (StyleConstants.isBold(attr)) ? false : true;
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setBold(sas, bold);
setCharacterAttributes(editor, sas, false);
class ItalicAction extends StyledEditorKit.StyledTextAction {
private static final long serialVersionUID = -1428340091100055456L;
public ItalicAction() {
super("font-italic");
public String toString() {
return "Italic";
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
StyledEditorKit kit = getStyledEditorKit(editor);
MutableAttributeSet attr = kit.getInputAttributes();
boolean italic = (StyleConstants.isItalic(attr)) ? false : true;
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setItalic(sas, italic);
setCharacterAttributes(editor, sas, false);
class ForegroundAction extends StyledEditorKit.StyledTextAction {
private static final long serialVersionUID = 6384632651737400352L;
JColorChooser colorChooser = new JColorChooser();
JDialog dialog = new JDialog();
boolean noChange = false;
boolean cancelled = false;
public ForegroundAction() {
super("foreground");
public void actionPerformed(ActionEvent e) {
JTextPane editor = (JTextPane) getEditor(e);
if (editor == null) {
JOptionPane.showMessageDialog(null,
"You need to select the editor pane before you can change the color.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
int p0 = editor.getSelectionStart();
StyledDocument doc = getStyledDocument(editor);
Element paragraph = doc.getCharacterElement(p0);
AttributeSet as = paragraph.getAttributes();
fg = StyleConstants.getForeground(as);
if (fg == null) {
fg = Color.BLACK;
colorChooser.setColor(fg);
JButton accept = new JButton("OK");
accept.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
fg = colorChooser.getColor();
dialog.dispose();
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cancelled = true;
dialog.dispose();
JButton none = new JButton("None");
none.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
noChange = true;
dialog.dispose();
JPanel buttons = new JPanel();
buttons.add(accept);
buttons.add(none);
buttons.add(cancel);
dialog.getContentPane().setLayout(new BorderLayout());
dialog.getContentPane().add(colorChooser, BorderLayout.CENTER);
dialog.getContentPane().add(buttons, BorderLayout.SOUTH);
dialog.setModal(true);
dialog.pack();
dialog.setVisible(true);
if (!cancelled) {
MutableAttributeSet attr = null;
if (editor != null) {
if (fg != null && !noChange) {
attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, fg);
setCharacterAttributes(editor, attr, false);
}// end if color != null
noChange = false;
cancelled = false;
private Color fg;
class FontAndSizeAction extends StyledEditorKit.StyledTextAction {
private static final long serialVersionUID = 584531387732416339L;
private String family;
private float fontSize;
JDialog formatText;
private boolean accept = false;
JComboBox fontFamilyChooser;
JComboBox fontSizeChooser;
public FontAndSizeAction() {
super("Font and Size");
public String toString() {
return "Font and Size";
public void actionPerformed(ActionEvent e) {
JTextPane editor = (JTextPane) getEditor(e);
int p0 = editor.getSelectionStart();
StyledDocument doc = getStyledDocument(editor);
Element paragraph = doc.getCharacterElement(p0);
AttributeSet as = paragraph.getAttributes();
family = StyleConstants.getFontFamily(as);
fontSize = StyleConstants.getFontSize(as);
formatText = new JDialog(new JFrame(), "Font and Size", true);
formatText.getContentPane().setLayout(new BorderLayout());
JPanel choosers = new JPanel();
choosers.setLayout(new GridLayout(2, 1));
JPanel fontFamilyPanel = new JPanel();
fontFamilyPanel.add(new JLabel("Font"));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = ge.getAvailableFontFamilyNames();
fontFamilyChooser = new JComboBox();
for (int i = 0; i < fontNames.length; i++) {
fontFamilyChooser.addItem(fontNames);
fontFamilyChooser.setSelectedItem(family);
fontFamilyPanel.add(fontFamilyChooser);
choosers.add(fontFamilyPanel);
JPanel fontSizePanel = new JPanel();
fontSizePanel.add(new JLabel("Size"));
fontSizeChooser = new JComboBox();
fontSizeChooser.setEditable(true);
fontSizeChooser.addItem(new Float(4));
fontSizeChooser.addItem(new Float(8));
fontSizeChooser.addItem(new Float(12));
fontSizeChooser.addItem(new Float(16));
fontSizeChooser.addItem(new Float(20));
fontSizeChooser.addItem(new Float(24));
fontSizeChooser.setSelectedItem(new Float(fontSize));
fontSizePanel.add(fontSizeChooser);
choosers.add(fontSizePanel);
JButton ok = new JButton("OK");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
accept = true;
formatText.dispose();
family = (String) fontFamilyChooser.getSelectedItem();
fontSize = Float.parseFloat(fontSizeChooser.getSelectedItem().toString());
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
formatText.dispose();
JPanel buttons = new JPanel();
buttons.add(ok);
buttons.add(cancel);
formatText.getContentPane().add(choosers, BorderLayout.CENTER);
formatText.getContentPane().add(buttons, BorderLayout.SOUTH);
formatText.pack();
formatText.setVisible(true);
MutableAttributeSet attr = null;
if (editor != null && accept) {
attr = new SimpleAttributeSet();
StyleConstants.setFontFamily(attr, family);
StyleConstants.setFontSize(attr, (int) fontSize);
setCharacterAttributes(editor, attr, false);

Sorry. My problem is that I want to insert HTML inside the body tag of an HTML page, and I don't know any simple method to get a reference to the <body> element from the JEditorPane widget, I get a reference to the actual HTML document but I can't get a reference of a tag from HTMLDocument either. Thanks.
Juanjo

Similar Messages

  • How to get string from jtextpane along with its attributes

    sir,
    How to get string from jtextpane along with its attributes
    i,e font,size,style,color etc.
    please help me out.
    my mail id is [email protected]

    JTextPane extends JTextComponent
    JTextComponent.getDocument()
    a Document is a set of Element, see Document.getRootElements(). Each Element has attributes, stored within an AttributSet object see Element.getAttributes()
    a Document can also be rendered as a String, see Document.getText( offest, length ), use it with 0 and Document.getLength() as parameters.

  • Send message from jtextpane

    how send message from jtextpane.
    iam using com.jscape.inet.smtp for send message through textarea. In text area i take string and assign to string using gettext().
    In case if textpane how to set body content to variable.

    Hi raja8nz,
    JTextPane extends JTextComponent, and JTextComponent provides the getText() method. So can't you just use getText()?
    -Yeath
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame implements ActionListener
       private JTextPane jtp;
       public Test()
          super( "My Test" );
          this.getContentPane().setLayout( new BorderLayout() );
          this.jtp = new JTextPane();
          JButton jb = new JButton( "Click" );
          jb.addActionListener( this );
          this.getContentPane().add( this.jtp, BorderLayout.CENTER );
          this.getContentPane().add( jb, BorderLayout.SOUTH );
       public void actionPerformed( ActionEvent e )
          System.out.println( this.jtp.getText() );
       public static void main( String[] args )
          Test test = new Test();
          test.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          test.setSize( 400, 400 );
          test.setVisible( true );
    }

  • Can i copy copy TEXT with Tag contents from JtextPane

    Hello,
    I want to copy text from jtextpane with Tag contents. I use jtextpane for displaying HTML page. If it is posibile please make a response and how it should be?

    Hi User,
    Please follow the below link:
    http://www.rittmanmead.com/2008/04/migration-obiee-projects-between-dev-and-prod-environments/
    Basically just to give you a heads up, you copy paste the RPD and webcatalog file from your dev instance to same locations in prod instance.
    Award points if your question is answered.
    Thanks,
    -Amith.

  • JMenuBar, losing focus from JTextPane or other components

    Hello,
    I implment JMenuItems for copying, cuting and pasting text from one JTextPane into another JTextPane.
    The problem is that when I click on the JMenuBar-->JMenuItem, the focus from JTextPane is lost. It works fine if I use JButton on a JToolBar.
    The code below is my paste() method that does not work.
    public void paste() {
            if (sourceWindowTextPane.isFocusOwner()) {
                sourceWindowTextPane.paste();
            } else if (targetWindowTextPane.isFocusOwner()) {
                targetWindowTextPane.paste();
        }What do I need to do?

    Thank you very much, uncle_alice.
    I found a weird solution. I get the name of the current focus owner first, and then I compare the returned name with
    names of my JTextPanes. The working code is shown below.
       String focusOwnerName=this.getContext().getFocusOwner().getName();
            if (focusOwnerName.equalsIgnoreCase("sourceWindowTextPane")) {
                sourceWindowTextPane.paste();
            } else if (focusOwnerName.equalsIgnoreCase("targetWindowTextPane")) {
                targetWindowTextPane.paste();
            }However,
    although I know the the focus owner's name is "sourceWindowTextPane" from this.getContext().getFocusOwner().getName(),
    I still get false when I use sourceWindowTextPane.isFocusOwner(). For example,
       String focusOwnerName=this.getContext().getFocusOwner().getName();//-->for instance, focusOwnerName is "sourceWindowTextPane".
       if(sourceWindowTextPane.isFocusOwner()){
             System.out.println("True");
      } else{
              System.out.println("False");
    I get "False" from the code above.
    Does anyone have any idea?

  • Problem to display Animated Gif from HTML into JEditorPane

    I have a problem displaying animated gif that comes from URL (HTML) into JEditorPane.
    Let me show you the source I have:
    * @author Dobromir Gospodinov
    * @version 1.0
    * Date: Dec 6, 2002
    * Time: 6:47:53 PM
    package test.advertserver;
    import javax.swing.*;
    import java.awt.*;
    import java.io.IOException;
    public class Test {
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JEditorPane ed = new JEditorPane();
              try {
                   ed.setPage("http://localhost:8200/servlet?key=value");
              } catch (IOException e) {
                   e.printStackTrace();
              JPanel panel = new JPanel();
              panel.setPreferredSize(new Dimension(500, 500));
              panel.add(ed);
              frame.getContentPane().add(panel);
              frame.pack();
              frame.setVisible(true);
    }Part of the returned from servlet HTML includes an img tag:
    <img src="/images/MyAnimatedGif.gif" alt="animated gif comment" width="480" height="50"  border="0">Let us assume that MyAnimatedGif.gif has 10 frames and gif is looped - when the 10th is dipslayed it has to display the 1st and so on.
    JEditorPane displays frames from 1 to 10 correctly but does not start from the first again. Instead JEditorPane displays a broken image.
    I locate where the problem arise:
    JEditorPane has an HTMLEditorKit that creates javax.swing.text.html.ImageView instance for every IMG tag.
    And here is the problem:
    ImageView has an ImageObserver necessary for the asynchronous image download. ImageObserver has the imageUpdate method. But this imageUpdate method is never called with ALLBITS flag raised up. Instead, after the last frame of MyAnimatedGif.gif is downloaded the imageUpdate method is called with flag ERROR raised up. Obviously this is a bug of Sun's implementation. Finaly the flag ALLBITS has to be received for normal end of image observing. But ALLBITS flag does not come.
    So, can anybody help me how to load an animated gif within JEditorPane completely.
    Thank You in advance,
    Dobromir Gospodinov
    P.S. If somebody of you wants to debbug what happens within ImageView will have to implement it (and related classes too, because of the limited package visability) borrowing the source from Sun's ImageView.

    I'm also having this problem with java 1.4.1 I discovered that some animated gifs work fine, while others stop animating. Running with java 1.3.1 fixed the problem. I'm going to report this as a bug
    Here's my code:
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    public class AnimatedGifTester
    extends JFrame
    public static void main(String argv[])
    throws Exception
    new AnimatedGifTester();
    public AnimatedGifTester()
    throws Exception
    String[] images = new String[] {
    "http://www.gif.com/ImageGallery/Animated/Animals/Photographic/dog_running.gif",
    "http://www.gif.com/ImageGallery/Animated/Characters/Cartoon/java.gif",
    "http://www.webdeveloper.com/animations/bnifiles/anielg.gif",
    "http://www.webdeveloper.com/animations/bnifiles/cat2.gif",
    "http://images.animfactory.com/animations/animals/fish/big_fish_swimming_md_wht.gif",
    "http://www.webgenies.co.uk/images/martian.gif",
    "http://www.webdeveloper.com/animations/bnifiles/at_sign_rotating.gif",
    "http://www.webdeveloper.com/animations/bnifiles/arrow_1.gif",
    "http://www.gif.com/ImageGallery/Animated/Characters/Cartoon/javaacro.gif",
    "http://java.sun.com/products/java-media/2D/samples/suite/Image/duke.running.gif",
    "http://www.gif.com/ImageGallery/Animated/SouthPark/Cartoon/stan.gif"
    StringBuffer buffer = new StringBuffer("<html><body>");
    for (int idx = 0; idx < images.length; idx++)
    buffer.append("<img src='" + images[idx] + "'>");
    buffer.append("</body></html>");
    String html = buffer.toString();
    // save a copy of the html to open in a browser so we can see what it's
    // supposed to look like
    BufferedWriter writer = new BufferedWriter(new FileWriter("animatedGifTest.html"));
    writer.write(html);
    writer.close();
    JEditorPane editorPane = new JEditorPane("text/html", html);
    editorPane.setEditable(false);
    getContentPane().add(editorPane);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(new Dimension(400, 600));
    show();

  • p tags with attributes not removed from JTextPane

    We are using HTMLEditorKit with JtextPane to create a HTML Document Editor, for our project. [JDK 1.3.1.]
    When we have a simple <p> tag for paragraph in HTML and we start deleting things from end of the document, it works fine. But when we have a <P> tag with attributes like <p align='CENTER'> the delete key deletes the characters but the cursor remains in the line below and doesnot move up as the characters of above para get deleted. The HTML also retains the <p align='CENTER'> tag, which should have been removed. It seems its not able to identify <p> tags with attributes as Html para tags, and so not deleting it.
    How do we solve this without migrating to jdk1.4 ? Please help.

    Usually attributes such as 'align=center' are deleted along with a tag, regardless of whether it is a p tag or another one. But you would have to carefully test what exactly gets deleted because attributes are not only stored with paragraphs. They can exist for single characters and as well come from a style sheet.
    The best is to generate a dump of your document before and after deletion.
    You can use something like the below code (it is not optimized at all and thus could be implemented better but it works) to produce a dump
      public void listElements(Element elem, int indent) {
        int i;
        String is = getIndent(indent);
        String elemName = elem.getName();
        Document elemDoc = elem.getDocument();
        String cont = "";
        String theText = "";
        System.out.println(is + "--start-----");
        System.out.println(is + "Element Name:" + elemName);
        if(elemName.equals(new String("content"))) {
          try {
            theText = elemDoc.getText(
                    elem.getStartOffset(),
                    elem.getEndOffset() - elem.getStartOffset());
            System.out.println(is + "Content: " + theText);
            if(theText.indexOf("\r") > -1) {
              System.out.println(is + " plus \\r");
            if(theText.indexOf("\n") > -1) {
              System.out.println(is + " plus \\n");
          catch (Exception e) {
        listAttributes(elem, indent);
        if(!elem.isLeaf()) {
          for(i=0;i<elem.getElementCount();i++) {
            listElements(elem.getElement(i),indent+2);
        System.out.println(is + "---end----");
      public void listAttributes(Element elem, int indent) {
        Object key;
        String attr;
        String attrName;
        int pos;
        String is = getIndent(indent);
        AttributeSet as = elem.getAttributes();
        Enumeration an = as.getAttributeNames();
        try {
          while(an.hasMoreElements()) {
            key = an.nextElement();
            attrName = key.toString();
            attr = as.getAttribute(key).toString();
            System.out.println(is + "Attribute Name: " +
                      attrName + " Attribute Content: " + attr);
            if(attr.indexOf("\r") > -1) {
              System.out.println(is + " plus \\r");
            if(attr.indexOf("\n") > -1) {
              System.out.println(is + " plus \\n");
        catch (Exception e) {
          e.printStackTrace();
      }Hope that helps
    Ulrich

  • Image, from JTextPane to RTF

    Hi, i need to convert the text in a JTextPane in a file .RTF, but there is the problem, the image in TextPane there are not in a file RTF, why?
    Thanks for help goodbye
    PS sorry for my language

    Since you don't have a text plan it will cost 25  cents to send  your picture from you online album, just follow these directions.
    Good Luck
     Click  HERE to send a text message from Verizon's web site. When you send the text message from the site it will not go towards your messaging plan. It's free on your end. The person receiving the message will be billed for each text. Not sure about the replying back.https://text.vzw.com/customer_site/jsp/messaging_lo.jsp?lid=//global//messaging//text+messaging//send+message

  • Printing document from JTextPane???

    Surely it can't be that difficult, but I've tried everything, copied code from http://www.manning.com/Robinson/chapter22.pdf, nothing seems to work. I've finally got to a stage where I can print a blank page, but that's not quite what I'm after.
    Any clues, hints?
    My source:
    =======================================
    ** Class extends JTextPane,
    public void initialize() {
         // this method called from the constructor
         setName("JTextPane1");
         setBounds(0, 0, 6, 22);
         // user code begin {1}
         try {
         String s = "file:"
                             + "C:\\Esd\\Docs" // System.getProperty("user.dir")
                             + System.getProperty("file.separator")
                             + "PrintInvoice.html";
         java.net.URL printInvoiceURL = new java.net.URL(s);
              javax.swing.text.html.HTMLEditorKit htmlKit =
                   new javax.swing.text.html.HTMLEditorKit();
              setEditorKit(htmlKit);
                   /* ... use the URL to initialize the editor pane ... */
              setPage(printInvoiceURL);
              setEditable(false);
              // user code end
         } catch (java.lang.Throwable ivjExc) {
              // user code begin {2}
              // user code end
              handleException(ivjExc);
    public int print(java.awt.Graphics pg, PageFormat pageFormat, int pageIndex)
         throws PrinterException {
    //     PrintView m_printView =null;
         pg.translate((int)pageFormat.getImageableX(),     
              (int)pageFormat.getImageableY());
         int wPage = (int)pageFormat.getImageableWidth();
         int hPage = (int)pageFormat.getImageableHeight();
         pg.setClip(0,0,wPage,hPage);
         // do this once per print
         if (m_printView == null) {
              BasicTextUI btui = (BasicTextUI)this.getUI();
              View root = btui.getRootView(this);
              System.out.println("root element: " + this.getDocument().getDefaultRootElement());
              System.out.println("root: " + root);
              System.out.println("wPage, hPage : " + wPage + ", " + hPage);
              m_printView = new PrintView(this.getDocument().getDefaultRootElement(),
                   root, wPage, hPage);
         boolean bContinue = m_printView.paintPage(pg, hPage, pageIndex);
         System.gc();
         if (bContinue)
              return PAGE_EXISTS;
         else {
              m_printView = null;
              return NO_SUCH_PAGE;
    *** class PrintView extends BoxView has method paintPage
    public boolean paintPage(Graphics g, int hPage, int pageIndex) {
         if (pageIndex > m_pageIndex) {
              m_firstOnPage = m_lastOnPage + 1;
              if (m_firstOnPage >= getViewCount())
                   return true;//               return false;
              m_pageIndex = pageIndex;
         int yMin = getOffset(Y_AXIS, m_firstOnPage);
         int yMax = yMin + hPage;
         Rectangle rc = new Rectangle();
         for (int k = m_firstOnPage; k < getViewCount(); k++) {
              rc.x = getOffset(X_AXIS, k);
              rc.y = getOffset(Y_AXIS, k);
              rc.width = getSpan(X_AXIS, k);
              rc.height = getSpan(Y_AXIS, k);
              if (rc.y+rc.height > yMax)
                   break;
              m_lastOnPage = k;
              rc.y -= yMin;
              if (k == 1)
              ; // if I call paintChild here I get null reference exception
              else
                        paintChild(g, rc, k);
         return true;
    *** Dialog window that tries to print the JTextPane:
    public void jButtonPrint_ActionPerformed(java.awt.event.ActionEvent actionEvent) {
    Thread runner = new Thread () {
         public void run() {
    //          new PrintView (PrintInvoiceDialog.this.getJTextPane1().getDocument().getDefaultRootElement(), 1);
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(getJTextPane1());
    if (printJob.printDialog()) {
    try {
    printJob.print();
    } catch (Exception ex) {
    ex.printStackTrace();
    runner.start();
    public PrintInvoiceTextPane getJTextPane1() {
         if (ivjJEditorPane1 == null)
              ivjJEditorPane1 = new PrintInvoiceTextPane ();
    return ivjJEditorPane1 ;

    I have exerienced the same problem and in my seaching i found this
    http://developer.java.sun.com/developer/onlineTraining/Programming/JDCBook/render.html#what
    It helped me greatly =)
    Hope that helps

  • To send smiley icons from jtextpane

    hello friends,
    I am in a confusion that how we can send smileys from one jtextpane.now i can only send the text but the smiley cannot.what i can do? any one know the solution please give me the solution ,if have source that explain show me i am very thankful so i need this very urgently.i hope that you will help me.thanks in advance

    I meant, have you tried just typying out the smileys? Originally, they were just punctuation. Many phones will now translate that into a picture. A basic smiley is a colon, dash, close parentheses, for example :-)
    mrksh wrote:
    But what fu is this
    I don't understand what this sentence means.

  • Transfering th focus from JTextPane to JList

    i have a JTextPane whith a JMenuBar With JMenuItem on pressing this menu
    item a JList with a JScrollPane appears i want to transfer the Focus from the JTextPane to the JList i tried the method setFocusable() but it doesn't work Any ready code is welcome and rewardable thank you.

    Hi,
    what u will have to do is? U will have to put a key listener for the JTextArea. U will have to use the KeyEvent, and check if KeyEvent.VK_TAB, then set the focus on the component wherever u need.
    Regards,
    Balaji.SN

  • Problem while reading JTable from JTextPane

    Hi,
    I am facing a bizarre problem. My JTextPane can contain rich text, image and table. While I am reading the tables from the JTextPane, I find that if there are more than one JTable, then the second table is returned first, then the first table.
    Still I have not found the exact pattern it returns when there are more than one table in the JTextPane, however I am getting the table in a different sequence than they were entered in the TextPane.
    Thanks in advance for the help.

    Hi,
    I am facing a bizarre problem. My JTextPane can contain rich text, image and table. While I am reading the tables from the JTextPane, I find that if there are more than one JTable, then the second table is returned first, then the first table.
    Still I have not found the exact pattern it returns when there are more than one table in the JTextPane, however I am getting the table in a different sequence than they were entered in the TextPane.
    Thanks in advance for the help.

  • Extract text file with HTML tags from JTextPane

    hello world
    I have a big problem !
    I am creating an applet with a JTextPane ...
    so I can write text, (bold, italic etc), i can insert images.
    Now i want to create a text file with all the HTML tags
    corresponding to what I wrote in my JTextPane.
    I want to have and save the HTML file corresponding to what i wrote ...
    Is it possible ? Help me please ....
    Jeremie

    writing to a file from an applet is going to take a fair amount of work on your part.
    in order to write to a file from your applet, you have to use servlets or jsp to write to a file on your server. if you wish to write locally, look into signing your applet or policy settings of your browser.
    for writing to a file to the server, i suggest you look into servlets and tomcat to run the servlets.
    i just finished a project that used servlets and they take some time to figure out, but its definitely worth your time.
    here are some websites...
    http://www.j-nine.com/pubs/applet2servlet/Applet2Servlet.html
    http://jakarta.apache.org
    other websites have tutorials that you can look at too
    Andy

  • Rendering data from jTextPane

    I have two jTextPanes in the same frame. I am rendering data from both of them using .getDocument() property, now I want to flush this data into same document. How can I do it?
    Please help me out.
    Thanks in advance.

    I am rendering data from both of them using .getDocument() propertyNo idea what this means.
    now I want to flush this data into same documentDon't understand this either.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • How can I get High Lighted text from JTextPane?

    I can get Selected text when right click.
    But, I have to get high lighted text without Right click.
    How can I do this?
    Is it possible any way?

    Hi,
    you could try it with Document doc = editor.getDocument();
    int start = editor.getSelectionStart();
    String selectedText = doc.getText(start, editor.getSelectionEnd() - start);(editor above being your JTextPane).
    Ulrich

Maybe you are looking for

  • #REGION_STATIC_ID# does not work in report template for PPR

    I was hoping to use the new substitution string #REGION_STATIC_ID# for a PPR report, because when we do Export/Import of the app the Region ID changes and we have to manually change the Pager Header Javascript to get the PPR to work. A real pain. So

  • Input values in bex selction screen

    Hi Experts-- Iam facing a peculiar functionality in bex reporting. We are maintaining ZBATCH (Length 10)as the masterdata in BW. Created a variable for ZBATCH, in the selection screen if  i give values as 36789 as input it displays the data i mean th

  • Lost all my album artwork on ipod classic. How do I get it back?

    I lost all my artwork on my ipod classic. How do I get it back?

  • Remove timestamp

    Hi, This is my query using oracle 9i. select NUMTODSINTERVAL(NVL(CLOSE_DT,current_date) - OPEN_DT,'DAY') from W_SRVREQ_D Result: NUMTODSINTERVAL(NVL(CLOSE_DT,CURRENT_DATE)-OPEN_DT,'DAY') 60 13:29:8.999999999 I want result as 60 only. Will remove time

  • Sent boxes in Gmail and in Mail are not the same

    Hi, I am using Gmail and Mail in OS X lion.  When I send a message through Gmail (on Firefox), the message is not in the sent box in Mail. The sent box in Mail keeps messages sent through only Mail. Is there any way to "synchronize" sent boxes in Gma