我该如何解决 ClassCastException?可能是 JFileChooser 的 Casting 错误

How can I solve ClassCastException? Maybe it is mistake of Casting of JFileChooser

目的

我正在定制一个应用程序供个人使用。这个应用程序可以在 Java 中制作许多 midi 文件。 我想一次性从列表中选择多个文件并将其保存为 zip 文件。

问题

出现如下错误信息。 我该如何解决 ClassCastException?也许是 JFileChooser 的 Cast 的 mitake。

(错误信息)

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: camidion.chordhelper.midieditor.PlaylistTableModel cannot be cast to javax.swing.JFileChooser
at camidion.chordhelper.midieditor.PlaylistTableModel$SelectedSequenceAction.setEnebledBySelection(PlaylistTableModel.java:188)
at camidion.chordhelper.midieditor.PlaylistTableModel$SelectedSequenceAction.init(PlaylistTableModel.java:195)
at camidion.chordhelper.midieditor.PlaylistTableModel$SelectedSequenceAction.<init>(PlaylistTableModel.java:177)

at camidion.chordhelper.midieditor.MidiSequenceEditorDialog$SequenceListTable.<init>(MidiSequenceEditorDialog.java:442)
at camidion.chordhelper.midieditor.MidiSequenceEditorDialog$SequenceListTable.<init>(MidiSequenceEditorDialog.java:444)
at camidion.chordhelper.midieditor.MidiSequenceEditorDialog.<init>(MidiSequenceEditorDialog.java:1182)

at camidion.chordhelper.ChordHelperApplet.init(ChordHelperApplet.java:477)

at camidion.chordhelper.MidiChordHelper$AppletFrame.<init>(MidiChordHelper.java:72)
at camidion.chordhelper.MidiChordHelper.run(MidiChordHelper.java:48)

at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access0(EventQueue.java:97)
at java.awt.EventQueue.run(EventQueue.java:709)
at java.awt.EventQueue.run(EventQueue.java:703)

at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

源代码

(我的想法)

PlayListTableModel.class

    public ListSelectionModel sequenceListSelectionModel = new DefaultListSelectionModel() {
    {
        setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    }
};

-

来自"protected void setEnebledBySelection() {....",错误消息在这里。

public abstract class SelectedSequenceAction extends AbstractAction implements ListSelectionListener {
    public SelectedSequenceAction(String name, Icon icon, String tooltip) {
        super(name,icon); init(tooltip);
    }
    public SelectedSequenceAction(String name, String tooltip) {
        super(name); init(tooltip);
    }
    @Override
    public void valueChanged(ListSelectionEvent e) {
        if( e.getValueIsAdjusting() ) return;
        setEnebledBySelection();
    }
    protected void setEnebledBySelection() {
        JFileChooser filechooser = new JFileChooser();
        filechooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        filechooser.setMultiSelectionEnabled(true);
        File[] index = ((JFileChooser) sequenceListSelectionModel).getSelectedFiles();
        setEnabled(index != null);
    }
    private void init(String tooltip) {
        putValue(Action.SHORT_DESCRIPTION, tooltip);
        sequenceListSelectionModel.addListSelectionListener(this);
        setEnebledBySelection();
    }
}

-

MidiSequenceEditerDialog

            /**
         * This is about Action for files
         */
        public Action saveMidiFileAction = getModel().new SelectedSequenceAction(
            "Save",
            "Save selected MIDI sequence to file"
        ) {
            @Override
            public void actionPerformed(ActionEvent event) {
                PlaylistTableModel playlistModel = getModel();
                SequenceTrackListTableModel sequenceModel = playlistModel.getSelectedSequenceModel();
                String fn = sequenceModel.getFilename();
                if( fn != null && ! fn.isEmpty() ) setSelectedFile(new File(fn));
                if( showSaveDialog((Component)event.getSource()) != JFileChooser.APPROVE_OPTION ) return;
                File[] f = getSelectedFiles();


                try {
                    ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/Users/DANIEL/Downloads"));
                    byte[] buffer = new byte[1024];
                    int len;
                    }
                    for(File files : f) {
                        InputStream in = new FileInputStream(files);
                        out.putNextEntry(new ZipEntry(files.getName()));
                        while ((len = in.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }
                        in.close();
                    }
                    out.close();

                } catch(FileNotFoundException e){
                    e.printStackTrace();
                    showError(e.getMessage());
                } catch(Exception e){
                    e.printStackTrace();
                    showError(e.getMessage());
                }
            }
        };

(原装线)

PlayListTableModel.class(原创)

public ListSelectionModel sequenceListSelectionModel = new DefaultListSelectionModel() {
    {
        setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    }
};

-

public abstract class SelectedSequenceAction extends AbstractAction implements ListSelectionListener {
    public SelectedSequenceAction(String name, Icon icon, String tooltip) {
        super(name,icon); init(tooltip);
    }
    public SelectedSequenceAction(String name, String tooltip) {
        super(name); init(tooltip);
    }
    @Override
    public void valueChanged(ListSelectionEvent e) {
        if( e.getValueIsAdjusting() ) return;
        setEnebledBySelection();
    }
    protected void setEnebledBySelection() {
        int index = sequenceListSelectionModel.getMinSelectionIndex();
        setEnabled(index >= 0);
    }
    private void init(String tooltip) {
        putValue(Action.SHORT_DESCRIPTION, tooltip);
        sequenceListSelectionModel.addListSelectionListener(this);
        setEnebledBySelection();
    }
}

-

MidiSequenceEditerDialog(原创)

        public Action saveMidiFileAction = getModel().new SelectedSequenceAction(
            "Save",
            "Save selected MIDI sequence to file"
        ) {
            @Override
            public void actionPerformed(ActionEvent event) {
                PlaylistTableModel playlistModel = getModel();
                SequenceTrackListTableModel sequenceModel = playlistModel.getSelectedSequenceModel();
                String fn = sequenceModel.getFilename();
                if( fn != null && ! fn.isEmpty() ) setSelectedFile(new File(fn));
                if( showSaveDialog((Component)event.getSource()) != JFileChooser.APPROVE_OPTION ) return;
                File f = getSelectedFile();
                if( f.exists() ) {
                    fn = f.getName();
                    if( ! confirm("Overwrite " + fn + " ?\n" + fn + " is OK?") ) return;
                }
                try ( FileOutputStream out = new FileOutputStream(f) ) {
                    out.write(sequenceModel.getMIDIdata());
                    sequenceModel.setModified(false);
                    playlistModel.fireSequenceModified(sequenceModel, false);
                }
                catch( IOException ex ) {
                    ex.printStackTrace();
                    showError( ex.getMessage() );
                }
            }
        };

ClassCastException 通常在您将某些对象转换为给定类型时发生,但它在运行时不会具有此类型。

例如:

public void foo(Object o) {
   ((MyObject) o).someFunction();
}

在这里,代码将编译,因为 Object 是所有对象的超 class,但您需要注意您的对象在运行时将被键入为 MyObject。

编辑:

你做到了:

File[] index = ((JFileChooser) sequenceListSelectionModel).getSelectedFiles();

您确定 sequenceListSelectionModel 可以转换为 JFileChooser 吗?