JTextPane && JScrollPane

Hi everybody,
maybe this question, which marks me as very dumb, but I will try.
I created a JTextPane with all the needed things(Styles,...) and everything works fine.
But now I want to embedd this pane into a JScrollPane. It works fine too, except of the horizontal scrollbar.
If I force its visibility it is shown, but nothing happens when the current line in the textpane will become longer than the displayable area. What I mean is, that the scrollbar displays, but the bubble will not appear. Therefore the current line will be continued in the next line.
But I just want this text to be continued in the same line, so that I can scroll.
thanks in advance
regards
c

its strange, you have to add an additional viewport into the viewport of the scrollpane. I thought the viewport of the scrollpane should do the job. why doesnt it do so?
regards,
stefan
Hi,
ok some hints
1. create a viewport
2. add the JTextPane to this viewport
3. add the viewport to a JScrollPane
// ... some code
JViewport vp = new JViewport();
vp.add(textPane);
vp.setScrollMode(JViewport.BLIT_SCROLL_MODE);
// ... maybe some more code
JScrollPane sp=new JScrollPane(vp,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);hope it helps
regards

Similar Messages

  • JTextPane/JScrollPane problems

    in my JTextPane i would like to be able to set the tab size (like you can with JTextArea), and for some reason my JScrollPane doesn't want to scroll the JTextPane horizontally, it just wraps the text. any help and sample code is very appreciated.
    TravenE

    Well normally I'd tell you to search the forums because I've answered both of these question several times before. But since the search isn't currently working for me I'm assuming it isn't working for you either, so here are my suggestons.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TextPaneTabs extends JFrame
         public TextPaneTabs()
              JTextPane textPane = new JTextPane();
              textPane.setFont( new Font("monospaced", Font.PLAIN, 12) );
              JScrollPane scrollPane = new JScrollPane( textPane );
              scrollPane.setPreferredSize( new Dimension( 200, 200 ) );
              getContentPane().add( scrollPane );
              setTabs( textPane, 4 );
         public void setTabs( JTextPane textPane, int charactersPerTab)
              FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
              int charWidth = fm.charWidth( 'w' );
              int tabWidth = charWidth * charactersPerTab;
              TabStop[] tabs = new TabStop[10];
              for (int j = 0; j < tabs.length; j++)
                   int tab = j + 1;
                   tabs[j] = new TabStop( tab * tabWidth );
              TabSet tabSet = new TabSet(tabs);
              SimpleAttributeSet attributes = new SimpleAttributeSet();
              StyleConstants.setTabSet(attributes, tabSet);
              int length = textPane.getDocument().getLength();
              textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
         public static void main(String[] args)
              TextPaneTabs frame = new TextPaneTabs();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestNoWrap extends JFrame
         JTextPane textPane;
         JScrollPane scrollPane;
         public TestNoWrap()
              JPanel panel = new JPanel();
              panel.setLayout( new BorderLayout() );
              setContentPane( panel );
              // no wrap by adding text pane to a panel using border layout
              textPane = new JTextPane();
              textPane.setText("1234567890 1234567890 1234567890");
              JPanel noWrapPanel = new JPanel();
              noWrapPanel.setLayout( new BorderLayout() );
              noWrapPanel.add( textPane );
              scrollPane = new JScrollPane( noWrapPanel );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane, BorderLayout.NORTH );
              // no wrap by overriding text pane methods
              textPane = new JTextPane()
                   public void setSize(Dimension d)
                        if (d.width < getParent().getSize().width)
                             d.width = getParent().getSize().width;
                        super.setSize(d);
                   public boolean getScrollableTracksViewportWidth()
                        return false;
              textPane.setText("1234567890 1234567890 1234567890");
              scrollPane = new JScrollPane( textPane );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane );
         public static void main(String[] args)
              TestNoWrap frame = new TestNoWrap();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • ( (JTextPane in JScrollPane) in JTabbedPane)???

    JTextPane textarea = new JTextPane();
    JScrollPane scroll= new JScrollPane(textarea);
    JTabbedPane tab = new JTabbedPane();
    tab.add(scroll);
    Now the problem is when i create many tabs and put
    it in my window , and i want to jump from one tab to
    another , the textpane does not get the focus .
    tab contains scroll as its client so it gives focus to the
    scroll but i want the textarea to have the cursor.so that there is no need for the user to click in the textarea to gain focus.
    I hope some one understands my problem and helps me ...
    thanks alot......

    I'm running JDK1.3 on windows 98. The requestFocus() method does not work unless it is executed after the JFrame is shown. Maybe this is your problem. The following sample program will help illustrate this.
    1) run the program as is. Focus should be on the text area as you select a tab.
    2) Comment out the 'newTab' methods in the main method. Uncomment the 'newTab' methods in the constructor. This time focus will remain on the tab as you select it.
    Hope this helps.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class TestTabbedPane extends JFrame
         JTabbedPane tabbedPane;
         public TestTabbedPane()
              tabbedPane = new JTabbedPane();
              tabbedPane.setPreferredSize( new Dimension(300, 200) );
              getContentPane().add(tabbedPane);
    //          newTab( "one" );
    //          newTab( "two" );
    //          newTab( "three" );
         private void newTab(String text)
              JTextArea textArea = new JTextArea( text );
              JScrollPane scrollPane = new JScrollPane( textArea );
              tabbedPane.addTab( text, scrollPane );
              tabbedPane.setSelectedIndex( tabbedPane.getTabCount() - 1 );
              textArea.requestFocus();
         public static void main(String args[])
    TestTabbedPane frame = new TestTabbedPane();
    frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    frame.pack();
    frame.setVisible(true);
              frame.newTab( "one" );
              frame.newTab( "two" );
              frame.newTab( "three" );

  • JScrollPane on JTextPane with GridBagLayout

    I am havign problem setting a scrollbar on a JTextPane. All I want. I want to add just buttons in one column from top to bottom, and I want the scrollbar so I can see all the buttons. I need to use GridBagLayout on the JTextPane. below is a simplified version of my code...anyone plz help..
    public class ScrollTestMain {
    public static void main(String[] args) {
    JFrame frame=new JFrame("test");
    JTextPane tp = new JTextPane();
    JScrollPane sp=new JScrollPane(tp);
    GridBagLayout gridbag=new GridBagLayout();
    GridBagConstraints c=new GridBagConstraints();
    tp.setLayout(gridbag);
    c.weightx=100;
    c.weighty=100;
    for (int i=0;i<16;i++) {
    c.gridx=0;
    c.gridy=i;
    JButton button =new JButton("button"+i);
    gridbag.setConstraints(button,c);
    System.out.println("for loop "+i);
    tp.insertComponent(button);
    frame.setSize(200,200);
    frame.setVisible(true);
    frame.getContentPane().add(sp, BorderLayout.CENTER);
    tp.setEditable(false);
    frame.show();
    I want the buttons to be like:
    button0
    button1
    button2
    button3
    button4
    and the vertical scrollbar so I can scrolldown to see all the buttons.

    From the "An Example of Using a Text Pane" section on the page How to Use Editor Panes and Text Panes in the java tutorial.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TextPaneTest
        public static void main(String[] args)
            String newline = "\n";
            String[] initString = new String[8];
            String[] initStyles = new String[8];
            for(int j = 0; j < 8; j++)
                initString[j] = " " + newline;
                initStyles[j] = "button" + j;
            JTextPane textPane = new JTextPane();
            StyledDocument doc = textPane.getStyledDocument();
            addStylesToDocument(doc);
            try
                for(int j = 0; j < initString.length; j++)
                    doc.insertString(doc.getLength(), initString[j],
                                     doc.getStyle(initStyles[j]));
            catch(BadLocationException ble)
                System.out.println("unable to init text");
            JScrollPane scrollPane = new JScrollPane(textPane);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(scrollPane);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private static void addStylesToDocument(StyledDocument doc)
            Style def = StyleContext.getDefaultStyleContext().
                            getStyle(StyleContext.DEFAULT_STYLE);
            Style space = doc.addStyle("space", def);
            StyleConstants.setSpaceAbove(space, 40f);
            StyleConstants.setLeftIndent(space, 75f);
            doc.setLogicalStyle(0, space);
            for(int j = 0; j < 8; j++)
                Style s = doc.addStyle("button" + j, space);
                JButton button = new JButton("button " + j);
                button.setCursor(Cursor.getDefaultCursor());
                button.setMargin(new Insets(5,5,5,5));
                button.setActionCommand("button " + j);
                //button1.addActionListener();
                StyleConstants.setComponent(s, button);
    }

  • Open a Text File in a JTextPane

    Hi,
    Can anyone please help me with this stupid problem. I want a specific .txt file to be opened in a JTextPane when the application is started. If anyone has any suggestions it would be really appreciated. Thanks.
    Martin

    Any help is really apprecited
    JFrame recordsFrame = new JFrame("Records");
    JTextPane textpane = new JTextPane();
    textpane.setPreferredSize(new Dimension(400,400));
    textpane.setMinimumSize(new Dimension(400,400));
    textpane.setText(/*What do i do in here to output a .txt file to the JTextPane*/);
    JScrollPane scroller=new JScrollPane(textpane);
    scroller.setPreferredSize(new Dimension(400,400));
    recordsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    recordsFrame.getContentPane().add("South", textpane);
    recordsFrame.setSize(400, 400);
    recordsFrame.setVisible(true);

  • 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

  • Total no. of lines in JTextPane document and Increment them on "ENTER" key

    hello,
    I wanted to know the total number of lines that a document has. I.e for example when I open a .java into my JTextPane, I wanted to know the total no. of lines the file has and I wanted to increment them when I press the enter key.
    2. Even it is a plain document, i.e just typing in the JTextPane and when I press enter key the number of lines should get incrementing.
    I am using this method , but un successful. Can any one help me?
    public int getLines()
              Document doc = text.getDocument();
              Element map = doc.getDefaultRootElement();
              int n = map.getElementCount();
              Element lastLine = map.getElement(n-1);
              if ((lastLine.getEndOffset() - lastLine.getStartOffset()) > 1)
                   return n;
              return n - 1;
    where text = JTextPane
    Any example source will be helpful.
    Thanks

    Your code looks correct. Here is the program I used to test it. You must be calling the getLines() method BEFORE the document is being updated.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    public class TestTextArea extends JFrame
         public TestTextArea()
              JPanel panel = new JPanel();
              setContentPane( panel );
              panel.setLayout( new BorderLayout() );
              final JTextPane textArea = new JTextPane();
              JScrollPane scrollPane = new JScrollPane( textArea );
              panel.add( scrollPane );
              JButton button = new JButton("Display Lines");
              panel.add( button, BorderLayout.SOUTH );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        Document doc = textArea.getDocument();
                        Element map = doc.getDefaultRootElement();
                        int n = map.getElementCount();
                        Element line = map.getElement(n-1);
                        if (line.getEndOffset() - line.getStartOffset() == 1)
                             n--;
                        System.out.println( n );
                        textArea.requestFocus();
         public static void main(String[] args)
              TestTextArea frame = new TestTextArea();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • JTextPane first line read only

    Hi all!
    I'm a beginner in java programming, that said im trying to make a simple text editor (who isn't?), it will be a part of another larger application, nevertheless this editor is a main component, just need some simple editing tips.
    I want to use a JTextPane for the editable surface, this is working fairly well but i am not able access other lines in the editor except from the first one. Meaning that when containing a large piece of text, my JTextPane is only able to edit the first line: For instance the caret will only show it self on the first line, I can write new letters, but only on the first line and i can erase them and so on. What am I missing? Have checked around many places for solutions
    To sum it up; I want to edit every line in my JTextPane instead of just the first one :)

    Ok! thanks a lot for the good advice, ant help is most appreciated. :-)
    Here is a piece of code that demonstrates my problem. Hope it brings insight! Try to write a line of text, then press enter to go to the next line, most probably you will find yourself unable to edit this line.
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    public class Test implements Runnable
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Test());
         public void run()
              JPanel cP = new JPanel();
              JTextPane tP = new JTextPane();
    JScrollPane sP = new JScrollPane( tP );
    tP.setPreferredSize(new Dimension( 400 , 400 ) );
              sP.setPreferredSize(new Dimension( 300 , 300 ) );
              tP.setEditable(true);
              cP.add(sP);
              JFrame f = new JFrame();
              f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              f.setContentPane( cP );
              f.setLocationRelativeTo( null );
              f.setVisible( true );
    }

  • Fixed a top line in JScrollPane?

    Dear all,
    I have a JScrollPane, which has a textPane in it. Now I want to set one important warning line at the top of the textPane, and then add any other texts into textPane following the warning line. Moreover, I want this warning line to be fixed at the top, no matter whether the textPane scroll down or not, i.e, this warning line is always at the top of pane and never disappears when scrolling down the textPane.
    I do not know how to implement this. The following code will scroll away the warning line after I adds long lines to it.
    Any samples on how to implement this?
    public class NewsPane extends JScrollPane {
      private JTextPane text;
      private DefaultStyledDocument doc;
      public NewsPane() {
           JTextPane text = new JTextPane( doc=new DefaultStyledDocument());
           text.setText("Warning ...");
           setViewportView(text);
      }Thanks!

    Try this
    regards
    Stas
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
    JTextPane edit=new JTextPane();
    JScrollPane scroll;
    JLabel l;
    public Test() throws Exception {
    JFrame frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    scroll=new JScrollPane(edit);
    l=new JLabel("Warning!");
    l.setBounds(10,10,100,20);
    l.setForeground(Color.red);
    edit.add(l);
    frame.getContentPane().add(scroll);
    AdjustmentListener adjLst = new AdjustmentListener() {
    public void adjustmentValueChanged(AdjustmentEvent e) {
    Rectangle rect=scroll.getViewport().getViewRect();
    l.setLocation(rect.x+10,rect.y+10);
    scroll.getVerticalScrollBar().addAdjustmentListener(adjLst);
    frame.setSize(200,200);
    frame.setLocationRelativeTo(null);
    frame.show();
    edit.getDocument().insertString(0,"test1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n",null);
    public static void main(String[] args) throws Exception {
    new Test();

  • JTextPane - setting selected text colour

    Ok, I have a bit of a problem. Here is some general information about my program.
    I have a JTextPane called "DDITextArea" and I can type in it and stuff. I want to be able to select some of the text and use a JColorChooser to set the text to that color of my choice. I am doing a bit of experimentation with the swing components and messed around with a JColorChooser. Here is the code for the chooser.
        ColourOption.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (first) {
              first = false;
              chooser.setPreviewPanel(new CustomPane());
            JDialog dialog = JColorChooser.createDialog(RecipeBrowser.this, "Demo 3", true, chooser, new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                    c = chooser.getColor();
                }, null);
            dialog.setVisible(true);
    *I NEED SOMETHING HERE TO SET THE SELECTED TEXT TO THE COLOUR I CHOOSE WITH THE JCOLOURCHOOSER
    *I HAVE A JTEXTPANE AND I WANT TO BE ABLE TO SELECT SOME TEXT THEN USE THE JCOLORCHOOSER TO SET THE COLOUR OF THE SELECTED TEXT
        });as you can see from the comments near the end of the code sample, I need to know how to set the selected text to Color c. I don't know if there is a method for this. I looked at the online Java syntax database but to no luck. Just to ensure that there is no misunderstanding I will give an example:
    DDITextArea has the sentence "The dog is wet and smelly" and its default font colour is black. If I highlight the words "The Dog", open the ColorChooser and select red, the words "The Dog" will be red while everything else is black.
    If it is any help, here is where my DDITextArea is created
              final JTextPane DDITextArea = new JTextPane();
              JScrollPane DDITextAreaScrollPane = new JScrollPane(DDITextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              //DDITextArea.setLineWrap(true);
              //DDITextArea.setWrapStyleWord(true);
              DDITextArea.setEnabled(true);
              DDITextArea.setEditable(true);
              DDITextArea.setVisible(true);
              gbc.fill = GridBagConstraints.BOTH;
              gbc.anchor = GridBagConstraints.CENTER;
              gbc.gridx = 1;
              gbc.gridy = GridY;
              gbc.gridwidth = 1;
              gbc.gridheight = 1;
              gbc.weightx = 1;
              gbc.weighty = 1;
              gbl.setConstraints(DDITextAreaScrollPane, gbc);
              PrintTab.add(DDITextAreaScrollPane);Am I missing any necessary syntax to do this or is there something much more complicated involved?

    Sorry for the double post but I figured it out. I missed the answer. This is a clear sign I must stop doing past-midnight research.
    Anyways, for any folds that have trouble with this in the future, here you go. I hope someone, somewhere, sometime, will have need for this.
        ColourOption.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (first) {
              first = false;
              chooser.setPreviewPanel(new CustomPane());
            JDialog dialog = JColorChooser.createDialog(RecipeBrowser.this, "Demo 3", true, chooser, new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                    c = chooser.getColor();
                }, null);
            dialog.setVisible(true);
    //THE CODE BELOW THIS COMMENT IS WHAT I ADDED
    new StyledEditorKit.ForegroundAction("", c).actionPerformed(null);
    //THE CODE ABOVE THIS COMMENT IS WHAT I ADDED
        });

  • JTextPane - Parsing HTML

    Hello all,
    I'm working on implementing a Web Browser in Java that recognizes only a small subset of the HTML tags.
    A simplistic way to display a Web Page is to use a JTextPane (JEditorPane) with the setPage(URL) method. The problem here is that setPage() recognizes more tags than I would want him to.
    My first solution was to subclass the ViewFactory class. It worked fine except for tags that are synthesized to HTML.Tag.Content. There are some tags such as <U> (but I can't filter HTML.Tag.Content because I want to accept tags such as <B>).
    Next, I tried subclassing HTMLDocument and its inner class HTMLDocument.HTMLReader. Before going any further, here's the code I use to display HTML in my JTextPane:
    editor = new JTextPane();
    // JScrollPane will contain editor
    JScrollPane scrollPane = new JScrollPane(editor,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    // init JTextPane
    editor.setEditable(false);
    EditorKit kit = new BasicHTMLEditorKit();
    editor.setEditorKit(kit);
    editor.addHyperlinkListener(...);
    loadPage("http://www.iro.umontreal.ca");
    private void loadPage(String strURL) {
    try {
    loadPage(new URL(strURL));
    } catch (Exception exc) {
    editor.setText("Error: " + exc);
    private void loadPage(URL url) {
    /*Document doc = editor.getDocument();
    EditorKit kit = editor.getEditorKit();
    StringReader reader = new StringReader(HTMLTxt);*/
    try {
    editor.setPage(url);
    //kit.read(reader, doc, 0);
    } catch (Exception exc) {
    editor.setText("Error: " + exc);
    setSubWindowTitle(editor);
    I tried to set the JTextPane document using its constructor:
    new JTextPane(new BasicHTMLDocument());
    And using the setDocument() method.
    I also tried to override the createDefaultDocument of the HTMLEditorKit and return new BasicHTMLDocument().
    In each cases, the parsing works fine because I put some println() in the overriden handleSimpleTag and handleStartTag of my BasicHTMLDocument (note that BasicHTMLDocument extends HTMLDocument and BasicHTMLReader extends HTMLDocument.HTMLReader).
    BUT whenever I try to display the HTML, it does not work. It looks like the parsing tree does not exist anymore (I put some println() in an overriden ViewFactory).
    Could someone help me figuring this out? I'd really like to understand why my strategy does not work. And by the way, is there any other simpler solution ? (note that I am forced to use JTextPane and that I absolutely need to filter undesired tags).
    Thank you all very much. I hope someone will be able to help me! :)

    Bumped. Google and the rest of the internet have been of no help.

  • JTextPane is full??

    Hello,
    I am trying to develop a multi-column text editor. I have a column (derived from JTextPane) with a DefaultStyledDocument in it and I need to know, if the TextPane is full.
    The problem is, that font size and type can vary. There could be images in it too. As the TextPane stands for a column in my Document, it must not scroll.
    If the TextPane is full, I need to instatiate a new one.
    How can I determine, when it is completely full????
    I'm glad for any hint!
    Thanks,
    Hendrik
    Here is the code for the column:
    * Created on 12.02.2004
    * To change the template for this generated file go to Window - Preferences -
    * Java - Code Generation - Code and Comments
    package view;
    import java.awt.Dimension;
    import java.awt.Insets;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import javax.swing.JTextPane;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.html.HTMLEditorKit;
    * @author Administrator
    * To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Generation - Code and Comments
    public class Column extends JTextPane implements CaretListener {
         private static final int height = 698;
         private int width;
         private int id;
         private DefaultStyledDocument doc;
         private HTMLEditorKit kit;
         private OutputStream os;
         private FileOutputStream fos;
         private static final String fileLoc = "c:/_testDoc.out";
         public Column(int id, DefaultStyledDocument doc, int width) {
              super(doc);
              this.doc = doc;
              this.width = width;
              this.kit = new HTMLEditorKit();
              this.init();
         public int getId() {
              return this.id;
         public boolean isFull() {
              out.say(this, super.getHeight());
              if (this.getHeight() > height)
                   return true;
              else
                   return false;
         public void init() {
              this.setPreferredSize(new Dimension(this.width, height));
              this.setMaximumSize(new Dimension(this.width, height));
              this.setCaretPosition(0);
              this.setMargin(new Insets(0, 0, 0, 0));
              this.setSize(new Dimension(width, height));
              this.addCaretListener(this);
         public void writeHTMLFile() {
              try {
                   this.kit.install(this);
                   fos = new FileOutputStream(new File(fileLoc));
                   os = new BufferedOutputStream(fos);
                   this.kit.write(os, doc, 1, doc.getLength());
                   this.kit.deinstall(this);
              } catch (Exception e1) {
                   out.say(this, "nothing written to file " + fileLoc);
         * (non-Javadoc)
         * @see javax.swing.event.CaretListener#caretUpdate(javax.swing.event.CaretEvent)
         public void caretUpdate(CaretEvent e) {
              if (isFull()) {
                   out.say(this, "Column " + this.getId() + " is full!");

    Try this example.
    regards,
    Stas
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.event.*;
    class Test {
        JTextPane edit;
        public static void main(String[] args) {
            System.out.println(Test.class.getResource("Test.class"));
            new Test();
        public Test() {
          JFrame frame=new JFrame("Test multi column");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().setLayout(new BorderLayout());
          edit=new JTextPane();
          JScrollPane scroll=new JScrollPane(edit);
          edit.setEditorKit(new NewEditorKit());
          try {
          edit.getDocument().insertString(0,"11111111112222222222333333333344444444445555555555566666666666777777777777888888888888999999999999",null);
          catch (Exception ex) {}
          frame.getContentPane().add(scroll);
          frame.setBounds(100,100,300,300);
          frame.show();
    class tf extends JTextField {
    class NewEditorKit extends StyledEditorKit {
    public ViewFactory getViewFactory(){
    return new MultiColumnViewFactory();
        class MultiColumnViewFactory implements ViewFactory {
            public View create(Element elem) {
             String kind = elem.getName();
             if (kind != null) {
              if (kind.equals(AbstractDocument.ContentElementName)) {
                        return new LabelView(elem);
              } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                  return new MultiColumnParagraphView(elem);
    //              return new ParagraphView(elem);
              } else if (kind.equals(AbstractDocument.SectionElementName)) {
                  return new BoxView(elem, View.Y_AXIS);
              } else if (kind.equals(StyleConstants.ComponentElementName)) {
                  return new ComponentView(elem);
              } else if (kind.equals(StyleConstants.IconElementName)) {
                  return new IconView(elem);
             // default to text display
                return new LabelView(elem);
    class MultiColumnParagraphView extends ParagraphView {
      int curWidth=0;
      int curHeight=0;
      public MultiColumnParagraphView(Element elem) {
        super(elem);
      protected void layout(int width, int height) {
        super.layout(width/3,height);
        curWidth=width/3;
      protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
        if (axis==View.Y_AXIS) {
          super.layoutMajorAxis(targetSpan,axis,offsets,spans);
          int n=offsets.length;
          int allSpan=offsets[n-1]+spans[n-1];
          int ts=allSpan/3;
          int offset=0;
          for (int i=0; i<n; i++) {
             if (offset>=ts) offset=0;
             offsets=offset;
    offset+=spans[i];
    else {
    super.layoutMajorAxis(targetSpan,axis,offsets,spans);
    protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
    if (axis==View.X_AXIS) {
    super.layoutMinorAxis(targetSpan,axis,offsets,spans);
    int n=offsets.length;
    int t=n/3;
    double tt=n;
    tt/=3;
    if ((tt-t)!=0) t++;
    System.err.println("t="+t+" n="+n+" tt="+tt);
    for (int i=0; i<n; i++) {
    if(i+1>t) offsets[i]+=curWidth;
    if(i+1>2*t) offsets[i]+=curWidth;
    else {
    super.layoutMinorAxis(targetSpan,axis,offsets,spans);

  • JTextPane and HTML form

    I'd like to display html page containing simple HTML form. JTectPane renders tis form very good but i sthere any way to handle any data change/submit on such a form in JTextPane

    Hi,
    Take a look at this example
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    public class TestShowPage {
    public static void main(String args[]) { 
    JTextPane tp = new JTextPane();
    JScrollPane js = new JScrollPane();
    js.getViewport().add(tp);
    JFrame jf = new JFrame();
    jf.getContentPane().add(js);
    jf.pack();
    jf.setSize(400,500);
    jf.setVisible(true);
    try {
    URL url = new URL("http://www.globalleafs.com/Download.html" );
    tp.setPage(url);
    catch (Exception e) {
    e.printStackTrace();
    Just compile and run the programme. see the output. If you need more info of such type of programmes, check http://www.globalleafs.com/Download.html
    Uma
    Java Developer
    http://www.globalleafs.com

  • Word count and my ActionPerformed

    I am having a little trouble with my program and was wondering if anyone could spot the mistake... I am trying to make a simple application that will count the number of words in a text field via click of a button and display the results.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class WordCount extends JFrame implements ActionListener
    // added JTextPane, JScrollPane, JPanel JTextField, and JButton
        public static void main(String[] args)
         // layout
        public WordCount()
              super();
              Container cp = getContentPane();
              wordCount.setEditable(false);
              south.setLayout(new FlowLayout(FlowLayout.CENTER));
              south.add(jbtCount);
                   jbtCount.addActionListener (this);
              south.add(new JLabel("  Word Count: "));
              south.add(wordCount);
              cp.add(BorderLayout.CENTER,jsPane);
              cp.add(BorderLayout.SOUTH,south);
         public void actionPerformed(ActionEvent e)
              //if(e.getSource() == jbtCount)   // user clicks Count Words Button
              Object s = e.getSource();
             if ( s instanceof Button )
                  jtPane.setDocument(new DefaultStyledDocument() {
                        public void insertString(int offset, String str, AttributeSet as) throws BadLocationException
                           super.insertString(offset,str,as);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                           wordCount.setText("" + countValid(tokens));
                         public void remove(int offset, int len) throws BadLocationException
                           super.remove(offset,len);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                             wordCount.setText("" + countValid(tokens));
                  else{}
         } // end actionPerformed
         private int countValid(String[] tokens)
              int count = 0;
             for (int i = 0; i < tokens.length; i++)
                    if (tokens.trim().length() != 0)
              count++;
         return count;
    } // end public class WordCount

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class WordCount extends JFrame implements ActionListener
         JTextPane jtPane = new JTextPane();
         JScrollPane jsPane = new JScrollPane(jtPane);
         JPanel south = new JPanel();
         JTextField wordCount = new JTextField(20);
         JButton jbtCount = new JButton("Count Words");
        public static void main(String[] args)
              int width = 700;
              int height = 300;
               WordCount f = new WordCount();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             f.setSize(width, height);
             f.setTitle("Word Counter");
             f.setLocation(200, 200);
             f.setVisible(true);
        public WordCount()
              super();
              Container cp = getContentPane();
              wordCount.setEditable(false);
              south.setLayout(new FlowLayout(FlowLayout.CENTER));
              south.add(jbtCount);
                   jbtCount.addActionListener (this);
              south.add(new JLabel("  Word Count: "));
              south.add(wordCount);
              cp.add(BorderLayout.CENTER,jsPane);
              cp.add(BorderLayout.SOUTH,south);
         public void actionPerformed(ActionEvent e)
              //if(e.getSource() == jbtCount)   // user clicks Count Words Button
              Object s = e.getSource();
                  // *** process Button actions
            if ( s instanceof Button )
                  jtPane.setDocument(new DefaultStyledDocument() {
                        public void insertString(int offset, String str, AttributeSet as) throws BadLocationException
                           super.insertString(offset,str,as);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                           wordCount.setText("" + countValid(tokens));
                         public void remove(int offset, int len) throws BadLocationException
                           super.remove(offset,len);
                           String text = jtPane.getText();
                           String[] tokens = text.split(" ");
                             wordCount.setText("" + countValid(tokens));
                  else{}
         }// end actionPerformed
         private int countValid(String[] tokens)
              int count = 0;
             for (int i = 0; i < tokens.length; i++)
                    if (tokens.trim().length() != 0)
              count++;
         return count;
    } // end public class WordCount

  • Same Image every time in JTextField with HTMLEditorKit and HTMLDocument

    Hi all
    I have a JTextPane with HTMLEditorKit as editorkit and HTMLDocument as document. I am trying to load an html file into the text pane. the html file contains image. When loading first time it is shown perfectly. After I change the image file with other file with the same name(overwrite it) and trying to load the html file again,the image is the first time loaded image. As i think the image is kept somewhere in "cash" or kind of that. But I need to refresh the html every time it is loaded and not to read from "cash".
    And code which i use:
    package client.temp;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    public class TestPanel extends JPanel {
    public TestPanel(File htmlFile) {
    JTextPane textPane = new JTextPane();
    JScrollPane scrollPane = new JScrollPane();
    HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
    HTMLDocument htmlDocument = new HTMLDocument();
    setLayout(new BorderLayout());
    scrollPane.getViewport().add(textPane, null);
    add(scrollPane, BorderLayout.CENTER);
    URL baseUrl = null;
    try {
    baseUrl = htmlFile.getParentFile().toURL();
    } catch (MalformedURLException e) {
    e.printStackTrace();
    htmlDocument.setBase(baseUrl);
    textPane.setEditorKit(htmlEditorKit);
    try {
    FileInputStream fi = new FileInputStream(htmlFile);
    InputStreamReader isr = new InputStreamReader(fi, "UTF8");
    BufferedReader r = new BufferedReader(isr);
    htmlEditorKit.read(r, htmlDocument, 0);
    r.close();
    isr.close();
    fi.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (BadLocationException e) {
    e.printStackTrace();
    textPane.setDocument(htmlDocument);
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton b = new JButton();
    b.setText("push");
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    TestPanel panel = new TestPanel(new File("c:\\temp\\temp.html"));
    JFrame fShow = new JFrame();
    fShow.getContentPane().setLayout(new BorderLayout());
    fShow.getContentPane().add(panel, BorderLayout.CENTER);
    fShow.setSize(800, 600);
    fShow.setVisible(true);
    frame.getContentPane().add(b);
    frame.pack();
    frame.setVisible(true);
    and here is the html file structure of my temp.html file
    <html>
    <body>
    <p>
    <img src='image01.jpg'>
    </p>
    </body>
    </html>
    the folder in which the temp.html located (in my case c:\\temp\\) contains image01.jpg file too.
    The piece above works correctly when clicking on the button first time.i.e. shows the image01.jpg correctly. After closing the showing frame fShow(not exiting application) and replacement of the image01.jpg by other file named image01.jpg, but with other content and clicking button again shows the first image again.If I exit the application and start again the picture is shown correctly.
    I need this because I am getting images from database while the template is same always.
    Thanks in advance.

    URL baseUrl = null;
    try {
    baseUrl = htmlFile.getParentFile().toURL();
    } catch (MalformedURLException e) {
    e.printStackTrace();
    htmlDocument.setBase(baseUrl);All you want is to defeat the cache. You could do it using random number generation.
    String newURL = htmlFile.getParentFile().toURL().toString();
    String rand = "rand="+new java.utl.Random().nextLong();
    if ( newURL.indexOf("?")>=0)
    newURL +="&"+rand;
    else
    newURL +="?"+rand;
    baseURL = new URL(newURL);
    htmlDocument.setBase(baseURL);
    This will ensure that u are using different url everytime.(well mostly!)

Maybe you are looking for