I'm writing a Java program that has a button with an action listener:
JButton button = new JButton("Change");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText(textField.getText());
}
});
At the top of the file, I have these two import statements:
import java.awt.*;
import javax.swing.*;
I know this is terrible practice, I am revising for an exam and it's way easier and quicker to just write that at the top of the page.
I get an error, however, telling me to import java.awt.event.ActionListener
If the event package is inside java.awt and I used the wildcard * to import everything, then why is it not being imported??
Here is the definition of type-import-on-demand in the Java Language Specification:
A type-import-on-demand declaration allows all accessible types of a named package or type to be imported as needed.
TypeImportOnDemandDeclaration:
importPackageOrTypeName . * ;
It is important to understand the terminology: "all accessible types of a named package" means all the types whose package declaration is specifically the one before the .*.
So, if a class's package is defined like:
package my.pkg.name;
Then it will be available to import my.pkg.name.*, but if a class is defined like:
package my.pkg.name.subname;
Then it will not be available to import my.pkg.name.*, because it does not belong to that package. It specifically belongs to my.pkg.name.subname which is - as far as Java is concerned - a different package.
It is true that Java implementations normally expect the packages to be ordered in a directory hierarchy, so the directory for my.pkg.name.subname is going to be under the directory of my.pkg.name. If you think of it, supposed you wrote
ls my/pkg/name/*
In that directory. It behaves very much the same: it would give you only the files under this directory directly, not the directories further under it. The semantics of type-import-on-demand is pretty much the same (excluding the subname "directory" itself, because it is not a type).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With