When do I need to import java.awt.*? If I want to import javax.swing.* do I need to also import java.awt.*?

19,496

Solution 1

You import awt if you use awt types, no more, no less.

I can't remember if I need to import java.awt.* to use anything in javax.swing.* or would I have imported java.awt.* for another reason? In other words, what is the purpose of importing java.awt.* ?

The purpose is to use any classes in the AWT library. Most would recommend that you import only the specific classes that you're using, no more, no less.

I was under the impression everything I needed to use JButton, JFrame, etc. was in javax.swing.*.

This will almost never be true. Most Java programs that are more than toy programs will need to use many libraries. For instance, most layout classes are held in the AWT library. Most listeners are held in the java.awt.event library.

Note that you don't have to import anything if you choose to use fully qualified type names.

e.g.,

java.awt.BorderLayout myBorderLayout = new java.awt.BorderLayout(5, 5);

Solution 2

These are from javax.swing.*

JFrame
JButton

These are from java.awt.*

Component
Color

You can make a window without java.awt.*

public class Frame extends JFrame{
    public static void main(String[] args){
        new Frame();
    }
    public Frame(){
        super("Frame");
        this.setVisible(true);
    }
}

If you wanted to, I prefer not to, you can use a fully qualified class name.

javax.swing.JFrame = new javax.swing.JFrame();

If you do this, you can make a program without importing anything.

Share:
19,496
krisharmas
Author by

krisharmas

Updated on June 05, 2022

Comments

  • krisharmas
    krisharmas almost 2 years

    I'm getting back into Java and reviewing some of my old code and I'm seeing a lot of places where I have done

    import javax.swing.*;
    import java.awt.*;
    

    or actually importing specific classes from the swing/awt packages. I can't remember if I need to import java.awt.* to use anything in javax.swing.* or would I have imported java.awt.* for another reason? In other words, what is the purpose of importing java.awt.* ? I was under the impression everything I needed to use JButton, JFrame, etc. was in javax.swing.*.