Hello Everyone,

I am experiencing errors when trying to compile a project in Java 8. The errors are caused by swing components. The code I am using is the following:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main2 {

    public Main2(){
        JFrame f = new JFrame ();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(100, 100);
        JPanel p = new JPanel();
        JLabel l = new JLabel("Test");
        p.add(l);
        f.add(p);

        f.setVisible(true);

    }

    public static void main(String[] args) {
        new Main2();
    }

}

The problems are caused by the p.add(l) and the f.add(p). They throw a The method add(JLabel) is undefined for the type JPanel and a The method add(Component) in the type Container is not applicable for the arguments (JPanel) error respectively. I have tried cleaning the project, and I have searched through all the solutions online and none of them worked. If I change f.add(p) to f.getRootPane().add(l) then it throws a The type javax.swing.JComponent cannot be resolved. It is indirectly referenced from required .class files. I have tried reinstalling the JDK, but I still have no success.

If I change the version of the JDK to 1.7 then the code works prefectly fine. The error is just with Java 8.

The exact versions of JDK I am using is 1.8.0_45 and 1.7.0_11

Thank you for any help.

Following is my Java version I got by running java -version and you code perfectly compiled for me

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) Client VM (build 25.45-b02, mixed mode)

well... that code won't cause any trouble, not in Java7, not in Java8 ...
I'm not exactly sure what is going wrong on your machine, but it looks like there is something wrong with your (class)path. It can't find the JComponent class, which might cause some issues (since it's the parent class of JPanel).

I agree. It's an installation problem. Possibly missing files, but more likely some old files that are sitting in the classpath somewhere and masking the Java 8 versions. I would formally uninstall all Java versions, then manually search & destroy all java-related directories, and delete the classpath variables, then download and re-install JDK 8 from scratch. Also if you are using an IDE that may have some old Java version code associated with it, so I would delete & download/re-install that as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.