Search code examples
javaswingjtextpanejeditorpane

Text disappear after Component change size


I create a jTable, and TableCellRenderer, TableCellEditor on it. I need to put there editable (with text/html context type) JEditorPane. When i write some text inside and resize component, text disappear. What I doing wrong? Furthermore above this component I have got buttons with text edition: for example:

JButton bold = new JButton():
bold.setAction(new StyledEditorKit.BoldAction());

It is part of my custom model:

private JEditorPane editorTxtPane = new JEditorPane("text/html", "");
private JEditorPane rendererTxtPane = new JEditorPane("text/html", "");
private final JPanel editorPanel = new JPanel();
private final JPanel rendererPanel = new JPanel();
private final ArrayList<FocusListener> editorFocusListeners = new ArrayList<FocusListener>();

public SampleModel() {
    super();

    rendererTxtPane.setContentType("text/html");
    editorTxtPane.setContentType("text/html");

    rendererPanel.add(initCellControls(rendererPanel, rendererLabel));
    rendererPanel.add(rendererTxtPane);

    editorPanel.add(initCellControls(editorPanel, editorLabel));
    JScrollPane sp = new JScrollPane(editorTxtPane);
    sp.setBorder(null);
    editorPanel.add(sp);

    editorTxtPane.addFocusListener(new FocusAdapter() {

        @Override
        public void focusGained(FocusEvent e) {
            super.focusGained(e);
            e.setSource(editorTxtPane);
            for (int i = editorFocusListeners.size() - 1; i >= 0; i--) {
                editorFocusListeners.get(i).focusGained(e);
            }
        }

        @Override
        public void focusLost(FocusEvent e) {
            super.focusLost(e);
            e.setSource(editorTxtPane);
            for (int i = editorFocusListeners.size() - 1; i >= 0; i--) {
                editorFocusListeners.get(i).focusLost(e);
            }
        }
    });
}

It is my editor and renderer methods:

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Comment c = data.get(row);
    rendererTxtPane.setText(c.getComment());
    return rendererPanel;
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    Comment c = data.get(row);
    c.setNeedSave(true);
    editorTxtPane.setText(c.getComment());
    return editorPanel;
}

Solution

  • This is not how Editors and Renderers work. In particular, the editor is only valid while the cell is being edited. Your TableModel should store each row's Document. After editing concludes, your model will be updated with the revised Document, as described here. You might compare what your doing with the example, which could form the basis of your sscce.