Selection utility in the style of the JOptionPane.showXxxDialog methods. - Java Swing

Java examples for Swing:JOptionPane

Description

Selection utility in the style of the JOptionPane.showXxxDialog methods.

Demo Code


//package com.java2s;

import java.awt.Component;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTree;

import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import javax.swing.tree.TreePath;

public class Main {
    /**/*from ww w .java2 s . c  o m*/
     * Selection utility in the style of the JOptionPane.showXxxDialog methods.
     * Given a JTree, presents an option dialog presenting the tree allowing users to select a node.
     * 
     * @param tree is the tree to display
     * @param parent is the component to anchor the dialog to
     * @return the path of the selected tree node or null if canceled.
     */
    public static TreePath showTreeNodeChooser(JTree tree, String title,
            Component parent) {
        final String OK = "OK", CANCEL = "Cancel";
        final JButton ok_butt = new JButton(OK), cancel_butt = new JButton(
                CANCEL);
        final TreePath selected[] = new TreePath[] { tree
                .getLeadSelectionPath() }; // only an array so it can be final, yet mutable
        ok_butt.setEnabled(selected[0] != null);
        final JOptionPane option_pane = new JOptionPane(new JScrollPane(
                tree), JOptionPane.QUESTION_MESSAGE,
                JOptionPane.DEFAULT_OPTION, null, new Object[] { ok_butt,
                        cancel_butt });
        ok_butt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                option_pane.setValue(OK);
            }
        });
        cancel_butt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                option_pane.setValue(CANCEL);
                selected[0] = null;
            }
        });
        TreeSelectionListener tsl = new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                selected[0] = e.getNewLeadSelectionPath();
                ok_butt.setEnabled(selected[0] != null);
            }
        };
        JDialog dialog = option_pane.createDialog(parent, title);
        tree.addTreeSelectionListener(tsl); // to start monitoring user tree selections
        dialog.setVisible(true); // present modal tree dialog to user
        tree.removeTreeSelectionListener(tsl); // don't want to clutter caller's tree with listeners
        return OK.equals(option_pane.getValue()) ? selected[0] : null;
    }
}

Related Tutorials