Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: Exception with add()

2k Views Asked by At

EDIT2: Ok, I hope this is how you do it. Below is the thinned version of the classes I used. The error still persists if I have all the Getters and Setters inside the SurfaceObject() classe, but seems to disappear if I exclude them. Which is quite weird. Even weird is that it also seems to appear if the variables are all private, and not, as in the example, protected. So I would like to know why that's the case: Main Class (Builds JFrame):

import javax.swing.JFrame;
public class FileCreator extends JFrame{
    private static FileCreator chooseAction;
    private Container contain;
    public static final int framewidth = 800;
    public static final int frameheight = 600;
    private final String[] iconName = {"Load File"};
    public static void main(String[] args) {
        chooseAction = new FileCreator();
    }
    public FileCreator(){
        super("Editor");
        contain = new Container(iconName, this);
        add(contain);
        setSize(framewidth,frameheight);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);

    }
}

This class builds the container and adds the cards to it (First Card is holdContent, second Card is the FirstOptionPanel). It also adds the ActionListener MainListener, which in turn calls the createPanel()-Method

import java.awt.CardLayout;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JPanel;
class Container extends JPanel {
    private FirstOptionPanel[] panels = new FirstOptionPanel[9];
    private final String[] cardNames = { "card1", "File Loaded" };
    private JButton[] buttons;
    private MainMenuListener main;
    private int contentWidth = 410, contentHeight = 300;
    private CardLayout cards;
    Container(String[] buttonName,
            FileCreator creator) {
        super();
        setLayout(cards = new CardLayout());
        setSize(FileCreator.framewidth, FileCreator.frameheight);
        buttons = new JButton[buttonName.length];
        int i = 0;
        buttons[i] = new JButton(buttonName[i]);
        main = new MainMenuListener(this, creator);
            buttons[i].addActionListener(main);
        JPanel card1 = new JPanel();
        card1.setSize(getWidth(), getHeight());
        card1.setLayout(null);
        JPanel holdContent = new JPanel();
        holdContent.setSize(contentWidth, contentHeight);
        holdContent.setLocation((FileCreator.framewidth - contentWidth) / 2,
                (FileCreator.frameheight - contentHeight) / 2);
        holdContent.add(buttons[i]);
        card1.add(holdContent);
        add(card1, cardNames[0]);
    }
    public JButton[] getButtons() {
        return buttons;
    }
    public void createPanel(int i, File selectedFile) {
        panels[i] = new FirstOptionPanel(selectedFile);
        add(panels[i], cardNames[i + 1]);
        cards.show(this, cardNames[i + 1]);
    }
}

This class is the ActionListener. It just registers the pressed button and calls the createPanel()-method upon pressing load File. However, the JFileChooser does nothing in this version. Normally, it loads the file and passes it.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MainMenuListener implements ActionListener {
    private JButton[] buttons;
    private JPanel[] panellist;
    private Container container;
    private JFileChooser jf;
    private FileCreator creator;
    public MainMenuListener(Container container, FileCreator creator) {
        // TODO Auto-generated constructor stub
        buttons= container.getButtons();
        this.creator = creator;
        panellist = container.getPanels();
        this.container = container;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        for(int i = 0; i<buttons.length;i++){if(i == 0){
                jf = new JFileChooser();
                int returnValue = jf.showOpenDialog(container);     
                if(returnValue == JFileChooser.APPROVE_OPTION){
                    container.createPanel(i, jf.getSelectedFile());
                }else       if(returnValue == JFileChooser.CANCEL_OPTION){
                    JOptionPane.showMessageDialog(creator, "No File selected!");
                }

            }
        }
    }
    }

This here is the FirstOptionPanel class. It's a JPanel that creates other JPanels (in this case a single entry-Object), and then displays them:

import java.io.File;
import javax.swing.JPanel;

public class FirstOptionPanel extends JPanel{
    private SurfaceObject[] entries;
    JPanel buttonHolder;
    public FirstOptionPanel(File selectedFile) {
        // TODO Auto-generated constructor stub
        super();
        setSize(FileCreator.framewidth, FileCreator.frameheight);
        setLayout(null);
        createObjects();
            }
    public FirstOptionPanel() {
        // TODO Auto-generated constructor stub
        super();
    }
    private void createObjects() {
                entries = new SurfaceObject[1];
                    entries[0] = new SurfaceObject("ENTRIES{|,Logo1,,1,,100,,100,,100,,100,|}");
                    add(entries[0]);
                }

}

