net.alantea.swing.tree.TreeUtils Maven / Gradle / Ivy
package net.alantea.swing.tree;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import net.alantea.utils.MultiMessages;
public class TreeUtils
{
public static final int showTreeCheckSelectionDialog(JFrame frame, String key, DefaultMutableTreeNode root)
{
int[] ret = new int[1];
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JTextArea message = new JTextArea();
message.setEditable(false);
message.setText(MultiMessages.get(key + ".message"));
message.setColumns(30);
panel.add(message);
JTree tree = new JTree();
JScrollPane scroll = new JScrollPane(tree);
tree.setCellRenderer(new SelectableTreeCellRenderer());
panel.add(scroll);
((DefaultTreeModel)tree.getModel()).setRoot(root);
final JButton ok = new JButton(MultiMessages.get("TreeDialog.ok"));
// ok.setEnabled(false);
ok.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Window w = SwingUtilities.getWindowAncestor(ok);
if(w != null) w.setVisible(false);
ret[0] = 1;
}
});
final JButton cancel = new JButton(MultiMessages.get("TreeDialog.cancel"));
cancel.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Window w = SwingUtilities.getWindowAncestor(ok);
if(w != null) w.setVisible(false);
ret[0] = -1;
}
});
tree.addTreeSelectionListener( (e) -> {
if (e.getPaths().length > 0)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode)e.getPath().getLastPathComponent();
Object userObject = node.getUserObject();
if (userObject instanceof Selectable)
{
Selectable selectable = (Selectable) userObject;
if (selectable.isSelectable())
{
selectable.setSelected(!selectable.isSelected());
tree.invalidate();
tree.repaint();
System.out.println(userObject + " " + selectable.isSelected());
}
}
}
});
JOptionPane.showOptionDialog(frame, panel, key + ".title", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, new JButton[]{ok, cancel}, cancel);
return ret[0];
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy