Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java swing component cannot be resolved

I took the following code from a tutorial:

import javax.swing.*;
import java.util.Date;

public class SwingGUI {

    public static void main( String[] args )
      {
        JFrame f = new JFrame( "test" );
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        f.setSize( 1500, 900 );
        JLabel l = new JLabel( String.format( "%tT", new Date() ) );
        f.add(l);
        f.setVisible( true );
      }
}

The f.add(l); is highlighted and two errors are shown:

  • The method add(Component) in the type Container is not applicable for the arguments (JLabel)

  • The type javax.swing.JComponent cannot be resolved. It is indirectly referenced from required .class files

Being relatively new to java, I do not really understand what Eclipse is trying to tell me. What can I do to make it work?

edit: The code runs without the line f.add(l);, so the problem is not that JFrame or JLabel are not found. After fiddeling around a little I got rid of the first error, but the second still remains. The component cannot be resolved, because it is indirectly referenced. What does that mean?

like image 768
Ludwitch Avatar asked Feb 18 '15 11:02

Ludwitch


People also ask

Can not be resolved to a type Java?

This means that your project isn't setup to include the JUnit libraries when it compiles; JUnit is not included in the Java runtime libraries (JRE System Library) so you have to add it to the build path.

Why does the Java Runtime Environment shutdown after showing a swing Jframe component?

It is due to JRE misconfiguration for project.

What is import javax swing?

Provides interfaces that enable the development of input methods that can be used with any Java runtime environment. javax.swing. Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.


1 Answers

I faced the same issue and found that my project was using the Java 8 libraries. I installed the Java 7 library, added the same to the project properties by referencing the library from the installed C:\Program Files\Java folder and the error was gone.

Looks like, the new Java 8 version may a different way to resolve the swing component.

like image 187
Anand Nanavati Avatar answered Nov 02 '22 03:11

Anand Nanavati