class cannot be cast to class javax.swing.tree.DefaultTreeCellRenderer error

248 Views Asked by At
public class jtre extends javax.swing.JFrame {
    static{
    
        try{
            
    UIManager.setLookAndFeel(NimbusLookAndFeel.class.getName());
        }catch (ClassNotFoundException ex){
            
        } catch (InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            Logger.getLogger(jtre.class.getName()).log(Level.SEVERE, null, ex);}}
   
    public jtre() {
        initComponents();
         jTree1.setCellRenderer(new WarnaRender());
        
        DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)jTree1.getCellRenderer();
         Icon closedIcon = new ImageIcon("/images/ve.png");
         Icon openIcon = new ImageIcon("/images/veya.png");
         Icon leafIcon = new ImageIcon("/images/xor.png");
         renderer.setClosedIcon(closedIcon);
         renderer.setOpenIcon(openIcon);
         renderer.setLeafIcon(leafIcon);   }
 
public class WarnaRender implements TreeCellRenderer{

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        JLabel label = new JLabel();
        label.setText(value.toString());
        label.setOpaque(true);
        if(row %2 == 1){
        label.setBackground(Color.RED);
        label.setForeground(Color.WHITE);
       } else {
        
        label.setBackground(Color.GREEN);
        label.setForeground(Color.RED); } 
        return label;}}   
    
     

I make a class which is called WarnaRender for coloring each node of jtree. My code is working. After that I want to add icons to jtree and I encountered an error which is "ClassCastException: class WarnaRender cannot be cast to class javax.swing.tree.DefaultTreeCellRenderer (WarnaRender is in unnamed module of loader 'app'; javax.swing.tree.DefaultTreeCellRenderer is in module java.desktop of loader 'bootstrap')". How can ı solve this problem? Can you help me. I investigated this error in the İnternet but I couldnt find the solution. Please help my code. Thank you.

1

There are 1 best solutions below

8
Jens On

Your class WarnaRender does not extends DefaultTreeCellRenderer so you can not cast it to this class.

So extend from it:

public class WarnaRender extends DefaultTreeCellRenderer {