// $Id: PmiiTreeCellEditor.java,v 1.2 2004/02/27 16:30:00 m31 Exp $
//
// This file is part of the program suite "Principia Mathematica II"
// which is a working prototype for the main project:
// "Hilbert II" - http://www.qedeq.org
//
// Copyright 2001-2004  Michael Meyling <mime@qedeq.org>.
//
// "Principia Mathematica II" is free software; you can redistribute
// it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

package com.meyling.principia.gui.jtree;

import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;


/**
 * Editor for a JTree.
 *
 * @version $Revision: 1.2 $
 * @author  Michael Meyling
 */
public final class PmiiTreeCellEditor extends DefaultCellEditor {

    private final JTextField editor;

    private ModuleElement editorValue;

    public PmiiTreeCellEditor(JTextField editor) {

        super(editor);
        this.editor = editor;
    }


    public Component getTreeCellEditorComponent(JTree tree, Object value,
        boolean isSelected, boolean expanded, boolean leaf, int row) {

        JTextField aEditor = (JTextField) super.getTreeCellEditorComponent(
            tree, value, isSelected, expanded, leaf, row);
        ModuleElement unit;
        if (value instanceof DefaultMutableTreeNode) {
            unit = (ModuleElement) ((DefaultMutableTreeNode)
                value).getUserObject();
            editorValue = unit;
            aEditor.setText(unit.getName());
        }
        return aEditor;

    }


    public boolean stopCellEditing() {
        try {
            editorValue.setName(editor.getText());
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
            editor.selectAll();
            return false;
        }
        //TODO Error handling
        return super.stopCellEditing();
    }


    public Object getCellEditorValue () {
        return editorValue;
    }

}
