提交 a2f14590 编写于 作者: M mrkam

7027698: /jfc/SampleTree demo needs to be improved

Reviewed-by: rupashka
上级 1080aa8f
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
......@@ -29,14 +29,13 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
*/
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.GraphicsEnvironment;
import java.util.Random;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* DynamicTreeNode illustrates one of the possible ways in which dynamic
......@@ -64,35 +63,33 @@ import java.util.Random;
*
* @author Scott Violet
*/
public class DynamicTreeNode extends DefaultMutableTreeNode
{
@SuppressWarnings("serial")
public class DynamicTreeNode extends DefaultMutableTreeNode {
// Class stuff.
/** Number of names. */
static protected float nameCount;
/** Number of names. */
protected static float nameCount;
/** Names to use for children. */
static protected String[] names;
protected static final String[] NAMES;
/** Potential fonts used to draw with. */
static protected Font[] fonts;
protected static Font[] fonts;
/** Used to generate the names. */
static protected Random nameGen;
protected static Random nameGen;
/** Number of children to create for each node. */
static protected final int DefaultChildrenCount = 7;
protected static final int DEFAULT_CHILDREN_COUNT = 7;
static {
String[] fontNames;
try {
fontNames = Toolkit.getDefaultToolkit().getFontList();
fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames();
} catch (Exception e) {
fontNames = null;
}
if(fontNames == null || fontNames.length == 0) {
names = new String[] {"Mark Andrews", "Tom Ball", "Alan Chung",
if (fontNames == null || fontNames.length == 0) {
NAMES = new String[] { "Mark Andrews", "Tom Ball", "Alan Chung",
"Rob Davis", "Jeff Dinkins",
"Amy Fowler", "James Gosling",
"David Karlton", "Dave Kloba",
......@@ -101,30 +98,26 @@ public class DynamicTreeNode extends DefaultMutableTreeNode
"Chester Rose", "Ray Ryan",
"Georges Saab", "Scott Violet",
"Kathy Walrath", "Arnaud Weber" };
}
else {
} else {
/* Create the Fonts, creating fonts is slow, much better to
do it once. */
int fontSize = 12;
names = fontNames;
fonts = new Font[names.length];
for(int counter = 0, maxCounter = names.length;
NAMES = fontNames;
fonts = new Font[NAMES.length];
for (int counter = 0, maxCounter = NAMES.length;
counter < maxCounter; counter++) {
try {
fonts[counter] = new Font(fontNames[counter], 0, fontSize);
}
catch (Exception e) {
} catch (Exception e) {
fonts[counter] = null;
}
fontSize = ((fontSize + 2 - 12) % 12) + 12;
}
}
nameCount = (float)names.length;
nameCount = (float) NAMES.length;
nameGen = new Random(System.currentTimeMillis());
}
/** Have the children of this node been loaded yet? */
protected boolean hasLoaded;
......@@ -136,6 +129,7 @@ public class DynamicTreeNode extends DefaultMutableTreeNode
super(o);
}
@Override
public boolean isLeaf() {
return false;
}
......@@ -145,8 +139,9 @@ public class DynamicTreeNode extends DefaultMutableTreeNode
* loaded, loadChildren is messaged and super is messaged for
* the return value.
*/
@Override
public int getChildCount() {
if(!hasLoaded) {
if (!hasLoaded) {
loadChildren();
}
return super.getChildCount();
......@@ -162,17 +157,22 @@ public class DynamicTreeNode extends DefaultMutableTreeNode
int randomIndex;
SampleData data;
for(int counter = 0; counter < DynamicTreeNode.DefaultChildrenCount;
for (int counter = 0; counter < DynamicTreeNode.DEFAULT_CHILDREN_COUNT;
counter++) {
randomIndex = (int)(nameGen.nextFloat() * nameCount);
if(fonts != null)
font = fonts[randomIndex];
else
randomIndex = (int) (nameGen.nextFloat() * nameCount);
String displayString = NAMES[randomIndex];
if (fonts == null || fonts[randomIndex].canDisplayUpTo(displayString)
!= -1) {
font = null;
if(counter % 2 == 0)
data = new SampleData(font, Color.red, names[randomIndex]);
else
data = new SampleData(font, Color.blue, names[randomIndex]);
} else {
font = fonts[randomIndex];
}
if (counter % 2 == 0) {
data = new SampleData(font, Color.red, displayString);
} else {
data = new SampleData(font, Color.blue, displayString);
}
newNode = new DynamicTreeNode(data);
/* Don't use add() here, add calls insert(newNode, getChildCount())
so if you want to use add, just be sure to set hasLoaded = true
......
/*
* Copyright (c) 1997, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
......@@ -29,28 +29,23 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
*/
import java.awt.Color;
import java.awt.Font;
/**
* @author Scott Violet
*/
public class SampleData extends Object {
public class SampleData extends Object
{
/** Font used for drawing. */
protected Font font;
/** Color used for text. */
protected Color color;
/** Value to display. */
protected String string;
/**
* Constructs a new instance of SampleData with the passed in
* arguments.
......@@ -103,6 +98,7 @@ public class SampleData extends Object
return string;
}
@Override
public String toString() {
return string;
}
......
/*
* Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
......@@ -29,9 +29,10 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
*/
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.BorderLayout;
......@@ -40,12 +41,12 @@ import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.*;
import javax.swing.tree.*;
/**
* A demo for illustrating how to do different things with JTree.
* The data that this displays is rather boring, that is each node will
......@@ -65,9 +66,8 @@ import javax.swing.tree.*;
*
* @author Scott Violet
*/
public final class SampleTree {
public class SampleTree
{
/** Window for showing Tree. */
protected JFrame frame;
/** Tree used for the example. */
......@@ -79,16 +79,16 @@ public class SampleTree
* Constructs a new instance of SampleTree.
*/
public SampleTree() {
// Force SampleTree to come up in the Cross Platform L&F
// Trying to set Nimbus look and feel
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
// If you want the System L&F instead, comment out the above line and
// uncomment the following:
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exc) {
System.err.println("Error loading L&F: " + exc);
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ignored) {
}
JMenuBar menuBar = constructMenuBar();
JPanel panel = new JPanel(true);
......@@ -126,15 +126,14 @@ public class SampleTree
panel.add("Center", sp);
panel.add("South", constructOptionsPanel());
frame.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.show();
frame.setVisible(true);
}
/** Constructs a JPanel containing check boxes for the different
* options that tree supports. */
@SuppressWarnings("serial")
private JPanel constructOptionsPanel() {
JCheckBox aCheckbox;
JPanel retPanel = new JPanel(false);
......@@ -171,30 +170,45 @@ public class SampleTree
buttonPane.setBorder(new TitledBorder("Selection Mode"));
button = new JRadioButton("Single");
button.addActionListener(new AbstractAction() {
public boolean isEnabled() { return true; }
@Override
public boolean isEnabled() {
return true;
}
public void actionPerformed(ActionEvent e) {
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
}
});
group.add(button);
buttonPane.add(button);
button = new JRadioButton("Contiguous");
button.addActionListener(new AbstractAction() {
public boolean isEnabled() { return true; }
@Override
public boolean isEnabled() {
return true;
}
public void actionPerformed(ActionEvent e) {
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
}
});
group.add(button);
buttonPane.add(button);
button = new JRadioButton("Discontiguous");
button.addActionListener(new AbstractAction() {
public boolean isEnabled() { return true; }
@Override
public boolean isEnabled() {
return true;
}
public void actionPerformed(ActionEvent e) {
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
}
});
button.setSelected(true);
......@@ -227,7 +241,7 @@ public class SampleTree
});
clickPanel.add(clickCBox);
borderPane.add(clickPanel, BorderLayout.NORTH);
*/
*/
return borderPane;
}
......@@ -243,9 +257,11 @@ public class SampleTree
menuItem = menu.add(new JMenuItem("Exit"));
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});
}
});
/* Tree related stuff. */
menu = new JMenu("Tree");
......@@ -273,8 +289,9 @@ public class SampleTree
protected DefaultMutableTreeNode getSelectedNode() {
TreePath selPath = tree.getSelectionPath();
if(selPath != null)
return (DefaultMutableTreeNode)selPath.getLastPathComponent();
if (selPath != null) {
return (DefaultMutableTreeNode) selPath.getLastPathComponent();
}
return null;
}
......@@ -290,11 +307,12 @@ public class SampleTree
return new DynamicTreeNode(new SampleData(null, Color.black, name));
}
/**
* AddAction is used to add a new item after the selected item.
*/
class AddAction extends Object implements ActionListener
{
class AddAction extends Object implements ActionListener {
/** Number of nodes that have been added. */
public int addCount;
......@@ -309,30 +327,30 @@ public class SampleTree
DefaultMutableTreeNode parent;
/* Determine where to create the new node. */
if(lastItem != null) {
parent = (DefaultMutableTreeNode)lastItem.getParent();
if(parent == null) {
parent = (DefaultMutableTreeNode)treeModel.getRoot();
if (lastItem != null) {
parent = (DefaultMutableTreeNode) lastItem.getParent();
if (parent == null) {
parent = (DefaultMutableTreeNode) treeModel.getRoot();
lastItem = null;
}
} else {
parent = (DefaultMutableTreeNode) treeModel.getRoot();
}
else
parent = (DefaultMutableTreeNode)treeModel.getRoot();
if (parent == null) {
// new root
treeModel.setRoot(createNewNode("Added " +
Integer.toString(addCount++)));
}
else {
treeModel.setRoot(createNewNode("Added " + Integer.toString(
addCount++)));
} else {
int newIndex;
if(lastItem == null)
if (lastItem == null) {
newIndex = treeModel.getChildCount(parent);
else
} else {
newIndex = parent.getIndex(lastItem) + 1;
}
/* Let the treemodel know. */
treeModel.insertNodeInto(createNewNode("Added " +
Integer.toString(addCount++)),
treeModel.insertNodeInto(createNewNode("Added " + Integer.
toString(addCount++)),
parent, newIndex);
}
}
......@@ -342,8 +360,8 @@ public class SampleTree
/**
* InsertAction is used to insert a new item before the selected item.
*/
class InsertAction extends Object implements ActionListener
{
class InsertAction extends Object implements ActionListener {
/** Number of nodes that have been added. */
public int insertCount;
......@@ -358,31 +376,31 @@ public class SampleTree
DefaultMutableTreeNode parent;
/* Determine where to create the new node. */
if(lastItem != null) {
parent = (DefaultMutableTreeNode)lastItem.getParent();
if(parent == null) {
parent = (DefaultMutableTreeNode)treeModel.getRoot();
if (lastItem != null) {
parent = (DefaultMutableTreeNode) lastItem.getParent();
if (parent == null) {
parent = (DefaultMutableTreeNode) treeModel.getRoot();
lastItem = null;
}
} else {
parent = (DefaultMutableTreeNode) treeModel.getRoot();
}
else
parent = (DefaultMutableTreeNode)treeModel.getRoot();
if (parent == null) {
// new root
treeModel.setRoot(createNewNode("Inserted " +
Integer.toString(insertCount++)));
}
else {
treeModel.setRoot(createNewNode("Inserted " + Integer.toString(
insertCount++)));
} else {
int newIndex;
if(lastItem == null)
if (lastItem == null) {
newIndex = treeModel.getChildCount(parent);
else
} else {
newIndex = parent.getIndex(lastItem);
}
/* Let the treemodel know. */
treeModel.insertNodeInto(createNewNode("Inserted " +
Integer.toString(insertCount++)),
treeModel.insertNodeInto(createNewNode("Inserted " + Integer.
toString(insertCount++)),
parent, newIndex);
}
}
......@@ -393,8 +411,8 @@ public class SampleTree
* ReloadAction is used to reload from the selected node. If nothing
* is selected, reload is not issued.
*/
class ReloadAction extends Object implements ActionListener
{
class ReloadAction extends Object implements ActionListener {
/**
* Messaged when the user clicks on the Reload menu item.
* Determines the selection from the Tree and asks the treemodel
......@@ -403,17 +421,19 @@ public class SampleTree
public void actionPerformed(ActionEvent e) {
DefaultMutableTreeNode lastItem = getSelectedNode();
if(lastItem != null)
if (lastItem != null) {
treeModel.reload(lastItem);
}
}
} // End of SampleTree.ReloadAction
/**
* RemoveAction removes the selected node from the tree. If
* The root or nothing is selected nothing is removed.
*/
class RemoveAction extends Object implements ActionListener
{
class RemoveAction extends Object implements ActionListener {
/**
* Removes the selected item as long as it isn't root.
*/
......@@ -451,19 +471,17 @@ public class SampleTree
paths[counter] = null;
}
treeModel.setRoot(null);
}
else {
} else {
// Find the siblings of path.
TreePath parent = path.getParentPath();
MutableTreeNode parentNode = (MutableTreeNode)parent.
MutableTreeNode parentNode = (MutableTreeNode) parent.
getLastPathComponent();
ArrayList toRemove = new ArrayList();
int depth = parent.getPathCount();
ArrayList<TreePath> toRemove = new ArrayList<TreePath>();
// First pass, find paths with a parent TreePath of parent
for (int counter = paths.length - 1; counter >= 0; counter--) {
if (paths[counter] != null && paths[counter].
getParentPath().equals(parent)) {
if (paths[counter] != null && paths[counter].getParentPath().
equals(parent)) {
toRemove.add(paths[counter]);
paths[counter] = null;
}
......@@ -478,8 +496,8 @@ public class SampleTree
if (paths[counter] != null) {
for (int rCounter = rCount - 1; rCounter >= 0;
rCounter--) {
if (((TreePath)toRemove.get(rCounter)).
isDescendant(paths[counter])) {
if ((toRemove.get(rCounter)).isDescendant(
paths[counter])) {
paths[counter] = null;
}
}
......@@ -493,10 +511,10 @@ public class SampleTree
int[] indices = new int[rCount];
Object[] removedNodes = new Object[rCount];
for (int counter = rCount - 1; counter >= 0; counter--) {
removedNodes[counter] = ((TreePath)toRemove.get(counter)).
removedNodes[counter] = (toRemove.get(counter)).
getLastPathComponent();
indices[counter] = treeModel.getIndexOfChild
(parentNode, removedNodes[counter]);
indices[counter] = treeModel.getIndexOfChild(parentNode,
removedNodes[counter]);
parentNode.remove(indices[counter]);
}
treeModel.nodesWereRemoved(parentNode, indices, removedNodes);
......@@ -522,8 +540,7 @@ public class SampleTree
return shallowestPath;
}
}
}
else {
} else {
shallowestPath = paths[counter];
shallowest = paths[counter].getPathCount();
}
......@@ -540,22 +557,16 @@ public class SampleTree
* This is actually rather expensive, it would be more efficient
* to extract the indices and then do the comparision.
*/
private class PositionComparator implements Comparator {
public int compare(Object o1, Object o2) {
TreePath p1 = (TreePath)o1;
int o1Index = treeModel.getIndexOfChild(p1.getParentPath().
private class PositionComparator implements Comparator<TreePath> {
public int compare(TreePath p1, TreePath p2) {
int p1Index = treeModel.getIndexOfChild(p1.getParentPath().
getLastPathComponent(), p1.getLastPathComponent());
TreePath p2 = (TreePath)o2;
int o2Index = treeModel.getIndexOfChild(p2.getParentPath().
int p2Index = treeModel.getIndexOfChild(p2.getParentPath().
getLastPathComponent(), p2.getLastPathComponent());
return o1Index - o2Index;
}
public boolean equals(Object obj) {
return super.equals(obj);
return p1Index - p2Index;
}
}
} // End of SampleTree.RemoveAction
......@@ -563,12 +574,11 @@ public class SampleTree
* ShowHandlesChangeListener implements the ChangeListener interface
* to toggle the state of showing the handles in the tree.
*/
class ShowHandlesChangeListener extends Object implements ChangeListener
{
class ShowHandlesChangeListener extends Object implements ChangeListener {
public void stateChanged(ChangeEvent e) {
tree.setShowsRootHandles(((JCheckBox)e.getSource()).isSelected());
tree.setShowsRootHandles(((JCheckBox) e.getSource()).isSelected());
}
} // End of class SampleTree.ShowHandlesChangeListener
......@@ -576,12 +586,11 @@ public class SampleTree
* ShowRootChangeListener implements the ChangeListener interface
* to toggle the state of showing the root node in the tree.
*/
class ShowRootChangeListener extends Object implements ChangeListener
{
class ShowRootChangeListener extends Object implements ChangeListener {
public void stateChanged(ChangeEvent e) {
tree.setRootVisible(((JCheckBox)e.getSource()).isSelected());
tree.setRootVisible(((JCheckBox) e.getSource()).isSelected());
}
} // End of class SampleTree.ShowRootChangeListener
......@@ -590,17 +599,28 @@ public class SampleTree
* to toggle between allowing editing and now allowing editing in
* the tree.
*/
class TreeEditableChangeListener extends Object implements ChangeListener
{
class TreeEditableChangeListener extends Object implements ChangeListener {
public void stateChanged(ChangeEvent e) {
tree.setEditable(((JCheckBox)e.getSource()).isSelected());
tree.setEditable(((JCheckBox) e.getSource()).isSelected());
}
} // End of class SampleTree.TreeEditableChangeListener
public static void main(String args[]) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
static public void main(String args[]) {
@SuppressWarnings(value = "ResultOfObjectAllocationIgnored")
public void run() {
new SampleTree();
}
});
} catch (InterruptedException ex) {
Logger.getLogger(SampleTree.class.getName()).log(Level.SEVERE, null,
ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(SampleTree.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
/*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
......@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
*/
import javax.swing.Icon;
import javax.swing.ImageIcon;
......@@ -42,32 +40,41 @@ import java.awt.Component;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.UIManager;
@SuppressWarnings("serial")
public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer {
public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer
{
/** Font used if the string to be displayed isn't a font. */
static protected Font defaultFont;
protected static Font defaultFont;
/** Icon to use when the item is collapsed. */
static protected ImageIcon collapsedIcon;
protected static ImageIcon collapsedIcon;
/** Icon to use when the item is expanded. */
static protected ImageIcon expandedIcon;
protected static ImageIcon expandedIcon;
/** Color to use for the background when selected. */
static protected final Color SelectedBackgroundColor = Color.yellow;//new Color(0, 0, 128);
protected static final Color SELECTED_BACKGROUND_COLOR;
static
{
static {
if ("Nimbus".equals(UIManager.getLookAndFeel().getName())) {
SELECTED_BACKGROUND_COLOR = new Color(0, 0,
0, 0);
} else {
SELECTED_BACKGROUND_COLOR = Color.YELLOW;
}
try {
defaultFont = new Font("SansSerif", 0, 12);
} catch (Exception e) {}
} catch (Exception e) {
}
try {
collapsedIcon = new ImageIcon(SampleTreeCellRenderer.class.getResource("/resources/images/collapsed.gif"));
expandedIcon = new ImageIcon(SampleTreeCellRenderer.class.getResource("/resources/images/expanded.gif"));
collapsedIcon = new ImageIcon(SampleTreeCellRenderer.class.
getResource("/resources/images/collapsed.gif"));
expandedIcon = new ImageIcon(SampleTreeCellRenderer.class.
getResource("/resources/images/expanded.gif"));
} catch (Exception e) {
System.out.println("Couldn't load images: " + e);
}
}
/** Whether or not the item that was last configured is selected. */
protected boolean selected;
......@@ -81,7 +88,6 @@ public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer
boolean selected, boolean expanded,
boolean leaf, int row,
boolean hasFocus) {
Font font;
String stringValue = tree.convertValueToText(value, selected,
expanded, leaf, row, hasFocus);
......@@ -91,24 +97,27 @@ public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer
setToolTipText(stringValue);
/* Set the image. */
if(expanded)
if (expanded) {
setIcon(expandedIcon);
else if(!leaf)
} else if (!leaf) {
setIcon(collapsedIcon);
else
} else {
setIcon(null);
}
/* Set the color and the font based on the SampleData userObject. */
SampleData userObject = (SampleData)((DefaultMutableTreeNode)value)
.getUserObject();
if(hasFocus)
setForeground(Color.cyan);
else
SampleData userObject = (SampleData) ((DefaultMutableTreeNode) value).
getUserObject();
if (hasFocus) {
setForeground(UIManager.getColor("Tree.selectionForeground"));
} else {
setForeground(userObject.getColor());
if(userObject.getFont() == null)
}
if (userObject.getFont() == null) {
setFont(defaultFont);
else
} else {
setFont(userObject.getFont());
}
/* Update the selected flag for the next paint. */
this.selected = selected;
......@@ -121,32 +130,32 @@ public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer
* currently does not allow backgrounds other than white, and it
* will also fill behind the icon. Something that isn't desirable.
*/
@Override
public void paint(Graphics g) {
Color bColor;
Icon currentI = getIcon();
if(selected)
bColor = SelectedBackgroundColor;
else if(getParent() != null)
/* Pick background color up from parent (which will come from
the JTree we're contained in). */
if (selected) {
bColor = SELECTED_BACKGROUND_COLOR;
} else if (getParent() != null) /* Pick background color up from parent (which will come from
the JTree we're contained in). */ {
bColor = getParent().getBackground();
else
} else {
bColor = getBackground();
}
g.setColor(bColor);
if(currentI != null && getText() != null) {
if (currentI != null && getText() != null) {
int offset = (currentI.getIconWidth() + getIconTextGap());
if (getComponentOrientation().isLeftToRight()) {
g.fillRect(offset, 0, getWidth() - 1 - offset,
getHeight() - 1);
}
else {
} else {
g.fillRect(0, 0, getWidth() - 1 - offset, getHeight() - 1);
}
} else {
g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
}
else
g.fillRect(0, 0, getWidth()-1, getHeight()-1);
super.paint(g);
}
}
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
......@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
*/
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
......@@ -38,6 +36,7 @@ import javax.swing.tree.TreePath;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.Color;
/**
* SampleTreeModel extends JTreeModel to extends valueForPathChanged.
* This method is called as a result of the user editing a value in
......@@ -47,9 +46,9 @@ import java.awt.Color;
*
* @author Scott Violet
*/
@SuppressWarnings("serial")
public class SampleTreeModel extends DefaultTreeModel {
public class SampleTreeModel extends DefaultTreeModel
{
/**
* Creates a new instance of SampleTreeModel with newRoot set
* to the root of this model.
......@@ -61,12 +60,14 @@ public class SampleTreeModel extends DefaultTreeModel
/**
* Subclassed to message setString() to the changed path item.
*/
@Override
public void valueForPathChanged(TreePath path, Object newValue) {
/* Update the user object. */
DefaultMutableTreeNode aNode = (DefaultMutableTreeNode)path.getLastPathComponent();
SampleData sampleData = (SampleData)aNode.getUserObject();
DefaultMutableTreeNode aNode = (DefaultMutableTreeNode) path.
getLastPathComponent();
SampleData sampleData = (SampleData) aNode.getUserObject();
sampleData.setString((String)newValue);
sampleData.setString((String) newValue);
/* UUUhhhhh, pretty colors. */
sampleData.setColor(Color.green);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册