Tables in JTextPane

Hello dear Java Developers,
i have one question about how to visualize an editable Table on a JTextPane. I Know i can input HTML-Code in a JTextPane and it can display all HTMl Components like Images and Tables, but i need generate a table without HTML. My JTextPane has a DefaultStyledDocument in it and i basically know how to actually draw a Table inside the JTextPane.
To insert an Element, which represents the table, into the Document my Code looks like this:
MyTable table = new MyTable(rows, cols); //MyTable is just the logical representation of a table (rowCount, columnCount, etc ...)
try
Style st = target.addStyle("table", null);
((MutableAttributeSet)st).addAttribute(AbstractDocument.ElementNameAttribute, TableElementName); //TableElementName is a static constant
((MutableAttributeSet)st).addAttribute(StyleConstants.NameAttribute, table);
target.insertString(position, " ignored string ", st); //target is an instance of StyledDocument
After i do that my ViewFactory produces the view for this table:
public View create(Element elem)
String kind = elem.getName();
if (kind.equals(TableElementName)) //if its my previously created TableElement
MyTableView tbv = new MyTableView(elem, View.Y_AXIS); //create MyTableView
return tbv;
return super.create(elem);
My TableView is a BoxView and it contains other BoxViews, which represent Rows and Cells. Each CellView draws a border on its boundaries to visualize the table border. The result inside the JTextPane looks like this: http://img571.imageshack.us/i/tablei.png/
Now i can only type text before or after that table, but i want to be able to type inside each cell, and obviously i cant do it if i have one View for all cells. The Document of the JTextPane contains all the text elements and the tableview is just one element, something like a char or so, and i can only place the caret either before or after the table.
My idea now is to realize one simply cell: i want to be able to draw borders around a specific editable textpart and maybe change the background color, just the usual table stuff. But i don't know how to realize that. Are here any experienced developers who can give me a hint or a simple example for my problem?
I know that the HTMLEditorKit has the function
insertHTML(HTMLDocument doc, int offset, String html, int popDepth, int pushDepth, HTML.Tag insertTag)
i tried to use this function and to debug it to see how they realize a tableview but it is based on HTML and also it's way to complicated and it blew up my head.
thanks in advance

Honestly i dont really know if its possible to display tables by inserting HTML-Code inside the JTextPane, but i know that it is possible to display editable tables inside the JTextPane.
The open source projekt http://shef.sourceforge.net/ gives an implementation of a Wysiwyg HTML Editor. Tables with borders work very good there, but it makes use of the HTMLEditorKit (see the function insert( ... ) above). This application uses a JEditorPane, i use a JTextPane (subclass of JEditorPane) so i should be able realize tables.
My application is not related to HTML in any kind and i use my own EditorKit and ViewFactory. All i want to do is display is a simple cell with border and being able to type text inside that cell. Fact is my StyledDocument (DefaultStyledDocument to be correct) has a Tree of Elements, the LeafElements will be displayed. Right now my TableView is a LeafElement and i can't place the carret inside a LeafElement. Somehow i have to tell the Document that the Cell is a branch element abd to draw a border around it, but i don't know how to do that because it is so poorly documented and i don't know where to find example code.

