簡體   English   中英

JTree-無法轉換為javax.swing.tree.MutableTreeNode

[英]JTree - cannot be cast to javax.swing.tree.MutableTreeNode

我對制作Java GUI非常陌生,正在嘗試在這里進行嘗試。 基本上,我有另一個類從excel表中讀取有關自動測試包的數據。 我想做的就是將這些測試添加到該資源樹中。 但是當我嘗試使用

   addTest(new testInfo
        ("TESTING",
            "TESTING MESSAGE"));

似乎在抱怨。 我的代碼:

package com.main;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class ExcelReaderGui extends JPanel
implements TreeSelectionListener {
/**
 * 
 */
private static final long serialVersionUID = 1L;
private JEditorPane htmlPane;
private JTree tree;
private URL helpURL;
private static boolean DEBUG = false;
private static ReadExcel re = new ReadExcel();
private List<testInfo> testsToAdd = new ArrayList<testInfo>();;

//Optionally play with line styles.  Possible values are
//"Angled" (the default), "Horizontal", and "None".
private static boolean playWithLineStyle = false;
private static String lineStyle = "Horizontal";

//Optionally set the look and feel.
private static boolean useSystemLookAndFeel = false;

public ExcelReaderGui() {
    super(new GridLayout(1,0));

    //Create the nodes.
    addTest(new testInfo
            ("TESTING",
                "TESTING MESSAGE"));
    DefaultMutableTreeNode top =
            new DefaultMutableTreeNode("Automated tests");
    createNodes(top);


    //Create a tree that allows one selection at a time.
    tree = new JTree(top);
    tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.SINGLE_TREE_SELECTION);

    //Listen for when the selection changes.
    tree.addTreeSelectionListener(this);

    if (playWithLineStyle) {
        System.out.println("line style = " + lineStyle);
        tree.putClientProperty("JTree.lineStyle", lineStyle);
    }

    //Create the scroll pane and add the tree to it. 
    JScrollPane treeView = new JScrollPane(tree);

    //Create the HTML viewing pane.
    htmlPane = new JEditorPane();
    htmlPane.setEditable(false);
    initHelp();
    JScrollPane htmlView = new JScrollPane(htmlPane);

    //Add the scroll panes to a split pane.
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    splitPane.setTopComponent(treeView);
    splitPane.setBottomComponent(htmlView);

    Dimension minimumSize = new Dimension(100, 50);
    htmlView.setMinimumSize(minimumSize);
    treeView.setMinimumSize(minimumSize);
    splitPane.setDividerLocation(150); 
    splitPane.setPreferredSize(new Dimension(700, 400));

    //Add the split pane to this panel.
    add(splitPane);
}

/** Required by TreeSelectionListener interface. */
public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
            tree.getLastSelectedPathComponent();

    if (node == null) return;

    Object nodeInfo = node.getUserObject();
    if (node.isLeaf()) {
        testInfo book = (testInfo)nodeInfo;
        displayURL(book.resultOfTest);
        if (DEBUG) {
            System.out.print(book.resultOfTest + ":  \n    ");
        }
    } else {
        displayURL("Drill down in the resource trees above to find tests with their results"); 
    }
    if (DEBUG) {
        System.out.println(nodeInfo.toString());
    }
}

private class testInfo {
    public String testName;
    public String resultOfTest;

    public testInfo(String test, String testResult) {
        testName = test;
        resultOfTest = testResult;
    }

    public String toString() {
        return testName;
    }
}

private void initHelp() {
    String s = "TreeDemoHelp.html";
    helpURL = getClass().getResource(s);
    if (helpURL == null) {
        System.err.println("Couldn't open help file: " + s);
    } else if (DEBUG) {
        System.out.println("Help URL is " + helpURL);
    }

    displayURL("Drill down in the resource trees above to find tests with their results");
}

private void displayURL(String url) {
    htmlPane.setText(url);
}

public void addTest(testInfo testToAdd) {
    testsToAdd.add(testToAdd);
}

private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;
    DefaultMutableTreeNode test = null;

    category = new DefaultMutableTreeNode("14 February 2014");
    top.add(category);

    for (testInfo newTest : testsToAdd) {
        category.add((MutableTreeNode) newTest);
    }

    category = new DefaultMutableTreeNode("13 february 2014");
    top.add(category);

    //TODO Tests for previous dates
}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event dispatch thread.
 */
private static void createAndShowGUI() {
    if (useSystemLookAndFeel) {
        try {
            UIManager.setLookAndFeel(
                    UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.err.println("Couldn't use system look and feel.");
        }
    }

    //Create and set up the window.
    JFrame frame = new JFrame("My Excel Reader");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add content to the window.
    frame.add(new ExcelReaderGui());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                re.setInputFile("D:\\Users\\liagordo\\java\\RMG\\dashboard.xls");
                re.read();
            } catch (IOException e) {
                System.out.println("Error reading excel file");
                e.printStackTrace();
            }
            createAndShowGUI();
        }
    });
}
}

當我運行前面的代碼時,收到錯誤消息:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: 
com.main.ExcelReaderGui$testInfo cannot be cast to javax.swing.tree.MutableTreeNode
at com.main.ExcelReaderGui.createNodes(ExcelReaderGui.java:157)
at com.main.ExcelReaderGui.<init>(ExcelReaderGui.java:53)
at com.main.ExcelReaderGui.createAndShowGUI(ExcelReaderGui.java:186)
at com.main.ExcelReaderGui.access$1(ExcelReaderGui.java:171)
at com.main.ExcelReaderGui$1.run(ExcelReaderGui.java:205)

您正在嘗試將這段代碼中的testInfo對象轉換為MutableTreeNode

category.add((MutableTreeNode) newTest);

這是不可能的。因為將testInfoMutableTreeNodetestInfoMutableTreeNode應該具有繼承關系,但是在您的代碼中它們之間沒有任何繼承關系

當我花了很長時間試圖找到答案時,我討厭它,然后將其發布在Stack Overflow上,然后不久我就得到了答案。 為了解決這個問題,我改變了:

for (testInfo newTest : testsToAdd) {
    category.add((MutableTreeNode) newTest);
}

至 :

for (testInfo newTest : testsToAdd) {
test = new DefaultMutableTreeNode(newTest);
category.add(test);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM