我正在尝试让应用程序从 xml 加载用户数据以制作树模型,然后用户可以选择从树中选择一条数据并为其设置图标。
我可以成功地从 xml 文件加载数据,但问题是我无法为树的每个节点设置不同的图标
我是这样做的
public class DefaultTreeRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = 1L;
private Icon userIcon;
private int getSelecteRow;
public DefaultTreeRenderer(String IconPath,int selected) throws IOException {
Image img = ImageIO.read(new File(IconPath)) ;
Image newimg = img.getScaledInstance( 28, 28, java.awt.Image.SCALE_SMOOTH ) ;
Icon x = new ImageIcon(newimg);
userIcon= x;
getSelecteRow = selected;
}
@Override
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
JLabel label = (JLabel) super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
if (?!!!) {
// This's the missing part, what should i state to set per row icon ?
label.setIcon(tutorialIcon);
label.setText(label.getText()+" √");
} else{
}
return label;
}
}
测试代码:
try {
jTree1.setCellRenderer(new DefaultTreeRenderer(iconPathTextBox.getText(),jTree1.getMinSelectionRow()));
} catch (IOException ex) {
Logger.getLogger(frame.class.getName()).log(Level.SEVERE , null , ex);
}