Similar Messages

  • How to insert a table in JTextPane("text/html")....

    How to insert a table in JTextPane(with contentType(text/html))....like we insert bold/italics etc..AND when I retrieve the contents using getText(),I should be able to get the html tags for table.........!!!
    Anyone Anywhere with solution..???

    -------

  • Insert HTML table into JTextPane

    hi people!
    I'm inserting htmltable in JTtextPane.
    The problem is, that borders aren't shown.
    they are shown in browser, the code in source view is also valid, but in JTextPane they ar invisible. Can anyone tell me Why?
    Here is a piece of code:
    public class HtmlTable {
    public static String insertTableString(int rows, int columns) {
    String tableString="<TABLE Width=100% Border=1>";
    for (int i=0; i<rows; i++) {
    tableString+="<TR>";
    for (int j=0; j<columns; j++)
    tableString+="<TD> </TD>";
    tableString+="</TR>";
    tableString+="</TABLE>";
    return tableString;
    call of this method:
    HTMLEditorKit kit;
    HTMLDoc=(HTMLDocument)editorTextPane.getStyledDocument();
    kit=(HTMLEditorKit)editorTextPane.getEditorKit();
    kit.insertHTML(HTMLDoc,editorTextPane.getCaretPosition(),HtmlTable.insertTableString(HtmlTable.getRowNumber(), HtmlTable.getColumnNumber()),0,0,HTML.Tag.TABLE);

    no Java code involved, just HTML and CSS
    <HTML>
    <HEAD>
    <style type="text/css">
    td {border-top-width:1pt; border-style:solid; }
    </style>
    </HEAD>
    <BODY>
    <p>
    Your Table goes here
    </p>
    <table>
    <tr>
    <td><p>Row 1 Col 1</p></td>
    <td><p>Row 1 Col 2</p></td>
    </tr>
    <tr>
    <td><p>Row 2 Col 1</p></td>
    <td><p>Row 2 Col 2</p></td>
    </tr>
    </table>
    </BODY>
    </HTML>

  • Tables in JTextPane (colored borders)

    I am working on an html Editor.
    I try to insert a table, i use the class Action, like you can see just down.
    i succeed in inserting rows and cells but i failed in having a border in my table.
    I share my editor iin two parts : edition and source where i can see the relevant html source. When i see the relevant html source and change it to insert colored borders, there are not consequences in the editing part (on the HTML Document). Why??
    HashMap _editActionMap= new HashMap();
    Action[] action = kit.getActions();
    int ind = 0;
    for ( int iIndex = 0; iIndex < action.length; iIndex ++ ) {              
    _editActionMap.put( action[iIndex].getValue( Action.NAME ), action[iIndex] );
    ind++;
    JButton table = new JButton("InsertTable");
    table = toolbarEdition.add( (Action)_editActionMap.get("InsertTable"));
    toolbarEdition.add(table);
    JButton tableRow = new JButton("insert row");
    tableRow = toolbarEdition.add( (Action)_editActionMap.get("InsertTableRow"));
    toolbarEdition.add(tableRow);
    JButton tableCell = new JButton("insert data");
    tableCell = toolbarEdition.add( (Action)_editActionMap.get("InsertTableDataCell"));
    toolbarEdition.add(tableCell);

    Honestly i dont really know if its possible to display tables by inserting HTML-Code inside the JTextPane, but i know that it is possible to display editable tables inside the JTextPane.
    The open source projekt http://shef.sourceforge.net/ gives an implementation of a Wysiwyg HTML Editor. Tables with borders work very good there, but it makes use of the HTMLEditorKit (see the function insert( ... ) above). This application uses a JEditorPane, i use a JTextPane (subclass of JEditorPane) so i should be able realize tables.
    My application is not related to HTML in any kind and i use my own EditorKit and ViewFactory. All i want to do is display is a simple cell with border and being able to type text inside that cell. Fact is my StyledDocument (DefaultStyledDocument to be correct) has a Tree of Elements, the LeafElements will be displayed. Right now my TableView is a LeafElement and i can't place the carret inside a LeafElement. Somehow i have to tell the Document that the Cell is a branch element abd to draw a border around it, but i don't know how to do that because it is so poorly documented and i don't know where to find example code.

  • How to insert row in usercreat table(useing HTML tags)in jtextPane

    hi all
    i creat userdefined table in JTextPane like this
    tableBody.toString() -- iam passeing table tags
    htmlKit.insertHTML(htmlDoc, caretPos, tableBody.toString(), 0, 0, HTML.Tag.TABLE);
    i want to insert a row in table.. i did like this
    htmlKit.insertHTML(htmlDoc, caretPos, sRow.toString(), 0, 0, HTML.Tag.TR); it working..
    but it inserting in current location.. i want to insert ending of table...
    pls help me

    Hi,
    Follow the below logic,
    PROCESS BEFORE OUTPUT.
      MODULE STATUS_0001.
      MODULE POPULATE_TABLE_CONTROL. --> Get the data from table store in 
                                                                          ITAB
      LOOP AT GT_CTRL_LP_D516 INTO GS_WA_CTRL_LP_D516
           WITH CONTROL CTRL_LP_D516
           CURSOR CTRL_LP_D516-CURRENT_LINE.
      The following module moves data to control
        MODULE MOVE_TO_CONTROL.--> Move data from ITAB to table control
      ENDLOOP.
    PROCESS AFTER INPUT.
      LOOP AT GT_CTRL_LP_D516.
      ENDLOOP.
      MODULE EXIT AT EXIT-COMMAND.
      MODULE USER_COMMAND_0001.  --> Here you have to take out the values from table control and update database table
    Reward points if helpful.
    Thanks and regards,
    Mallareddy Rayapureddy,
    Munich, Germany.

  • Problen in appearing  Jtable in JTextPAne ???

    Hi. to all,
    In thiscode i try to appear table in JTextPane .. There is a button "table" when you press on it the JDilog will appear in it you can specify the number of row and column to design the table ..... then when you press applay in JDilog the table should appear
    There is my try but it has error can't adjust it please any one tell me the correct way :
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextPane;
    public class Table extends JFrame {
        private JTextPane textPane=new JTextPane();
        private JButton tableButton=new JButton("Table");
        private JPanel mainPanel=new JPanel();
        public Table(){
            mainPanel.setLayout(new BorderLayout());
            mainPanel.add(tableButton,BorderLayout.NORTH);
            tableButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                       new TableTest().setVisible(true);
                       textPane.setText(new TableTest().myTable);    // This ie error but i can not the way to set table in textpane
            mainPanel.add(textPane,BorderLayout.CENTER);
            getContentPane().add(mainPanel);
        public static void main(String[]args){
            Table table=new Table();
            table.setDefaultCloseOperation(Table.EXIT_ON_CLOSE);
            table.setSize(new Dimension(500,250));
            table.setLocationRelativeTo(null);
            table.setVisible(true);
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.event.ActionListener;
    import java.util.Hashtable;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JSpinner;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.border.TitledBorder;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableModel;
    public class TableTest extends JDialog {
        private JSpinner rowSpinner, colSpinner;
        private Box mainBox, rowSpinnerBox, colSpinnerBox;
        private JLabel rowLabel, columnLabel;
        private JTextField rowField, colField;
        private TitledBorder titledBorder;
        private JButton okButton,cancelButton;
        public TableModel myTable;
        private int[] row;
        private int[] col;
        public TableTest() {
            intializeSpinner();
            intializeBox();
            intializeLabel();
            intializeTextField();
            intializeButton();
            designView();
            row = (int[]) rowSpinner.getValue();
            col = (int[]) colSpinner.getValue();
            myTable = new TableModelTest(row, col);
            JTable table = new JTable(myTable);
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(mainBox);
            getContentPane().add(scrollPane);
        private void intializeSpinner() {
            rowSpinner = new JSpinner();
            rowSpinner.setPreferredSize(new Dimension(100, 15));
            rowSpinner.setMaximumSize(new Dimension(100, 15));
            colSpinner = new JSpinner();
            colSpinner.setPreferredSize(new Dimension(100, 15));
            colSpinner.setMaximumSize(new Dimension(100, 15));
        private void intializeBox() {
            titledBorder = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 3), "Insert table");
            mainBox = Box.createVerticalBox();
            mainBox.setBorder(titledBorder);
            rowSpinnerBox = Box.createHorizontalBox();
            colSpinnerBox = Box.createHorizontalBox();
        private void intializeLabel() {
            rowLabel = new JLabel("Insert row       :");
            columnLabel = new JLabel("Insert column :");
        private void intializeTextField() {
            rowField = new JTextField();
            rowField.setPreferredSize(new Dimension(100, 15));
            rowField.setMaximumSize(new Dimension(100, 15));
            colField = new JTextField(10);
            colField.setPreferredSize(new Dimension(100, 15));
            colField.setMaximumSize(new Dimension(100, 15));
        public void intializeButton(){
            okButton=new JButton("ok");
            cancelButton=new JButton("cancel");
        public void okButtonAddActionListener(ActionListener listener){
            okButton.addActionListener(listener);
        private void designView() {
            rowSpinnerBox.add(rowLabel);
            rowSpinnerBox.add(Box.createHorizontalStrut(5));
            rowSpinnerBox.add(rowField);
            rowSpinnerBox.add(Box.createHorizontalStrut(5));
            rowSpinnerBox.add(rowSpinner);
            //   rowSpinnerPanel.add(Box.createHorizontalGlue());
            colSpinnerBox.add(columnLabel);
            colSpinnerBox.add(Box.createHorizontalStrut(5));
            colSpinnerBox.add(colField);
            colSpinnerBox.add(Box.createHorizontalStrut(5));
            colSpinnerBox.add(colSpinner);
            //  colSpinnerPanel.add(Box.createHorizontalGlue());
            mainBox.add(rowSpinnerBox);
            mainBox.add(Box.createVerticalStrut(5));
            mainBox.add(colSpinnerBox);
            mainBox.add(Box.createVerticalGlue());
        class TableModelTest extends AbstractTableModel {
            public Hashtable lookUp;
            public int rows;
            public int columns;
            public int[] columnNames;
            public TableModelTest(int[] rows, int[] colNames) {
                this.rows = rows.length;
                this.columns = colNames.length;
                lookUp = new Hashtable();
                // this.columnNames = new int[columns];
                //  System.arraycopy(colNames, 0, this.columnNames, 0, columns);
            public int getRowCount() {
                return rows;
            public int getColumnCount() {
                return columns;
            public Object getValueAt(int rowIndex, int columnIndex) {
                return lookUp.get(new Point(rowIndex, columnIndex));
    }thanks in advance

    In thiscode i try to appear table in JTextPane Basically you add the component throught the JTextPane model which is the document; the new style contain the table as an attribute and registered with StyleConstants
    try this ( not tested)
    StyleContext context = new StyleContext();
        StyledDocument document = new DefaultStyledDocument(context);
        Style tableStyle = context.getStyle(StyleContext.DEFAULT_STYLE);
        TableModel model = new DefaultTableModel( new Object[]{"col1", "col2"}, 2);
        JTable table = new JTable(model);
        StyleConstants.setComponent(tableStyle, table);
        try {
          document.insertString(document.getLength(), "this will not show", tableStyle );
        } catch (BadLocationException badLocationException) {
          System.err.println("Oops");
        JTextPane textPane = new JTextPane(document);
        textPane.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textPane);Why you do not build an html page which contains the table and set the text on the JTextPane to this page( String); then add hyperlinkListener so that you can rebuild the html table upon an predefined different links inside the html table
    Hope this could help. Please give me a shout in case you need further help
    Regards,
    Alan Mehio
    London,UK

  • RTFEditorKit isn't casting with TableEditorKit

    Hi,
    I am preparing RTFEditor. I did paging and other properties (bullet, numbered etc.) but I can't use table on jtextpane. I'm postin my Codes below.
    my call button Codes:
    private void mnTabloEkleActionPerformed(java.awt.event.ActionEvent evt) {
          TableEditorKit  ourKit = (TableEditorKit) m_monitor.getEditorKit(); // editorkit get edildiðinde ise çalýþmýyor.
          TableDocument myDoc = (TableDocument) m_monitor.getDocument();// bu olamszsa tabloyu koymuyor.
            myDoc.insertTable(0, 2, new int[] {200, 100, 150});
            myDoc.insertTable(4, 2, new int[] {100, 50});
            try {
                myDoc.insertString(10, "Paragraph after table.\nYou can set caret in table cell and start typing.", null);
                myDoc.insertString(4, "Inner Table", null);
                myDoc.insertString(3, "Cell with a nested table", null);
                myDoc.insertString(0, "Table\nCell", null);
            catch (BadLocationException ex) {
                ex.printStackTrace();
    }my TableEditorKit's Code:
    package editor.page;
    import dys.javax.swing.text.rtf.RTFEditorKit;
    import javax.swing.text.*;
    * @author Administrator
    public class TableEditorKit extends RTFEditorKit {
        ViewFactory defaultFactory = new PageableEditorKit().getViewFactory();  //bu alaný commentlediðimizde yazý çýkýyor,
                                                                                //tablo çýkmýyor sayfa geniþliyor.
        public ViewFactory getViewFactory() {
            return defaultFactory;
        public Document createDefaultDocument() {   //bu alaný commentlediðimizde yazý ve tablo
                                                     //çýkmýyor sadece sayfa orjinal haline yakýn bir þekilde duruyor.
            return new TableDocument();
    at last my RTFfEditorKid's Code:
    package editor.page;
    import java.awt.*;
    import java.awt.print.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.geom.AffineTransform;
    import javax.swing.event.*;
    import dys.javax.swing.text.rtf.RTFEditorKit;
    public class PageableEditorKit extends RTFEditorKit {
        PageableViewFactory factory = new PageableViewFactory();
        private JTextPane editor = null;    //  w = 72 * 8.5 = 612    (inch = 72 )
        public static int DRAW_PAGE_INSET_TOP = 20;
        public static int DRAW_PAGE_INSET_LEFT = 10;    //public static int DRAW_PAGE_INSET_TOP = 0;
        protected int pageWidth = 730;
        protected int pageHeight = 940;
        public static String PAGE_BREAK_ATTR_NAME = "page_break_attribute";
        protected Insets pageMargins = new Insets(100, 125, 100, 125); //protected Insets pageMargins = new Insets(0, 0, 0,0);
        protected JTextPane header;
        protected JTextPane footer;
        public boolean isChangeSize = false;
        private boolean isValidHF;
        public static int HF_SHIFT = 3;
        boolean isPageBreakInsertion = false;
        public boolean isHeaderFooter = false;
        public final PaginationPrinter pp; // = new PaginationPrinter(pf, editor);
        protected float headerOrjHeight = 22;
        protected float headerOrjWidth = 100;
        protected float footerOrjHeight = 22;
        protected float footerOrjWidth = 100;
        public boolean refresh = false;
        protected Rectangle edtGorunenAlan;
        public int actifPage = 0;
        protected int hfTiklananPage = 0;
        DocumentListener relayoutListener = new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                relayout();
            public void removeUpdate(DocumentEvent e) {
                relayout();
    ....

    when I wrote this code:
    TableEditorKit  ourKit = (TableEditorKit) m_monitor.getEditorKit();I am taking error bellow.
    Exception in thread "AWT-EventQueue-1" java.lang.ClassCastException: editor.page.PageableEditorKit cannot be cast to editor.page.TableEditorKit
            at editor.Editor.mnTabloEkleActionPerformed(Editor.java:2014)
            at editor.Editor.access$5200(Editor.java:122)
            at editor.Editor$51.actionPerformed(Editor.java:1038)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
            at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1170)
            at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1211)
            at java.awt.Component.processMouseEvent(Component.java:6038)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)Edited by: selcukyapici on Jun 21, 2009 11:33 PM

  • Paint JTextPane on top of table using paintComponent?

    I have a JTable inside a JScrollPane which draws up a grid. In my application the table serves as a background. The best analogy is that this would be much like you might imagine a game board as a background for the game pieces on top.
    The application isn't a game, but to continue using my example, the components or game pieces are represented by JTextPane objects. These components will reside in different locations on top of the table. They can't be rendered within the table because they often span columns and rows. Additionally, even though they always start at the top of a row grid line, they don't necessarily end at the bottom of one.
    So I was wondering if there is a way to manually paint them. I envisioned that I would override the JTable or the JScrollPane paintComponent method but I am not sure how. Here is what I was thinking:
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    for (JTextPane myComponent : components)
    SwingUtilities.paintComponent(this.getGraphics(), appointmentComponent, this ,
    (int)startingLocation.getX(), (int)startingLocation.getY(),width, height);
    Of course this doesn't work. But is there a way I can draw a JTextPane or any component in an arbitrary location on top of a container of some sort?
    thanks

    Thanks, such a simple solution, I don't know why I didn't start with this, for some reason I decided a layered pane wouldn't work.
    So I added the JLayeredPane as the viewportview of the JScrollPane. Then I added the table to the layered pane and the objects go on the next layer and work great.

  • ComponentView does not redraw component in JTextPane Cell Rend

    We have created a JTable implementation that uses JTextPanes as cell renderers/editors so that text styles and the like are available. We want insert a component, such as a JButton, into the JTextPane. However, the component is only visible when the cell is in an editable state. In the renderer, the ComponentView looks like it has set aside the space where the component is to be, but the component is not visible.
    I have looked at this problem for several days now, and have only determined that this seems to be occuring at a low level. What I have found is that the ButtonUI's update method is not called when the document is in the cell renderer, while it seems called continuously in the cell editor (on each caret blink).
    Does anybody have any insight as to the problem? I have submitted this as a bug to Sun but wanted to find out if anybody else has come across anything similar to this.
    Thank for any help.
    Steve Feveile
    Here is sample code to reproduce the problem:
    // Main Class
    * Main frame for the testing of the component not painting. This simplifies
    * an issue we have come across when trying to set up using a JTextPane as a
    * renderer/editor as the cells in a table.
    * Under these conditions we have found that a component inserted into the JTextPanes document
    * only appears in the editing state of the cell, whereas the rendering state leaves
    * the spacing for the component but does not make it visible.
    * Note that creating a JTextPane with the one of these documents will show the component,
    * even when not editing.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class tableFrame extends JFrame
         public tableFrame()
              //set up frame
              getContentPane().setLayout(new BorderLayout());
              setSize(500,300);
              setTitle("Table Missing Component Test");
    addWindowListener(
         new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                             setVisible(false);                         
                   System.exit(0);     
              //set up components the table
              JTable table = new JTable(createDocumentTableModel(2,2));
              table.setRowHeight(60);
              //set the default renderer/editor to use the JTextPane implementation
              for (int x = 0; x < table.getColumnCount(); x++) {
                   table.setDefaultEditor(table.getColumnClass(x), new TextPaneCellEditor());
                   table.setDefaultRenderer(table.getColumnClass(x), new TextPaneRenderer());
              JScrollPane pane = new JScrollPane(table);
              getContentPane().add(pane, BorderLayout.CENTER);
              //this adds a textpane without the table involved
              //uising the same way of inserting a document
              JTextPane tPane = new JTextPane();
              DefaultStyledDocument doc = new DefaultStyledDocument();
              try
                   doc.insertString(0, "Some text in a JTextPane", null);
                   JButton b = new JButton("Button");
         SimpleAttributeSet inputAttributes = new SimpleAttributeSet();
              StyleConstants.setComponent(inputAttributes, b);
              doc.insertString(0 , " ", inputAttributes);
              catch (Throwable t)
                   System.out.println("createDocumentTableModel error: " + t.getMessage());
              tPane.setDocument(doc);
              tPane.setSize(490, 60);
              JScrollPane pane2 = new JScrollPane(tPane);
              getContentPane().add(pane2, BorderLayout.SOUTH);
         * this creates a table model where the documents are the value
         * in each cell, and the cell renderer/editor can use this instead
         * of a string value
         private TableModel createDocumentTableModel(int row, int col)
              Vector headerData = new Vector();
              Vector tableData = new Vector();
              for (int i=0;i<row;i++)
                   headerData.add("Column" + i);
                   Vector rowData = new Vector();
                   for (int j=0;j<col;j++)
                        DefaultStyledDocument doc = new DefaultStyledDocument();
                        try
                             //this inserts some string to see that this is visible
                             //when editing and rendering
                             doc.insertString(0, ("Row: " + i + ", Column: " + j), null);
                             //this button will only be visible when the cell is in
                             //an editing state
                             JButton b = new JButton("Button" + i + "-" + j);
                   SimpleAttributeSet inputAttributes = new SimpleAttributeSet();
                        StyleConstants.setComponent(inputAttributes, b);
                        doc.insertString(0 , " ", inputAttributes);
                        catch (Throwable t)
                             System.out.println("createDocumentTableModel error: " + t.getMessage());
                        rowData.add(doc);
                   tableData.add(rowData);
              return new DefaultTableModel(tableData, headerData);
         //starts the ball rolling
         static public void main(String args[])
              (new tableFrame()).setVisible(true);
    // Custom Cell Editor
    * Sets the editor to use a JTextPane implementation
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.util.EventObject;
    import java.io.Serializable;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TextPaneCellEditor implements TableCellEditor
    /** Event listeners */
    protected EventListenerList listenerList = new EventListenerList();
    transient protected ChangeEvent changeEvent = null;
    protected JTextPane editorComponent;
    protected EditorDelegate delegate;
    protected int clickCountToStart = 1;
         * constructor.
    public TextPaneCellEditor() {
              editorComponent = new JTextPane();
              //use 1 click count to edit a cell
              clickCountToStart = 1;
              * controls the values of the editor
              delegate = new EditorDelegate() {
                   * sets the text value cell.
                   * @param value - value to set in the document
                   public void setValue(Object value) {
                        if (value instanceof Document)
                             editorComponent.setDocument((Document) value);
                        else
                             editorComponent.setText("");
                   * gets the text value cell.
                   * @return the document in the textpane
                   public Object getCellEditorValue() {
                        return editorComponent.getDocument();
         // implements the setting the value for the editor
         public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
              if (value != null)          
                   delegate.setValue(value);
              else
                   delegate.setValue("");
              return editorComponent;
    // Implementing the CellEditor Interface
         // implements javax.swing.CellEditor
         public Object getCellEditorValue() {
              return delegate.getCellEditorValue();
         // implements javax.swing.CellEditor
         public boolean isCellEditable(EventObject anEvent) {
              if (anEvent instanceof MouseEvent) {
                   return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
              return true;
    // implements javax.swing.CellEditor
         public boolean shouldSelectCell(EventObject anEvent) {
              return delegate.shouldSelectCell(anEvent);
         // implements javax.swing.CellEditor
         public boolean stopCellEditing() {
              fireEditingStopped();
              return true;
         // implements javax.swing.CellEditor
         public void cancelCellEditing() {
              fireEditingCanceled();
    // Handle the event listener bookkeeping
         // implements javax.swing.CellEditor
         public void addCellEditorListener(CellEditorListener l) {
              listenerList.add(CellEditorListener.class, l);
         // implements javax.swing.CellEditor
         public void removeCellEditorListener(CellEditorListener l) {
              listenerList.remove(CellEditorListener.class, l);
         * Notify all listeners that have registered interest for
         * notification on this event type. The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @see EventListenerList
         protected void fireEditingStopped() {
              // Guaranteed to return a non-null array
              Object[] listeners = listenerList.getListenerList();
              // Process the listeners last to first, notifying
              // those that are interested in this event
              for (int i = listeners.length-2; i>=0; i-=2) {
                   if (listeners==CellEditorListener.class) {
                        // Lazily create the event:
                        if (changeEvent == null)
                             changeEvent = new ChangeEvent(this);
                        ((CellEditorListener)listeners[i+1]).editingStopped(changeEvent);
         * Notify all listeners that have registered interest for
         * notification on this event type. The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @see EventListenerList
         protected void fireEditingCanceled() {
              // Guaranteed to return a non-null array
              Object[] listeners = listenerList.getListenerList();
              // Process the listeners last to first, notifying
              // those that are interested in this event
              for (int i = listeners.length-2; i>=0; i-=2) {
                   if (listeners[i]==CellEditorListener.class) {
                        // Lazily create the event:
                        if (changeEvent == null)
                             changeEvent = new ChangeEvent(this);
                        ((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent);
    // Protected EditorDelegate class
    protected class EditorDelegate implements ActionListener, ItemListener, Serializable {
              //made up of unimplemented methods
              protected Object value;
              public Object getCellEditorValue() {
                   return null;
              public void setValue(Object x) {}
              public void setDocument(Object x) {}
              public Document getDocument() {
                   return null;
              public boolean isCellEditable(EventObject anEvent) {
                   return true;
              /** Unfortunately, restrictions on API changes force us to
              * declare this method package private.
              boolean shouldSelectCell(EventObject anEvent) {
                   return true;
              public boolean startCellEditing(EventObject anEvent) {
                   return true;
              public boolean stopCellEditing() {
                   return true;
                   public void cancelCellEditing() {
              public void actionPerformed(ActionEvent e) {
                   fireEditingStopped();
              public void itemStateChanged(ItemEvent e) {
                   fireEditingStopped();
    // Custom Cell Renderer
    * renders a table cell as a JTextPane.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TextPaneRenderer extends JTextPane implements TableCellRenderer                                                  
         * Constructor - just set to noneditable
         public TextPaneRenderer() {
              setEditable(false);
         * implementation of table cell renderer. If the value is a document
         * the, the text panes setDocument is used, otherwise a string value
         * is set
         public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
              if (value != null)
                   if (value instanceof Document)
                        //set the value to a document
                        setDocument((Document) value);
                   else
                        //convert the value to a string
                        setText(value.toString());
              else
                   //set text to an empty string
                   setText("");
              return this;

    Hi, I came across the forum and found your problem is very similar to what I am having now. Your post has been a year old, I just wonder if you come up anything productive to what you had? Could you let us know what you (or Sun) find out if you do have one? Thanks.

  • How can I print a html table and preview it?

    Hi there!
    Please help me.
    I spent a lot of time to find how to print a html table and preview it.
    I tried use code of the book http://www.manning.com/sbe/ Chapter 22. But this book consists only code for rtf and they change size of JtextPane before printing.
    I have found the bellow code;
    http://forum.java.sun.com/thread.jsp?thread=120578&forum=57&message=316116 But I problems with printing.
    I also found this code; http://forum.java.sun.com/thread.jsp?forum=31&thread=146439
    But there is no code,so i don't understand.
    Can u help me?
    Thanks my friends.

    There is the comp.lang.javacript newsgroup for one:
    http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf-8&group=comp.lang.javascript
    Here are a couple of more candidates I found from google in about two minutes:
    http://www.jguru.com/forums/home.jsp?topic=JavaScript
    http://www.jsworkshop.com/bb/viewforum.php?f=1&sid=524b20160ca47c0ab786214e2003f1d1
    http://javascript.internet.com/forum/
    I am sure there are many more. :)

  • Saving a file from a form to be display on a table

    Hi i'm having some problems trying to save the filled out on the form to be displayed on the table i don't know how i am going to go about it can you please help me thanks.
    Here is the code for the form.
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;              //for layout managers and more
    import java.awt.event.*;        //for action events
    import java.net.URL;
    import java.text.ParseException;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.swing.JComboBox;
    public class DD extends JPanel
                                 implements ActionListener {
        private String newline = "\n";
        protected static final String textFieldString = "Name"; 
        protected static final String textFieldString1 = "Start Time";
        protected static final String textFieldString2 = "End Time";
        protected static final String textFieldString3 = "Total Time(Minutes)";
        protected static final String ftfString = "Date";
        protected static final String buttonString = "JButton";
        JFormattedTextField startTime;
        JTextField totalTime;
        protected JLabel actionLabel;
        Component[][] rowData;
        private String[] shapeName = { "Meeting", "Lunch", "Holiday", "Sickness",
                 "Preparing report", "Administrative work", "Emails", "Query" };
        public DD() {
            setLayout(new BorderLayout());
            Panel data = new Panel();
              data.setLayout(new GridLayout(7, 4));
            rowData = new Component[7][];
    //      One row
                   for (int row = 0; row < 7; row++)
                        rowData[row] = new Component[5];
                        rowData[row][0] = new TextField(10);
                        rowData[row][1] = new TextField(10);
                        ((TextField) rowData[row][1]).addActionListener(this);
                        rowData[row][2] = new JComboBox(shapeName);
                        ((JComboBox) rowData[row][2]).addActionListener(this);
    //      ((TextField)rowData[ row ][ 2 ]).addActionListener(this);
                        rowData[row][3] = new TextField(10);
                        ((TextField) rowData[row][3]).addActionListener(this);
    //      JComboBox jcboxShapeCombo;
    //      System.out.println(rowData[row][2]);
    //      jcboxShapeCombo[2] = new JComboBox (shapeName);
    //      rowData[ row ][ 3 ] = new TextField(10);
                        rowData[row][4] = new TextField(10);
                        ((TextField) rowData[row][4]).addActionListener(this);
                        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
                        ((TextField) rowData[row][0]).setText(sdf.format(new java.util.Date()));
                        data.add(rowData[row][0]);
                        data.add(rowData[row][1]);
                        data.add(rowData[row][2]);
                        data.add(rowData[row][3]);
                        data.add(rowData[row][4]);
            //Create a regular text field.
            JTextField textField = new JTextField(10);
            textField.setActionCommand(textFieldString);
            textField.addActionListener(this);
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
            startTime = new JFormattedTextField(sdf);
            startTime.setValue(new java.util.Date());
            startTime.setActionCommand(textFieldString1);
            startTime.addActionListener(this);
            JTextField textField2 = new JTextField(10);
            textField2.setActionCommand(textFieldString2);
            textField2.addActionListener(this);
            totalTime = new JTextField(10);
            totalTime.setActionCommand(textFieldString3);
            totalTime.addActionListener(this);
            //Create a formatted text field.
            JFormattedTextField ftf = new JFormattedTextField(
                      //java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
                    java.util.Calendar.getInstance().getTime());
            ftf.setActionCommand(textFieldString);
            ftf.addActionListener(this);
            //Create some labels for the fields.
            JLabel textFieldLabel = new JLabel(textFieldString + ": ");
            textFieldLabel.setLabelFor(textField);
            JLabel textFieldLabel1 = new JLabel(textFieldString1 + ": ");
            textFieldLabel1.setLabelFor(startTime);
            JLabel textFieldLabel2 = new JLabel(textFieldString2 + ": ");
            textFieldLabel2.setLabelFor(textField2);
            JLabel textFieldLabel3 = new JLabel(textFieldString3 + ": ");
            textFieldLabel3.setLabelFor(totalTime);
            JLabel ftfLabel = new JLabel(ftfString + ": ");
            ftfLabel.setLabelFor(ftf);
            //Create a label to put messages during an action event.
            actionLabel = new JLabel("Type text in a field and press Enter.");
            actionLabel.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
            //Lay out the text controls and the labels.
            JPanel textControlsPane = new JPanel();
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            textControlsPane.setLayout(gridbag);
            JLabel[]labels = {textFieldLabel, textFieldLabel1,textFieldLabel2, textFieldLabel3, ftfLabel};
            JTextField[] textFields = {textField, startTime,textField2,totalTime, ftf};
            addLabelTextRows(labels, textFields, gridbag, textControlsPane);
            c.gridwidth = GridBagConstraints.REMAINDER; //last
            c.anchor = GridBagConstraints.WEST;
            c.weightx = 1.0;
            textControlsPane.add(actionLabel, c);
            textControlsPane.setBorder(
                    BorderFactory.createCompoundBorder(
                                    BorderFactory.createTitledBorder("Text Fields"),
                                    BorderFactory.createEmptyBorder(5,5,5,5)));
            //Create a text area.
            JTextArea textArea = new JTextArea(
            textArea.setFont(new Font("Serif", Font.ITALIC, 16));
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            JScrollPane areaScrollPane = new JScrollPane(textArea);
            areaScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            areaScrollPane.setPreferredSize(new Dimension(250, 250));
            areaScrollPane.setBorder(
                BorderFactory.createCompoundBorder(
                    BorderFactory.createCompoundBorder(
                                    BorderFactory.createTitledBorder("Comment"),
                                    BorderFactory.createEmptyBorder(5,5,5,5)),
                    areaScrollPane.getBorder()));
            //Create an editor pane.
            JEditorPane editorPane = createEditorPane();
            JScrollPane editorScrollPane = new JScrollPane(editorPane);
            editorScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            editorScrollPane.setPreferredSize(new Dimension(250, 145));
            editorScrollPane.setMinimumSize(new Dimension(10, 10));
            String[] initString =
            { "Meeting", "Lunch", "Holiday", "Sickness",
                     "Preparing report", "Administrative work", "Emails", "Query" };
            JList listCategories = new JList(initString);
            JScrollPane editorScrollPane = new JScrollPane(listCategories);
            editorScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            editorScrollPane.setPreferredSize(new Dimension(250, 145));
            editorScrollPane.setMinimumSize(new Dimension(10, 10));
            //Create a text pane.
            JTextPane textPane = createTextPane();
            JScrollPane paneScrollPane = new JScrollPane(textPane);
            paneScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            paneScrollPane.setPreferredSize(new Dimension(250, 155));
            paneScrollPane.setMinimumSize(new Dimension(10, 10));
            //Put the editor pane and the text pane in a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                                  editorScrollPane,
                                                  paneScrollPane);
            splitPane.setOneTouchExpandable(true);
            splitPane.setResizeWeight(0.5);
            JPanel rightPane = new JPanel(new GridLayout(1,0));
            rightPane.add(splitPane);
            rightPane.setBorder(BorderFactory.createCompoundBorder(
                            BorderFactory.createTitledBorder("Category of Task"),
                            BorderFactory.createEmptyBorder(5,5,5,5)));
            JPanel rightPane = new JPanel(new GridLayout(1,0));
            rightPane.add(editorScrollPane);
            //Put everything together.
            JPanel leftPane = new JPanel(new BorderLayout());
            leftPane.add(textControlsPane,
                         BorderLayout.PAGE_START);
            leftPane.add(areaScrollPane,
                         BorderLayout.CENTER);
            add(leftPane, BorderLayout.LINE_START);
            add(rightPane, BorderLayout.LINE_END);
            JButton button = new JButton("Submit");
            button.setCursor(Cursor.getDefaultCursor());
            //button.setMargin(new Insets(0,0,0,0));
            button.setActionCommand(buttonString);
            button.addActionListener(this);
            add(button, BorderLayout.SOUTH);
            button.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        String toPrint = collectData();
                        newFile(toPrint);
       private String collectData()
              String toPrint = "";
              for (int i = 0; i < rowData.length; i++)
                   Component[] currentRowComps = rowData;
                   for (int j = 0; j < currentRowComps.length; j++)
                        Component currentComp = currentRowComps[j];
                        if (currentComp instanceof TextField)
                             TextField tf = (TextField) currentComp;
                             toPrint += tf.getText() + " - ";
                        else if (currentComp instanceof JComboBox)
                             JComboBox box = (JComboBox) currentComp;
                             Object selection = box.getSelectedItem();
                             if (selection != null)
                                  toPrint += selection.toString() + " - ";
                   toPrint += "\n";
              return toPrint;
         private File newFile(String data)
              File newfile = null;
              try
                   newfile = new File("I:\\ouput.doc");
                   System.out.println("DATA? - " + data);
                   FileOutputStream fos = new FileOutputStream(newfile);
                   fos.write(data.getBytes());
                   fos.close();
                   // JOptionPane.showMessageDialog(null, "Save File");
                   JOptionPane.showMessageDialog(null, "File saved.", "Success",
                   JOptionPane.INFORMATION_MESSAGE);
              catch (IOException ioexc)
                   JOptionPane.showMessageDialog(null, "Error while saving file: " + ioexc,
                   "Error", JOptionPane.ERROR_MESSAGE);
              return null;
    private void addLabelTextRows(JLabel[] labels,
    JTextField[] textFields,
    GridBagLayout gridbag,
    Container container) {
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.EAST;
    int numLabels = labels.length;
    for (int i = 0; i < numLabels; i++) {
    c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
    c.fill = GridBagConstraints.NONE; //reset to default
    c.weightx = 0.0; //reset to default
    container.add(labels[i], c);
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    container.add(textFields[i], c);
    public void actionPerformed(ActionEvent e) {
    String prefix = "You typed \"";
    if (textFieldString2.equals(e.getActionCommand()))
    JTextField source = (JTextField)e.getSource();
    actionLabel.setText(prefix + source.getText() + "\"");
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
    try {
                        java.util.Date end = sdf.parse(source.getText());
                        java.util.Date start = sdf.parse(startTime.getText());
                        long difference = (end.getTime() - start.getTime()) / 60000;
                        totalTime.setText(Long.toString(difference));
                   } catch (ParseException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
    if (textFieldString1.equals(e.getActionCommand()))     {JTextField source = (JTextField)e.getSource();
            actionLabel.setText(prefix + source.getText() + "\"");}
    if (textFieldString2.equals(e.getActionCommand()))     {JTextField source = (JTextField)e.getSource();
            actionLabel.setText(prefix + source.getText() + "\"");}
    if (textFieldString3.equals(e.getActionCommand()))     {JTextField source = (JTextField)e.getSource();
            actionLabel.setText(prefix + source.getText() + "\"");}
    else if (textFieldString.equals(e.getActionCommand())) {
    //JPasswordField source = (JPasswordField)e.getSource();
    //actionLabel.setText(prefix + new String(source.getPassword())
    //+ "\"");
    } else if (buttonString.equals(e.getActionCommand())) {
    Toolkit.getDefaultToolkit().beep();
    private JEditorPane createEditorPane() {
    JEditorPane editorPane = new JEditorPane();
    editorPane.setEditable(false);
    java.net.URL helpURL = DD.class.getResource(
    "DailyDairyDemoHelp.html");
    if (helpURL != null) {
    try {
    editorPane.setPage(helpURL);
    } catch (IOException e) {
    System.err.println("Attempted to read a bad URL: " + helpURL);
    } else {
    System.err.println("Couldn't find file: Daily Dairy.html");
    return editorPane;
         private JTextPane createTextPane() {
    String[] initString =
    { "Meeting", "Lunch", "Holiday", "Sickness",
         "Preparing report", "Administrative work", "Emails", "Query" };
    String[] initStyles =
    { "regular", "italic", "bold", "small", "large",
    "regular", "button", "regular", "icon",
    "regular"
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);
    try {
    for (int i=0; i < initString.length; i++) {
    doc.insertString(doc.getLength(), initString[i],
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    protected void addStylesToDocument(StyledDocument doc) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().
    getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);}
    /*s = doc.addStyle("icon", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon pigIcon = createImageIcon("images/Pig.gif",
    "a cute pig");
    if (pigIcon != null) {
    StyleConstants.setIcon(s, pigIcon);
    s = doc.addStyle("button", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon soundIcon = createImageIcon("images/sound.gif",
    "sound icon");
    JButton button = new JButton();
    if (soundIcon != null) {
    button.setIcon(soundIcon);
    } else {
    button.setText("BEEP");
    button.setCursor(Cursor.getDefaultCursor());
    button.setMargin(new Insets(0,0,0,0));
    button.setActionCommand(buttonString);
    button.addActionListener(this);
    StyleConstants.setComponent(s, button);
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path,
    String description) {
    java.net.URL imgURL = DD.class.getResource(path);
    if (imgURL != null) {
    return new ImageIcon(imgURL, description);
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event dispatch thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("DailyDairyDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Add content to the window.
    frame.add(new DD());
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event dispatching thread:
    //creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    //Turn off metal's use of bold fonts
              UIManager.put("swing.boldMetal", Boolean.FALSE);
              createAndShowGUI();
    And here is the code for the table.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.util.Date;
    import java.sql.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class DDTable extends JFrame{
         protected JTable m_table;
         protected DDTableData m_data;
         protected JLabel m_title;
         public DDTable(){
              super("DDTABLE");
              setSize(600, 300);
              UIManager.put("Table.focusCellHighlightBorder",new LineBorder(Color.black, 0));
              m_data = new DDTableData();
              m_title = new JLabel(m_data.getTitle(), SwingConstants.CENTER);
              m_title.setFont(new Font("Helvetica", Font.PLAIN, 24));
              getContentPane().add(m_title, BorderLayout.NORTH);
              m_table = new JTable();
              m_table.setAutoCreateColumnsFromModel(false);
              m_table.setModel(m_data);
              for (int k = 0; k < m_data.getColumnCount(); k++) {
                   DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
                   renderer.setHorizontalAlignment(DDTableData.m_columns[k].m_alignment);
                   TableColumn column = new TableColumn(k, DDTableData.m_columns[k].m_width, renderer, null);
                   m_table.addColumn(column);
              JTableHeader header = m_table.getTableHeader();
              header.setUpdateTableInRealTime(false);
              setJMenuBar(createMenuBar());
              JScrollPane ps = new JScrollPane();
              ps.getViewport().setBackground(m_table.getBackground());
              ps.getViewport().add(m_table);
              getContentPane().add(ps, BorderLayout.CENTER);
              protected JMenuBar createMenuBar(){
                   JMenuBar menuBar = new JMenuBar();
                   JMenu mFile = new JMenu("File");
                   mFile.setMnemonic('f');
                   Action actionNew = new AbstractAction("New Appointment"){
                        public void actionPerformed(ActionEvent e){
                             if (!promptToSave())
                                  return;
                             newDocument();
                        JMenuItem item = new JMenuItem(actionNew);
                        item.setMnemonic('n');
                        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
                        mFile.add(item);
                        Action actionSave = new AbstractAction("Save Appointment"){
                             public void actionPerformed(ActionEvent e){
                                  boolean m_textChanged = false;
                                  if (!m_textChanged)
                                       return;
                                  saveFile(false);
                              item = new JMenuItem(actionSave);
                             item.setMnemonic('s');
                             item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
                             mFile.add(item);
                   JMenuItem mData = new JMenuItem("Retrieve Data");
                   mData.setMnemonic('r');
                   ActionListener lstData = new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        retrieveData();
                   mData.addActionListener(lstData);
                   mFile.add(mData);
                   mFile.addSeparator();
                   JMenuItem mExit = new JMenuItem("Exit");
                   mExit.setMnemonic('x');
                   ActionListener lstExit = new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             System.exit(0);
                   mExit.addActionListener(lstExit);
                   mFile.add(mExit);
                   menuBar.add(mFile);
                   return menuBar;
              protected void saveFile(boolean b) {
                   // TODO Auto-generated method stub
              protected void newDocument() {
                     //Create and set up the window.
                 JDialog frame = new JDialog();//"DailyDairyDemo");
                 frame.setModal(true);
                 //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 //Add content to the window.
                 frame.add(new DD());
                 //Display the window.
                 frame.pack();
                 frame.setVisible(true);
                 JOptionPane.showMessageDialog(this, "Done!");
                 //loadFile();
              protected boolean promptToSave() {
                   // TODO Auto-generated method stub
                   return true;
              public void retrieveData(){
                   Runnable updater = new Runnable(){
                        public void run(){
                             SimpleDateFormat frm = new SimpleDateFormat("MM/dd/yyyy");
                             String currentDate = frm.format(m_data.m_date);
                             String result =
                             (String)JOptionPane.showInputDialog(DDTable.this,"Please enter date in form mm/dd/yyyy:", "Input", JOptionPane.INFORMATION_MESSAGE, null, null, currentDate);
                             if (result==null)
                                  return;
                             java.util.Date date = null;
                             try{
                                  date = frm.parse(result);
                             catch (java.text.ParseException ex){
                                  date = null;
                             if (date == null){
                                  JOptionPane.showMessageDialog(DDTable.this, result+" is not a valid date", "Warning", JOptionPane.WARNING_MESSAGE);
                                  return;
                             setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                             try{
                                  m_data.retriveData(date);
                             catch (Exception ex){
                                  JOptionPane.showMessageDialog(DDTable.this,"Error retrieving data:\n"+ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
                             setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                             m_title.setText(m_data.getTitle());
                             m_table.tableChanged(new TableModelEvent(m_data));
                   SwingUtilities.invokeLater(updater);
         public static void main(String argv[]){
              DDTable frame = new DDTable();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
       class DDData{
            public String m_name;
            public String m_date;
            public String m_startTime;
            public String m_endTime;
            public String m_totalTime;
            public String m_comment;
            public String m_category;
            public DDData(String name, String date,String startTime, String endTime, String totalTime, String comment, String category){
                 m_name = name;
                 m_date = date;
                 m_startTime = startTime;
                 m_endTime = endTime;
                 m_totalTime = totalTime;
                 m_comment = comment;
                 m_category = category;
       class ColumnData{
            public String m_title;
            public int m_width;
            public int m_alignment;
            public ColumnData(String title, int width, int alignment) {
                 m_title = title;
                 m_width = width;
                 m_alignment = alignment;
       class DDTableData extends AbstractTableModel{
         private static final long serialVersionUID = 1L;
         static final String QUERY = "SELECT symbols.name,"+"data startTime, data.endTime, data.totalTime, data.comment, data.category FROM DATA INNER JOIN SYMBOLS"
         +"ON DATA.symbol = SYMBOLS.symbol WHERE"+
         "month(data.date1)=? AND day(data.date1)=?"+
         "AND year(data.date1)=?";
         @SuppressWarnings("unchecked")
         public void retriveData(Date date)
         throws SQLException, ClassNotFoundException {
              try {
                   File f = new File("appointments.dat");
                   FileInputStream fis = new FileInputStream(f);
                ObjectInputStream ois = new ObjectInputStream(fis);
                m_vector = (Vector<DDData>) ois.readObject();
                ois.close();
                fis.close();
               } catch(ClassCastException ex) {
               } catch(FileNotFoundException ex) {
               } catch(IOException ex) {
              /*GregorianCalendar calendar = new GregorianCalendar();
              calendar.setTime(date);
              int month = calendar.get(Calendar.MONTH)+1;
              int day = calendar.get(Calendar.DAY_OF_MONTH);
              int year = calendar.get(Calendar.YEAR);
              m_date = date;
              m_vector = new Vector();
              Connection conn = null;
              PreparedStatement pst = null;
              try{
                   //Load the JDBC-ODBC bridge driver
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   conn = DriverManager.getConnection("jdbc:odbc:Market", "admin", "");
                   pst = conn.prepareStatement(QUERY);
                   pst.setInt(1, month);
                   pst.setInt(2, day);
                   pst.setInt(3, year);
                   ResultSet results = pst.executeQuery();
                   while (results.next()){
                        String name = results.getString(1);
                        String startTime = results.getString(2);
                        String endTime = results.getString(3);
                        String totalTime = results.getString(4);
                        String comment = results.getString(5);
                        String category = results.getString(6);
                        m_vector.addElement(new DDData(name, startTime, endTime, totalTime, comment, category, category));
                   sortData();
              finally{
                   if (pst != null )
                        pst.close();
                   if (conn != null)
                        conn.close();
         private void saveData() {
              try {
                   File f = new File("appointments.dat");
                   FileOutputStream fos = new FileOutputStream(f);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(m_vector);
                oos.close();
                fos.close();
               } catch(IOException ex) {
         private void sortData() {
              // TODO Auto-generated method stub
         static final public ColumnData m_columns[] = {
                 new ColumnData("Name", 100, JLabel.LEFT),
                 new ColumnData("Date", 100, JLabel.LEFT),
                 new ColumnData("Start Time", 100, JLabel.RIGHT),
                 new ColumnData("End Time", 100, JLabel.RIGHT),
                 new ColumnData("Total Time", 100, JLabel.RIGHT),
                 new ColumnData("Comment", 200, JLabel.RIGHT),
                 new ColumnData("Category", 100, JLabel.RIGHT),
            protected SimpleDateFormat m_frm;
            protected Vector<DDData> m_vector = new Vector<DDData>();
            protected Date m_date;
            public DDTableData(){
                 m_frm = new SimpleDateFormat("MM/dd/yyyy");
                 setDefaultData();
            public void setDefaultData(){
                 try{
                      m_date = m_frm.parse("07/31/2007");
                 catch (java.text.ParseException ex){
                      m_date = null;
                 m_vector.removeAllElements();
                 m_vector.addElement(new DDData("Jerome", null, "Dan", null, null, null, null));
            public int getRowCount(){
                 return m_vector==null ? 0 : m_vector.size();
            public int getColumnCount(){
                 return m_columns.length;
            public String getColumnName(int column){
                 return m_columns[column].m_title;
            public boolean isCellEditable(int nRow, int nCol){
                 return false;
            public Object getValueAt(int nRow, int nCol){
                 if (nRow < 0 || nRow>=getRowCount())
                      return "";
                 DDData row = m_vector.elementAt(nRow);
                 switch (nCol){
                 case 0: return row.m_name;
                 case 1: return row.m_date;
                 case 2: return row.m_startTime;
                 case 3: return row.m_endTime;
                 case 4: return row.m_totalTime;
                 case 5: return row.m_comment;
                 case 6: return row.m_category;
                 return "";
            public String getTitle(){
                 if (m_date==null)
                      return "Daily Dairy";
                 return "Daily Dairy at "+m_frm.format(m_date);

    here is code to collect the data pls what can i do to get the data on the form display on the JTable in the all categories as on the form pls...
    private String collectData()
              String toPrint = "";
              for (int i = 0; i < rowData.length; i++)
                   Component[] currentRowComps = rowData;
                   for (int j = 0; j < currentRowComps.length; j++)
                        Component currentComp = currentRowComps[j];
                        if (currentComp instanceof TextField)
                             TextField tf = (TextField) currentComp;
                             toPrint += tf.getText() + " - ";
                        else if (currentComp instanceof JComboBox)
                             JComboBox box = (JComboBox) currentComp;
                             Object selection = box.getSelectedItem();
                             if (selection != null)
                                  toPrint += selection.toString() + " - ";
                   toPrint += "\n";
              return toPrint;
         private File newFile(String data)
              File newfile = null;
              try
                   newfile = new File("I:\\ouput.doc");
                   System.out.println("DATA? - " + data);
                   FileOutputStream fos = new FileOutputStream(newfile);
                   fos.write(data.getBytes());
                   fos.close();
                   // JOptionPane.showMessageDialog(null, "Save File");
                   JOptionPane.showMessageDialog(null, "File saved.", "Success",
                   JOptionPane.INFORMATION_MESSAGE);
              catch (IOException ioexc)
                   JOptionPane.showMessageDialog(null, "Error while saving file: " + ioexc,
                   "Error", JOptionPane.ERROR_MESSAGE);
              return null;
    private void addLabelTextRows(JLabel[] labels,
    JTextField[] textFields,
    GridBagLayout gridbag,
    Container container) {
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.EAST;
    int numLabels = labels.length;
    for (int i = 0; i < numLabels; i++) {
    c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
    c.fill = GridBagConstraints.NONE; //reset to default
    c.weightx = 0.0; //reset to default
    container.add(labels[i], c);
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    container.add(textFields[i], c);
    Message was edited by:
    desaint
    Message was edited by:
    desaint

  • Saving RTF from JTextPane and missing subscripts

    I've written a little application that involves saving and loading styled text in a JTextPane. Bold and italic styled text survives the loading/saving process but subscripts always revert to the regular style.
    To test this further, I created a document with bold, italic and subscript styled text in MS Word, saved it as RTF and then loaded it into my JTextPane. I got the same result as above: my subscripts were lost, but bold and italic survived.
    Is this a bug? If so any news of it being known or fixed?
    thanks,
    McN

    Swing's RTFEditorKit only supports an early release of the RTF specification -- maybe somewhere along 1.1. Microsoft has updated the spec with each new version of Word, so that I think the XP version is something around 1.6 or 1.7. The most common behavior of the current Swing RTFEditorKit is to ignore those extra features it doesn't recognize, like subscripts, tables, images, etc. I have occasionally had it produce a null value as well...giving me fits.

  • Advanced styling with JTextPane

    i am currently trying to develop a method to render html tags to a JTextPane window- i can deal with bold, itallic, underlinded etc. styles but im having probelms trying to render the preformatted tag <pre>. the JTextPane automatically word wraps anything entered which is not what i want, does anyone know of a way to either stop word wrapping or to markup the text to prevent it from wrapping.
    I am aware that there is a libary that can render this for me (JTextPane.setPage(String url) has shown me that <pre> can be rendered correctly) but i have been instructed not to use this. Can anyone suggest anything that might help? im going crazy trying to think up a soloution!

    What i mean is that i have to read in a html document and render (select tags) it without using HTMLEditorKit and HTMLDocument. Like i said i can render text so its bold, itallic, do tables, etc. but the <pre> tag is giving me problems.

  • 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-->

  • TableCellRenderer with JTextPane and HTML

    I'm writing a TableCellRenderer that will be rendering HTML content using a custom extension to the JTextPane class. Where I'm having trouble is in calculating the necessary height to set the table row based on the content of the cell (in this case HTML text in my JTextPane component). I know the width of the table cell and I can figure out the width of the content (taking into account the formatting because of the HTML content). This all works perfectly until the column width shrinks enough to cause the underlying view to word wrap.
    Here is the code snippet from my JTextPane to count the number of lines of text and calculate the width of the content
      public int getWidthOfContent() {
        getLineCount();
        return m_iWidthOfContent;
      public int getWidthOfContent(int p_iWidthOfArea) {
        getLineCount(p_iWidthOfArea);
        return m_iWidthOfContent;
      public int getLineCount(int iComponentWidth) {
        int iWidth = 0;
        int iBreakCount = 0;
        int iHardBreakCount = 0;
        int iTotalWidth = 0;
        int iTotalContentWidth = 0;
        int iMaxHeight = 0;
        Document doc = getDocument();
        ElementIterator it = new ElementIterator(doc.getDefaultRootElement());
        StyleSheet styleSheet = null;
        if(doc instanceof HTMLDocument) {
          styleSheet = ((HTMLDocument)doc).getStyleSheet();
        if(iComponentWidth == -1) {
          iWidth = getWidth();
        else {
          iWidth = iComponentWidth;
        Element e;
        while ((e=it.next()) != null) {
          AttributeSet attributes = e.getAttributes();
          Enumeration enumeration = attributes.getAttributeNames();
          boolean bBreakDetected = false;
          while(enumeration.hasMoreElements()) {
            Object objName = enumeration.nextElement();
            Object objAttr = attributes.getAttribute(objName);
            if(objAttr instanceof HTML.Tag) {
              HTML.Tag tag = (HTML.Tag)objAttr;
    //          if(tag == HTML.Tag.BODY) {
    //            UCSParagraphView pv = new UCSParagraphView(e);
    //            if(pv.willWidthBreakView(iWidth)) {
    //              iHardBreakCount++;
              FontMetrics fontMetrics = null;
              if(styleSheet != null && styleSheet.getFont(attributes) != null) {
                fontMetrics = getFontMetrics(styleSheet.getFont(attributes));
              if(fontMetrics != null && fontMetrics.getHeight() > iMaxHeight) {
                iMaxHeight = fontMetrics.getHeight();
              if(tag.breaksFlow()) {
                //This must be a breaking tag....this will add another line to the count
                bBreakDetected = true;
                if(tag.equals(HTML.Tag.BR) || tag.isBlock() && (!tag.equals(HTML.Tag.HEAD) && !tag.equals(HTML.Tag.BODY))) {
                  if(iTotalContentWidth == 0) {
                    iTotalContentWidth = iTotalWidth;
                    iTotalWidth = 0;
                  else if(iTotalWidth > iTotalContentWidth) {
                    iTotalContentWidth = iTotalWidth;
                    iTotalWidth = 0;
                  else {
                    iTotalWidth = 0;
                  if(tag.equals(HTML.Tag.H1) || tag.equals(HTML.Tag.H2) || tag.equals(HTML.Tag.H3) || tag.equals(HTML.Tag.H4)) {
                    iHardBreakCount += 3; //These count as three lines (Blank - Content - Blank)
                  else {
                    iHardBreakCount++;
                iBreakCount++;
          if(!bBreakDetected) {
            Font font;
            FontMetrics fontMetrics;
            if(e.getDocument() instanceof HTMLDocument) {
              font = ((HTMLDocument)e.getDocument()).getStyleSheet().getFont(e.getAttributes());
              fontMetrics = getFontMetrics(font);
            else {
              font = getFont();
              fontMetrics = getFontMetrics(font);
            int iRangeStart = e.getStartOffset();
            int iRangeEnd = e.getEndOffset();
            if(fontMetrics.getHeight() > iMaxHeight) {
              iMaxHeight = fontMetrics.getHeight();
            if(e.isLeaf()) {
              String strText;
              try {
                strText = this.getText(iRangeStart, iRangeEnd - iRangeStart);
                if(strText.equals("\n")) {
                  //iBreakCount++;
                iTotalWidth += SwingUtilities.computeStringWidth(fontMetrics, strText);
              catch (BadLocationException ex) {
                //Something happened.....don't care....just eat the exception
        m_iMaxFontHeight = iMaxHeight;
        m_iWidthOfContent = iTotalWidth;
        m_iHardBreakCount = iHardBreakCount;
        if(iWidth > 0) {
          int iLineCount = (iTotalWidth / iWidth) + iBreakCount;
          return iLineCount;
        return 1;
      }And here is the code from my TableCellRenderer that uses the above information
       public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                                      boolean hasFocus, int row, int column) {
         if(ValidationHelper.hasText(value) && value.toString().indexOf("<html>") != -1) {
           UCSHTMLTextPane pane = new UCSHTMLTextPane();
           pane.setText(ValidationHelper.getTrimmedText(value.toString()));
           BigDecimal lWidthCell = new BigDecimal(table.getCellRect(row, column, false).getWidth() - 15);
           BigDecimal lWidthContent = new BigDecimal(pane.getWidthOfContent(lWidthCell.intValue()));
           int iHardBreakCount = pane.getHardBreakCount();
           BigDecimal lLineCount = lWidthContent.divide(lWidthCell, BigDecimal.ROUND_CEILING);
           int iLineCount = lLineCount.intValue();
           double dWidthCell = lWidthCell.doubleValue();
           double dWidthContent = lWidthContent.doubleValue();
           double dWidthContentPlusFivePercent = dWidthContent + (dWidthContent * .01);
           double dWidthContentMinumFivePercent = dWidthContent - (dWidthContent * .01);
           if(dWidthCell >= dWidthContentMinumFivePercent && dWidthCell <= dWidthContentPlusFivePercent) {
             iLineCount++;
           iLineCount += iHardBreakCount;
           int iMaxFontHeight = pane.getMaxFontHeight();
           int iHeight = (iMaxFontHeight * iLineCount) + 5;
           if ( (iLineCount > 0) && (table.getRowHeight(row) != iHeight)) {
             pane.setPreferredSize(new Dimension(0, iHeight));
             if(m_bAutoAdjustHeight) {
               table.setRowHeight(row, iHeight);
           if(iLineCount == 1) {
             if(iHeight != table.getRowHeight()) {
               if(m_bAutoAdjustHeight) {
                 table.setRowHeight(iHeight);
           setComponentUI(pane, table, row, column, isSelected, hasFocus);
           return pane;
    }Any suggestions?

    Hello,
    You must initialize correctly your JTextPane like this:
    javax.swing.text.html.HTMLEditorKit htmlEditorKit = new javax.swing.text.html.HTMLEditorKit();
    javax.swing.text.html.HTMLDocument htmlDoc = (javax.swing.text.html.HTMLDocument)htmlEditorKit.createDefaultDocument();
    setEditorKit(htmlEditorKit);
    setDocument(htmlDoc);
    setEditable(true);
    setContentType("text/html");

Maybe you are looking for