And finally, the SurfaceObject class. The aforementioned SurfaceEntry-Class extends this class. SurfaceEntry() is not used here, but the error still occurs. But only if I have all these different getters() and setters(). If I don't include them, the programm runs just fine. Even though I don't actually use them yet!(Large File ahead):

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MouseInfo;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class SurfaceObject extends JPanel{
    /**
     * 
     */
    private String iconName;
    private int id;
    int coordinates[] = new int[2];
    int momentaryCoord[] = new int[2];
    protected boolean imageNotFound;
    protected int[] sizeOfRectangle = new int[2];
    protected String pictureName;
    protected ImageIcon momentaryPicture;
    protected Image img;
    protected boolean mouseInAction;
    protected Dimension d;
    protected boolean selected;
    private FirstOptionPanel parent;
    public SurfaceObject(String group) {
        super();
    }

    @Override
    protected void paintComponent(Graphics g) {
        // TODO Auto-generated method stub
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        if (!imageNotFound) {
            g2.drawImage(img, 0, 0, null);
            System.out.println("shown");
        } else {
            System.out.println("Drawn");
            g2.setColor(Color.blue);
            g2.fillRect(0, 0, 200, 200);
        }

    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public final String getIconName() {
        return iconName;
    }

    public final void setIconName(String iconName) {
        this.iconName = iconName;
    }

    public final int getId() {
        return id;
    }

    public final void setId(int id) {
        this.id = id;
    }

    public final int[] getCoordinates() {
        return coordinates;
    }

    public final void setCoordinates(int[] coordinates) {
        this.coordinates = coordinates;
    }

    public final int[] getMomentaryCoord() {
        return momentaryCoord;
    }

    public final void setMomentaryCoord(int[] momentaryCoord) {
        this.momentaryCoord = momentaryCoord;
    }

    public final boolean isImageNotFound() {
        return imageNotFound;
    }

    public final void setImageNotFound(boolean imageNotFound) {
        this.imageNotFound = imageNotFound;
    }

    public final int[] getSizeOfRectangle() {
        return sizeOfRectangle;
    }

    public final void setSizeOfRectangle(int[] sizeOfRectangle) {
        this.sizeOfRectangle = sizeOfRectangle;
    }

    public final String getPictureName() {
        return pictureName;
    }

    public final void setPictureName(String pictureName) {
        this.pictureName = pictureName;
    }

    public final ImageIcon getMomentaryPicture() {
        return momentaryPicture;
    }

    public final void setMomentaryPicture(ImageIcon momentaryPicture) {
        this.momentaryPicture = momentaryPicture;
    }

    public final Image getImg() {
        return img;
    }

    public final void setImg(Image img) {
        this.img = img;
    }

    public final Dimension getD() {
        return d;
    }

    public final void setD(Dimension d) {
        this.d = d;
    }

    public final boolean isMouseInAction() {
        return mouseInAction;
    }

    public final FirstOptionPanel getParent() {
        return parent;
    }

}

This is the error message I get when I run the programm:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException
at javax.swing.LayoutComparator.compare(Unknown Source)
at javax.swing.LayoutComparator.compare(Unknown Source)
at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.enumerateAndSortCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFocusTraversalCycle(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.LayoutFocusTraversalPolicy.getFirstComponent(Unknown Source)
at javax.swing.SortingFocusTraversalPolicy.getDefaultComponent(Unknown Source)
at java.awt.FocusTraversalPolicy.getInitialComponent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.SequencedEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

I hope this is enough of an explanation to work with. Thanks in advance,

Nicolai

1

There are 1 best solutions below

5
On

Found the answer to my question. For anyone wondering, it seems as if Java has a problem with the method "public FirstOptionPanel getParent()" of my SurfaceObject()-class. I explain this to myself with the reasoning that it is a method from a superclass. Which somehow makes it impossible to be created in another thread? If anyone has a more probable answer, I'm inclined to listen to it. (Eclipse just generated that get-method like that, I wouldn't have done it like that myself. If I change the methods name, the program works just fine)