From jtextpane to jtextpane

hi,
i want to write some thing on the one jtextpane and on hitting enter i want it to go to another jtextpane which handling is suitable for this....
i try the following but it dosent give me the result. it gives me error
JTextPane pane1,pane2;
pane2.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ev)
               String s=pane1.getText();
               pane1.setText("");
          try{
               document.insertString(document.getLength(), s+
"\n\n", normalStyle );
     catch(Exception e) {}
please help me!

I solved the problem by now, creating a class ( Serializable of course ) that keep's the first bean attributes and that the first bean write in the write External. Then The second bean is renamed as the first and with the same serialver, and in the readExternal I read that Info class. It works well but I would like to keep the name of the second class, not the first like it happens here.
Thank U all.

Similar Messages

  • Moving from JTextArea to JTextPane

    i'd like to implement a syntax highlighting into my program, however, JTextArea is what i'm using, and i need to use a JTextPane for it.
    My problem is that some of the methods are not the same between the two, such as: setTabSize(), this is one feature that i would like to set, but i do not know how to in a JTextPane, i'd appreciate any help

    Check out my replies (2 and 5) from this thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=226322

  • Set images on to JTextPane from JTextField or JTextPane using ":)"

    Hi,
    Please see my problem
    jtf = JTextField();
    ae = ActionEvent
    jta = JTextPane();
         if(ae.getSource() == jtf)
                   String Sticon = jtf.getText();
                   //jta.setText(Sticon);
                   System.out.println(Sticon);
                   if(Sticon == ":)" || Sticon.equals(":)"))
                        jta.insertIcon(new ImageIcon("07.gif"));
                        System.out.println("inside sticon");
                   else
                        jta.setText(Sticon);
                   jtf.setText("");
    Help please
    Thanks

    Do not use a test like if (Sticon == ":)")... for a String you always have to use the equals()[b] method.

  • Is changing from JTextArea to JTextPane a big deal???

    hi, me again,
    I was just wondering if anybody could tell me if it is a big deal to change from a TextArea to a TextPane! I have only realised what I can and can't do in a textarea and was wondering if I have a lot of work ahead with documents and attribute sets!?
    anyone have any comforting or reassuring word for me before I go a mess up my program!!

    If you use version control or make a snapshot of your source code, you can try to explore and learn from it (if and only if there is no time constraint)

  • 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

  • How to give styles to my HTMLDocument inside a JTextPane?

    I have a JTextPane with a HTMLDocument attached to it. How can I style the text which is typed in? For example I want to set a larger font. How can I do this in my example?
    Another problem is that when I hit the alignment buttons the text is actually aligned according to the hit button but the JEditorPane doesn't show the text correctly. It also doesn't enter a line feed when typing ENTER key.
    Can someone help me on this please?
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextPane;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    public class AdditionalText extends JFrame implements ActionListener {
         private JButton leftAlign;
         private JButton centerAlign;
         private JButton rightAlign;
         private JTextPane editor;
         private JButton save;
         private JButton dump;
         public AdditionalText() {
              setTitle("Test Frame");
              JPanel topToolbar = new JPanel();
              leftAlign = new JButton("Left");
              centerAlign = new JButton("Center");
              rightAlign = new JButton("Right");
              ActionListener alignLeft = new HTMLEditorKit.AlignmentAction("alignLeft", 0);
              ActionListener alignCenter = new HTMLEditorKit.AlignmentAction("alignCenter", 1);
              ActionListener alignRight = new HTMLEditorKit.AlignmentAction("alignRight", 2);
              leftAlign.addActionListener(alignLeft);
              centerAlign.addActionListener(alignCenter);
              rightAlign.addActionListener(alignRight);
              topToolbar.add(leftAlign);
              topToolbar.add(centerAlign);
              topToolbar.add(rightAlign);
              editor = createEditor();
              JPanel bottomToolbar = new JPanel();
              save = new JButton("Save");
              save.addActionListener(this);
              dump = new JButton("Dump");
              dump.addActionListener(this);
              bottomToolbar.add(save);
              bottomToolbar.add(dump);
              getContentPane().add(BorderLayout.NORTH, topToolbar);
              getContentPane().add(BorderLayout.CENTER, editor);
              getContentPane().add(BorderLayout.SOUTH, bottomToolbar);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              setSize(new Dimension(640, 480));
              setLocation((screenSize.width - 640) / 2, (screenSize.height - 480) / 2);
         private JTextPane createEditor() {
              JTextPane textPane = new JTextPane() {
                   public void paintComponent(Graphics g) {
                        Graphics2D g2 = (Graphics2D) g;
                        g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
                        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                        g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
                        g2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
                        g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                        g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
                        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                        super.paintComponent(g2);
              textPane.setEditorKit(new HTMLEditorKit());
              return textPane;
         public void actionPerformed(ActionEvent e) {
              HTMLDocument htmlDocument = (HTMLDocument) editor.getDocument();
              if(e.getSource() == save) {
                   HTMLEditorKit kit = (HTMLEditorKit)editor.getEditorKitForContentType("text/html");
                   try {
                        kit.write(System.out, htmlDocument, 0, htmlDocument.getLength());
                   } catch (IOException ex) {
                        ex.printStackTrace();
                   } catch (BadLocationException ex) {
                        ex.printStackTrace();
              } else if(e.getSource() == dump) {
                   htmlDocument.dump(System.err);
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (ClassNotFoundException e) {
                   e.printStackTrace();
              } catch (InstantiationException e) {
                   e.printStackTrace();
              } catch (IllegalAccessException e) {
                   e.printStackTrace();
              } catch (UnsupportedLookAndFeelException e) {
                   e.printStackTrace();
              AdditionalText at = new AdditionalText();
              at.show();
    }

    I created a class that can be used to highlight Java source code. Most of the code is for handling multi line comments. If you just want it to highlight certain keywords then you can get rid of all that logic. In case your interested, the code can be downloaded from here:
    http://www.discoverteenergy.com/files/SyntaxDocument.java

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • How to change the size of the caret in a JTextPane

    I have text of different font sizes and the default caret height is the height of the text with the maximum font size. How do I change the caret height so that it matches the height of the text with the specified font size ?

    This has been a real pain in the butt to figure out, but I think I finally got it. If you create your own caret (subclass of DefaultCaret) then you override its paint() and damage() methods. I was having all kinds of problems with this though. I was getting pieces of carets left behind when I moved with the arrow keys, etc... from the helps I found. The arrow keys were my big problem.
    I think I finally figured out that the damage() simply does need to specify an area a little bigger than the old caret so it can blank it out. Then I think others had a logic problem, and Sun does not make this problem clear. What happens it that I think repaint() calls paint() who then uses the bigger x, y, height and width parameters that got set in damage(), which was causing my problems because the damage size was bigger than the size I wanted to create my caret with. What I do is figure out my area from the font I am using (another trick) and make them (the charWd and charHt) variables class variables. I calculate them in damage, use a bigger area to blank out my old caret in damage, and then used the correct caret size I calculated in damage() in paint(), instead of the rectangle values that seem to get passed from damage() to paint(). That was the problem in other examples.
    Here is my code:
    run with java caretPain
    run with java caretPain -1 to see my fixed version
    run with java caretPain -2 to see some problems
    // written by: Stan Towianski
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Hashtable;
    import java.util.ArrayList;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.undo.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.text.*;
    import javax.swing.plaf.*;
    import java.net.URL;
    import java.io.*;
    import java.beans.*;
    public class caretPain extends JFrame {
    static caretPain CRTP2;
    JPanel contentPane;
    JTextPane textPane;
    JTextPane textPane2;
    JScrollPane scrollPane;
    JSplitPane splitPane;
    String newline = "\n";
    static final int MAX_CHARACTERS = 300100;
    static int FrameWidth = 500;
    static int FrameHeight = 300;
    String caretType = "blockOutline";
    static int useSpecialCaret = 0;
    DefaultCaret useCaret = new MyCaret();
    public caretPain() {
    textPane = new JTextPane( new DefaultStyledDocument() );
    textPane2 = new JTextPane( new DefaultStyledDocument() );
    if ( useSpecialCaret == 1 )
    System.out.println( "using special caret 1" );
    textPane.setCaret( useCaret );
    else if ( useSpecialCaret == 2 )
    System.out.println( "using special caret 2" );
    textPane.setCaret( new WsCaret() );
    textPane.setCaretPosition(0);
    textPane.setMargin(new Insets(5,5,5,5));
    scrollPane = new JScrollPane(textPane);
    textPane.setPreferredSize(new Dimension(FrameWidth, FrameHeight));
    JScrollPane scrollPane = new JScrollPane(textPane);
    //Create a split pane for the change log and the text area.
    splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
    textPane, textPane2 );
    splitPane.setOneTouchExpandable(true);
    //Add the components to the frame.
    contentPane = new JPanel(new BorderLayout());
    contentPane.add(splitPane, BorderLayout.CENTER);
    setContentPane(contentPane);
    class MyCaret extends DefaultCaret
    int charWd = 30;
    int charHt = 30;
    // draw the caret
    public void paint(Graphics g)
    System.err.println( "entered MyCaret.paint()" );
    if ( ! isVisible() )
    System.err.println( "exiting because not visible" );
    return;
    try {
    JTextComponent c = getComponent();
    int dot = getDot();
    Rectangle r = c.modelToView(dot);
    System.err.println("caret: text position: " + dot +
    ", view location = [" +
    r.x + ", " + r.y + "]" +
    newline);
    g.setColor(c.getCaretColor());
    //g.drawLine(r.x, r.y + r.height - 1, r.x + 14, r.y + r.height - 1);
    System.err.println( "caretType =" + caretType ); //+ " component =" + c.toString() );
    if ( caretType.equals( "blockOutline" ) )
    g.drawRect( r.x, r.y, charWd, charHt );
    else if ( caretType.equals( "block" ) )
    g.fillRect( r.x, r.y, charWd, charHt );
    else if ( caretType.equals( "bar" ) )
    g.drawLine( r.x, r.y, r.x, r.y + charHt );
    catch (BadLocationException e) {
    System.err.println( "bad caret loc" + e);
    // specify the size of the caret for redrawing
    // and do repaint() -- this is called when the
    // caret moves
    //protected synchronized void damage(Rectangle r)
    public synchronized void damage(Rectangle r)
    System.err.println( "entered MyCaret.damage()" );
    System.err.println("caret.damage(): text position: " + getDot() +
    ", view location = [" +
    r.x + ", " + r.y + "]" +
    newline);
    //FontMetrics fm = g.getFontMetrics();
    //System.out.println( "textPane getfont =" + textPane.getFont() );
    //System.out.println( "\n\n read in attribs font size =" + textPane.getInputAttributes().getAttribute(StyleConstants.FontSize) + "\n\n" );
    //int ii = Integer.parseInt( (String) textPane.getInputAttributes().getAttribute( StyleConstants.FontSize ) );
    int ii = Integer.parseInt( String.valueOf( textPane.getInputAttributes().getAttribute( StyleConstants.FontSize ) ) );
    //System.out.println( "textPane input attrib font size =" + ii );
    Font f = new Font( "ff", Font.PLAIN, ii );
    //System.out.println( "textPane input attrib font =" + f );
    FontMetrics fm = getFontMetrics( f );
    //FontMetrics fm = g.getFontMetrics();
    //FontMetrics fm = getFontMetrics( textPane.getInputAttributes().getAttribute( StyleConstants.FontSize ) );
    //MutableAttributeSet inputAttributes = getInputAttributes();
    //String fs = textPane.getAttribute( "FontSize" );
    //System.out.println( "\n\n read font size =" + textPane.getCharacterAttributes().getAttribute(StyleConstants.FontSize) + "\n\n" );
    charWd = fm.charWidth( 'k' );
    charHt= fm.getHeight();
    //System.out.println( "font width =" + charWd + " font height =" + charHt + " font =" + fm.toString());
    if ( r == null )
    System.err.println( "caret.damage() return on rectangle == null" );
    return;
    x = r.x - 2;
    y = r.y - 2; // + r.height - 2;
    width = charWd + 4; //textPane.getColumnWidth();
    height = charHt + 4; //textPane.getRowHeight();
    System.err.println("caret.damage(): set caret width, height, x, y =" + width + "," + height + "," + x + "," + y );
    repaint();
    //repaint();
    public class WsCaret extends DefaultCaret {
    transient private int[] flagXPoints = new int[3];
    transient private int[] flagYPoints = new int[3];
    public WsCaret() {
    this.setBlinkRate(500);
    public void paint(Graphics g) {
    if(isVisible()) {
    JTextComponent component = this.getComponent();
    TextUI mapper = component.getUI();
    Rectangle r = null;
    try {
    r = mapper.modelToView(component, this.getDot());
    catch(BadLocationException exc) {}
    //System.out.println( "rect r =" + r.toString() );
    //g.drawLine(r.x, r.y, r.x, r.y + r.height - 1);
    //g.drawLine(r.x+1, r.y, r.x+1, r.y + r.height - 1);
    g.drawRect( r.x, r.y, 10, r.height );
    Document doc = component.getDocument();
    if (doc instanceof AbstractDocument) {
    Element bidi = ((AbstractDocument)doc).getBidiRootElement();
    if ((bidi != null) && (bidi.getElementCount() > 1)) {
    // there are multiple directions present.
    flagXPoints[0] = r.x;
    flagYPoints[0] = r.y;
    flagXPoints[1] = r.x;
    flagYPoints[1] = r.y + 4;
    flagYPoints[2] = r.y;
    flagXPoints[2] = (true) ? r.x + 5 : r.x - 4;
    System.out.println( "going g.fillPolygon" );
    g.fillPolygon(flagXPoints, flagYPoints, 3);
    protected synchronized void damage(Rectangle r) {
    if (r != null) {
    this.x = r.x - 4;
    this.y = r.y;
    //there must be a better way to doing this, but for now you
    //just increase the width so that it will cover the new caret's size
    this.width = 20; // the original width is 10
    this.height = r.height;
    //this.height = r.height + 20;
    //this.height = 10;
    repaint();
    //The standard main method.
    public static void main(String[] args) {
    if ( args.length > 0 )
    System.out.println( "found arg so will use special caret." );
    if ( args[0].equals( "-1" ) )
    useSpecialCaret = 1;
    else if ( args[0].equals( "-2" ) )
    useSpecialCaret = 2;
    else
    System.out.println( "found no arg so will standard caret." );
    System.out.println( "give arg: -1 to get Stan\'s working caret" );
    System.out.println( "give arg: -2 to get another example\'s caret" );
    try
    CRTP2 = new caretPain();
         catch (Exception ex)
    System.out.println("Error creating CRTP2: " + ex);
    ex.printStackTrace();
    System.exit(0);
    CRTP2.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void windowActivated(WindowEvent e) {
    CRTP2.textPane.requestFocus();
    CRTP2.setTitle( "This is my title you" );
    CRTP2.pack();
    CRTP2.setVisible(true);

  • JTextPane and TransferHandler

    While trying to integrate another company's applet into our system, I realized I was going to have to write my own TransferHandler to handle pasting content from Microsoft Word. Soon after, I realized that you must also override other methods of TransferHandler so that copying, cutting and drag-and-drop all still work. I have been able to get most things working, but have had trouble with the createTransferable() method. The problem I am having is that the JComponent I am trying to allow copying from is a JTextPane with and underlying HTMLDocument. When I use the JTextPane.getSelectedText() method, I only get the bare text and not the underlying HTML code that I desire.
    I have searched high and low for a method to get the underlying HTML code which corresponds to the current selection in the JTextPane to no avail. Can anyone offer any insight into this conundrum?
    Thank you for your time and consideration.

    It's funny that no one has ever answered this question (or the many like it from before). I ended up finding the source for Java's default TransferHandler and seeing how it was grabbing the underlying HTML code. It all seems to make much more sense now, but it's not something I would have arrived at without the source to look at.
    You can find the source to the BasicTextUI.TextTransferHandler here -- http://www.javaresearch.org/source/jdk142/javax/swing/plaf/basic/BasicTextUI.java.html. Among other things, it shows how you go about "grabbing" the structure from the underlying document. Basically you use the EditorKit (or, in this case, the HTMLEditorKit) to read from the document and it take care of the "translation" for you. The important part goes something like this (minus try-catch blocks):
    Document doc = textPane.getDocument();
    EditorKit kit = textPane.getEditorKit();
    int beg = textPane.getSelectionStart();
    int end = textPane.getSelectionEnd();
    Position p0 = doc.createPosition(beg);
    Position p1 = doc.createPosition(end);
    StringWriter htmlOut = new StringWriter(p1.getOffset() - p0.getOffset());
    kit.write(htmlOut, doc, p0.getOffset(), p1.getOffset() - p0.getOffset());
    return htmlOut.toString();Now the only problem I need fixed is trying to get the EditorKit to stop from including all the structure from the entire ancestry of the current selection. For instance, if you select just one letter from a cell of a table that is nested in a div, inside another table, the resulting string from that single-character selection would be like this:
    <html xmlns="http://www.w3.org/1999/xhtml">
    <body>
    <table>
    <tr>
    <td>
    <div>
    <table><tr><td>X</td></tr></table>
    </div>
    </td>
    </tr>
    </table>
    </body>
    </html>Now if someone could just point out how to intelligently limit that return scope, I'd be one happy little coder! (I tried, unsuccessfully, to insert a marker like following, to no avail.)
    <!--Begin Marker-->
    the original selection goes here
    <!--End Marker-->

  • How to get the current location text in JTextPane

    hi
    i want to get the current location text in JTextPane ...iam useing
    caretPos = jtpMain.getCaretPosition();
    iam geting the current Locations at the same time i want to read the entery current line
    i used like this
    StartPos=jtpMain.getText();
    but iam geting entry data in JTextPane ... how can get current Locatin data ...
    pls help me

    If I understood your request, what you would like to do is to be able to retrieve Start and End Positions of a given line (a line and NOT the whole content of the JTextPane).
    JTextPane is a graphical component that is bound to a logical document. Documents are structured in elements. What defines an element is up to you to decide if you extend your own document but elements are by default paragraphs (runs of text ended by a carriage return '\n' character). So, I think that what you want to do is to retrieve the Start and End positions of the
    paragraph over which the caret is currently positionned. Then I think you have got to do the following :
    int intStartPos;
    int intEndPos;
    int intCaretPos;
    javax.swing.text.StyledDocument docStyledDoc;
    javax.wing.text.Element eleParagraph;
    intCaretPos = jtpMain.getCaretPosition( );
    //Get a reference to the default styled document bound to the JTextPane component
    docStyledDoc = jtpMain.getStyledDocument( );
    //Get the paragraph element from the document over which the caret is positionned
    eleParagraph = docStyledDoc.getParagraphElement(intCaretPos);
    //Get paragraph's offsets
    intStartPos = eleParagraph.getStartOffset( );
    intEndPos = eleParagraph.getEndOffset( );
    hi
    i want to get the current location text in JTextPane
    ...iam useing
    caretPos = jtpMain.getCaretPosition();
    iam geting the current Locations at the same time i
    want to read the entery current line
    i used like this
    StartPos=jtpMain.getText();
    but iam geting entry data in JTextPane ... how can
    get current Locatin data ...
    pls help me

  • Incorrect Offset in setCharacterAttributes() of JTextPane AND Matcher

    I use Java regular expression, Matcher class or m.find(), for searching and replacing string from JTextPane. Then, I use setCharacterAttributes() to change color of the matched string.
    My problem is that when text in the JTextPane() contains new line characters, the start position returned from m.start() includes those new line characters but the setCharacterAttributes() method does not.
    Therefore, if I use the start position returned from m.start() as "offset" for the setCharacterAttributes() method, the matched string is incorrectly colored. If there are two new line characters before the matched string, the colored text will be missed by two characters to the right.
    For example, if the matched string is "are" in the "how are you?" text, and there are two new line characters before the text, the colored text is "e y" rather than "are".
    What should I do to fix this problem?
    Thank you very much.

    Get the position of the found text from the document associated with the JTextPane. Try this:import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    import javax.swing.text.Document;
    public class SearchTextPane {
       JFrame frame = new JFrame ("Search JTextPane Test");
       JTextPane textPane = new JTextPane ();
       JPanel panel = new JPanel ();
       JTextField textField = new JTextField (10);
       JButton button = new JButton ("Find");
       Document doc = textPane.getDocument ();
       void makeUI () {
          button.addActionListener (new ActionListener () {
             public void actionPerformed (ActionEvent e) {
                try {
                   Matcher matcher = Pattern.compile (textField.getText ())
                         .matcher (doc.getText (0, doc.getLength ()));
                   matcher.find ();
                   textPane.setCaretPosition (matcher.start ());
                   textPane.moveCaretPosition (matcher.end ());
                   textPane.requestFocus ();
                } catch (Exception ex) {
                   JOptionPane.showMessageDialog (frame, "Not Found!\n" + ex.toString ());
                   //ex.printStackTrace();
          panel.add (textField);
          panel.add (button);
          panel.setPreferredSize (new Dimension (300, 40));
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (300, 300);
          frame.add (textPane, BorderLayout.CENTER);
          frame.add (panel, BorderLayout.SOUTH);
          frame.setLocationRelativeTo (null);
          frame.setVisible (true);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                new SearchTextPane ().makeUI ();
    }db

  • Forcing a JTextPane to scroll down

    Hello I have a JTextPane inside a JScrollpane
    how can I force the JTextPane to scroll down when text is added to it?

    Why is it so hard to do a search before posting a question??????
    I took 3 words from you topic, "+jtextpane +scroll +down" and did a search and found that this question has been asked and answered dozens of times.

  • Adding ScrollBars to JTextPane

    I migrated from TextArea to JTextPane in a simple chat program in order to display colors and styled font sizes. The problem is that the border and scroll bars previously given by TextArea are gone when I switched to JTextPane. I managed to place a border. But I cannot figure out how to add at least vertical scroll bars to the TextArea. I tried to use JScrollPane and then added the JTextPane to it, but then I cannot see what I type.
    Can you please help?
    CS

    You are doing the correct thing. To add scrolling to any Swing component you add the component to a JScrollPane and then add the JScrollPane to your container.
    If you cannot see what you are typing that may be because you didn't give your component enough space and the scrollbars of the JScrollPane are taking up all the space. Give your component more space and see if that fixes the problem.
    HTH
    Bryan

  • Problem - Text in JTextPane overlaps

    Hi All,
    I have an application that allows 2 users (User A + User B) to chat
    interactively. Every character User A / User B inputs will be sent to the other
    side immediately. Only one of the users is "active" - only characters input by the
    "active" user will be sent to the other side. When the "active" user has finished
    typing, he/she will press a button to indicate he/she is done and the other side
    will become "active".
    Characters input by User A / User B will be displayed in an instance of
    JTextPane at the other side. An instance of DefaultStyledDocument is used as the
    only argument of the constructor that is called to initialize the instance of
    JTextPane. JTextPane is used because different colors has to be used to identify
    characters input by the 2 users.
    Below is some lines of code of the application.
          StyledDocument doc = new DefaultStyledDocument();
          JTextPane txtReceiveBuffer = new JTextPane(doc);
          SimpleAttributeSet attribute = new SimpleAttributeSet();
          StyleConstants.setForeground(attribute, Color.blue);
          doc.insertString(doc.getLength(), strUserInput, attribute);
          ...Sometimes a line of characters in the JTextPane will overlap the other line.
    (It seems like a transparent layer with some characters is placed in front of
    another layer with some characters.) Sometimes the line "behind" will totally
    disappear. (It seems like a non-transparent layer with some characters is placed
    in front of another layer with some characters.) If a user tries to resize the
    frame that contains the JTextPane, sometimes things will be fine again, but
    sometimes the problem doesn't go until the application is restarted.
    Has anyone ever encountered the same problem? And does anyone get a solution to
    this problem?
    Thanks in advance.
    Paul

    Are you adding the text from the other user in another thread than the event thread? Swing is not thread safe and strange things might happen if you update components from other threads. The solution would be to only update from the event thread. Look at the method SwingUtilities.invokeLater() for a way to do that: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable&#41;

  • Tab setting in JTextPane

    Hi,
    I am going to develop an simple XML editor which will provide following functionalituies.
    * Automatic Indentation
    * Highilight attributes of given schema
    * Tag Validation.
    I decided to use JTextPane.
    1) Is It right choice for Rich Text Support ?
    2) How to set Tab size in JTextPane

    2) How to set Tab size in JTextPane Search the forum. You can even use keywords directly from your question: "jtextpane tab size".

Maybe you are looking for

  • Qosmio G20-156 - no sound

    Hi, i'm having a bit of trouble with my g20-156. It had stopped locating wireless networks, so as it was in need of a bit of a clean up anyway, i restored it back to factory default settings. The good news is that the wireless problem is now resolved

  • I miss the delete to the right key on wireless keyboard

    I really miss this, and was about to post asking for a solution when on Google I discovered the following post: My delete button is operating in the...: Apple Support Communities

  • HT1725 trying to connect and getting host down check your connection and try again??

    trying to connect and getting host down check your connection and try again??

  • TS3988 icloud only works with one version of outlook

    I uninstalled 2013 outlook and re-installed 2010 but I still get an error message when trying to launch icloud. The error says icloud cannot work with two versions of outlook (which i don't have now) any thoughts?

  • Problems with the Validator

    Hi, I have a <h:command_hyperlink label="DataList" commandName="showList" actionRef="Bean.showDataListAction"/> and some late in the Code a <h:form .....> with some text fields using the custom validator. The value will be requaed for this text field