Hi I had a program which worked fine in a .jar file.
Basically all the classes were part of the same package called : "eu.floraresearch.lablib.gui.checkboxtree"
They ALL are located in the SAME "checkboxTree" folder. Each file has a line stating
package eu.floraresearch.lablib.gui.checkboxtree;
I need to modify the code and to integrate it in another project.
So I took all the .java files, copied them in my Eclipse project folder (no package anymore), and got rid of the "package eu.floraresearch.lablib.gui.checkboxtree;" line in each files. Everything is fine except for one file comprising an enumeration.
Originally the file looked like this:
package eu.floraresearch.lablib.gui.checkboxtree;
public class QuadristateButtonModel extends DefaultButtonModel {
public enum State {
CHECKED, GREY_CHECKED, GREY_UNCHECKED, UNCHECKED
}
...
}
The problem is, there is another class which originally imported the above class enumeration:
import eu.floraresearch.lablib.gui.checkboxtree.QuadristateButtonModel.State;
public class QuadristateCheckbox extends JCheckBox {
public QuadristateCheckbox() {
this(null);
}
public QuadristateCheckbox(String text) {
this(text, State.UNCHECKED);
}
...
}
First of all I find it weird how enumerations can be imported.. But it worked fine when everything was inside the package.
Since all my .java files are in the same folder now, I just removed the package line.
However I have this issue with the QuadristateCheckbox class which imports "QuadristateButtonModel.State".
If I change the import line with
import QuadristateButtonModel.State;
it states
The import QuadristateButtonModel cannot be resolved
I tried various things I found on the internet like
import static QuadristateButtonModel.State.*;
or
import QuadristateButtonModel.State.*;
but the same error messages occur:
The import QuadristateButtonModel cannot be resolved
On top of that, in the above code from QuadristateCheckbox class:
public QuadristateCheckbox(String text) {
this(text, State.UNCHECKED);
}
an error message
State cannot be resolved to a variable
which is understandable given the fact that I fail to import the State enumeration.
What can I do? Please explain to me what is wrong
PS: The code was taken from this site: http://www.javaworld.com/article/2077762/core-java/swing-based-tree-layouts-with-checkboxtree.html
The authors provide classes to build checkable trees.
Related
So, I have a package "com", which consists of two sub-packages "Common" and "Model1". The Model1 contains a class Model which I am trying to import in the Servlet2 class, which resides in the Common package. I compile the Model class first which stays fine, but the Servlet2 class doesn't and comes up with an error saying "package com.Model1 doesn't exist"
Here's the Model class:
package com.Model1;
import java.util.*;
**public** class Model{
public ArrayList<String> getBrands(String color){
ArrayList<String> brands=new ArrayList<String>();
if(color.equals("amber")){
brands.add("Jack Amber");
brands.add("Red Moose");
}
else{
brands.add("Jail Pale Ale");
brands.add("Gout Stout");
}
return brands;
}
}
Here's the Servle2 class:
package com.Common;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.Model1.Model;
public class Servlet2 extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("Coffee selection advice<br>");
String c=req.getParameter("color");
Model m=new Model();
ArrayList result=m.getBrands(c);
out.println("<br>Got coffee color "+c);
Iterator it=result.iterator();
while(it.hasNext()){
out.println("<br> Try: "+it.next());
}
}
}
I just can't seem to figure out how to sort this out.
Edit: Realised that default modifier is restrictive, but even making it public doesn't seem to work.
I am using notepad++ and I hope this works as the Minimal, Complete, and Verifiable example:
package com.common;
import com.model.*;
public class TheClassIWantToImportInto {
public static void main(String[] args){
System.out.println("Testing 1");
TheClassIwantToImport obj=new TheClassIWantToImportInto();
obj.testFunction();
}
}
The second class:
package com.model;
public class TheClassIWantToImport{
public void testFunction(){
System.out.println("testing function");
}
}
Both the .java files are in the same folder "C:\Program Files\Java\jdk1.8.0_161\bin"
Using the following commands in this order:
javac -d . TheClassIWantToImport.java (Works fine)
javac -d . TheClassIWantToImportInto.java (Error: package com.model doesn't exist)
Set up your project such that you have some root dir which is your project's main directory. Let's call that /Users/you/projects/MyCoolProject
Within that, make a src/main dir which will contain your sources. A source file goes in a directory that matches its package declaration. com.Model1 is a bad package name for three reasons. Convention states not to start them with caps, convention states that they are supposed to represent either your reverse website or failing that, at least the project name, and finally 'model1' is not descriptive. So let's go with package com.mycompany.coolproject.vehicleModel; instead. In that case, your Model class should be on your disk at /Users/you/projects/MyCoolProject/src/main/com/mycompany/coolproject/vehicleModel/Model.java
Use a build tool such as maven or gradle to build your project. This is going to be a lot simpler than trying to manually make javac do the right thing here. If you MUST use java, make dir build in /users/you/projects/MyCoolProject, make sure you're in that directory, and then try: javac -d build -sourcepath src/main src/main/com/mycompany/coolproject/vehicleModel/*.java and note that you'll have to add a path to that every time you make another package (to avoid having to do that... use maven or gradle).
Once you've done that, this error goes away (the error indicates that javac can't find the other source file because your project isn't properly set up yet. The above instructions lead to a properly set up project, with javac/maven/gradle being capable of finding all your source files as needed, and it's how almost all java programmers work).
I am testing a few Java API, I've created my project called 'MyLearning' where all my src files are located, in src I created another Package callede 'myfiles', now when I import the java.nio.file.Files API, IntelliJ doesn't show me suggestions for this class. But in the main package i.e src folder, the suggestion works totally fine.
Example:
The above picture shows my main src folder, where the Files API works totally fine.
But then in the new Package that I've created i.e myfiles, it is showing error on retrieving the methods of Files API. Error is
Cannot resolve symbol 'exists'
Can anyone tell me what could be the poblem here?
You have to put method calls inside a method.
public void foo()
{
Files.exists(path);
}
I also noticed that one of the tags you put is intellij-14. The latest version of IntelliJ is 2016.2.
You have to call it in a method, not in the class
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
Path path = Paths.get("C:\\log.txt");
System.out.println(Files.exists(path));
}
}
This might be a duplicate, but I cannot find an answer using the below answers and many other sites on the internet...
My conundrum:
I am attempting to (poorly) run some classes from a jar in jsp. Effectively what I have is the following:
<%#page import="edu.cs242.hadoop.*" %>
<%
... do some stuff ...
MRSearcher ss = new MRSearcher();
... do some stuff ...
%>
But every time I try to run the jsp I get the following error:
An error occurred at line: 32 in the jsp file: /hadoop.jsp
MRSearcher cannot be resolved to a type
My webapp structure looks like:
/
|hadoop.jsp
|lucene.jsp
|index.jsp
|WEB-INF/
|lib/
|lucene.jar
|hadoop.jar
|classes/
|*.java for our hadoop.jar
I've tried calling the jar itself and compiling the java through tomcat, both produce the same results.
Here is a snippet from our MRSearcher class:
package edu.cs242.hadoop;
import java.io.*;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
/**
* Created by cloudera on 3/10/14.
*/
public class MRSearcher {
MRSearcher() {}
public String[] run(String arg1, String arg2) {
String[] things = new String[] {};
// do stuff
return things;
}
}
There are other classes, but this one is the one that allows us to interface with the rest of the program. The main is in a file called: Main.java, and it does nothing but runs this for command line output. The syntax is correct as we can run the main and retrieve output.
I don't mean to sound insolent, but please don't comment on the futility and awfulness of including things like JAR files in JSP. This is never going to production, it's a school project that doesn't need the necessity of correctness, it needs the necessity of functioning. If I were doing this for a job I would do it right, but right now I don't care about learning about the correct way to separate logic and presentation layers in JSP -- I can do that just fine in other languages and understand the concept very well.
I have looked through and attempted to use the following solutions before posting this, all of this has failed:
how to run jar file methods in jsp
How to call method from jar file in JSP?
how to reference an external jar in jsp app?
And more to try to solve this problem.
In WEB-INF/classes/ you must have MRSearcher.class file. Keep in mind JSP files are compiled first time you access it, so your project can compile although your JSP are not well.
On the other hand, your MRSearcher() constructor must be public, if you omitte this, by default the constructor will be package and cannot be accessed from other packages. Check if your Main.java class is in same package of MRSearcher. If yes, this is why it can invoke MRSearcher constructor.
I hope this helps you.
Regards,
Consider the following simple example of code:
public class TestStaticImport {
static enum Branches {
APPLE,
IBM
}
public static void doSomething(Branches branch) {
if (branch == APPLE) {
System.out.println("Apple");
}
}
}
If we will try to compile this code, we will get the error message:
java: cannot find symbol
symbol: variable APPLE
location: class TestStaticImport
This could be solved by introducing static import of this enum:
import static ... TestStaticImport.Branches.*
But in this moment incomprehensible things (for me) begin:
this solution works fine, everything is well compiled, until class TestStaticImport will be moved into empty root package, i.e. there isn't any
package blablabla; in the top of this java file;
Code line: import static TestStaticImport.Branches.*; is highlighted as valid code in my Intellij IDEA (name of IDE doesn't matter, just for information), but when I try to compile such code following error appears:
java: package TestStaticImport does not exist
So, there are actually two questions:
1) Main question: why is it impossible to import static from empty directory?
2) What is another way (if it exists) for allowing in code references to enum's fields using just their names (i.e. APPLE instead of Branches.APPLE), except static import?
P.S. Please, don't tell me, that empty packages is ugly style and so on. This question is just theoretical problem.
The Java language specification forbids any imports from the unnamed package:
A type in an unnamed package (§7.4.2) has no canonical name, so the
requirement for a canonical name in every kind of import declaration
implies that (a) types in an unnamed package cannot be imported, and
(b) static members of types in an unnamed package cannot be imported.
As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time
error on any attempt to import a type (or static member thereof) in an
unnamed package.
In ancient times, the Java inventors had to map Java types to files so the compiler could do some real work. They decided to map packages to folders and types to files. That worked pretty well. It especially set the emotional background for newcomers: "I hate you. Don't mess with me." But I digress.
The default package is a problem, though, since it doesn't have a well defined folder. If you have package com, you know that there is a folder com somewhere but what's the name of the folder for the default package?
So the designers decided that import and default package don't mix. In fact, you get an error when you try to import anything that has no package (i.e. import TestStaticImport without the static and * would also fail). See How to import a class from default package
So the problem isn't the static import but that you try to import from the default package.
Like some other corner cases in Java, there is no solution.
see also: In Java- "Static Members of the default package cannot be imported"- Can some one explain this statement?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
eclipse 3.4 (ganymede) package collision with type
I'm new in java, but i tried to write a script for a game Lineage2.
heres a code:
package ZergZ.ZTeleport;
import javolution.util.FastMap;
import com.l2jserver.Config;
import com.l2jserver.gameserver.handler.IVoicedCommandHandler;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
import com.l2jserver.gameserver.model.Location;
import com.l2jserver.gameserver.handler.VoicedCommandHandler;
public class ZTeleport implements IVoicedCommandHandler
{
private static final String[] VOICED_COMMANDS =
{
"teleport"
};
#Override
public boolean useVoicedCommand(String command, L2PcInstance activeChar, String params)
{
if (activeChar == null)
return false;
if (params.equalsIgnoreCase("aden"))
{
activeChar.teleToLocation(147736,-56243,-2781);
}
if (params.equalsIgnoreCase("gracia"))
{
activeChar.teleToLocation(-186742,244167,2675);
}
if (params.equalsIgnoreCase("pvp1"))
{
activeChar.teleToLocation(147736,-56243,-2781);
}
if (params.equalsIgnoreCase("pvp2"))
{
activeChar.teleToLocation(179337,221937,4475);
}
}
#Override
public String[] getVoicedCommandList()
{
return VOICED_COMMANDS;
}
}
when server starts java says:
1. ERROR in \ZTeleport.java (at line 17)
package ZergZ.ZTeleport;
^^^^^^^^^^^^^^^^^^^^
The package ZergZ.ZTeleport collides with a type
the script is situated in ZergZ/ZTeleport.java
I'll give you another script which works fine:
package custom.HeroCirclet;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.quest.Quest;
import com.l2jserver.gameserver.model.quest.QuestState;
public class HeroCirclet extends Quest
{
______
}
Thanks.
You say "the script is situated in ZergZ/ZTeleport.java". This implies that the class ZTeleport belongs to the package ZergZ. But you have declared it as belonging to a different package, ZergZ.ZTeleport.
In your second example, I would bet that the source file is located in custom/HeroCirclet/HeroCirclet.java, which matches its package declaration, and does not create a naming conflict.
You either need to move the source file (people normally don't call java source files "scripts", btw) into a directory that matches its declared package, or change the package declaration to match its location.
It's because you have a class named ZTeleport in the ZergZ package and a package named ZergZ.ZTeleport.
The package name is basically the project directory where the Java file is situated.
That means if ZTeleport.java is in ZergZ directory, then the package name is
package ZergZ;
You don't specify the class name on package declaration and directory are separated with a . and not directory folder token.
The collision here is between your package name and your class name, which are the same. If you stick to the usual naming conventions (naming your packages with a starting lower case and your classes with a starting upper case), you should avoid such situations.
You should follow Java naming conventions. Change your package into:
package zergZ.zTeleport; // all name is begin with lower
// no change, but for clearer : all class name should begin with higher character
public class ZTeleport implements IVoicedCommandHandler
{
}
After that, for sure, you should refresh or/and rebuild your project to see it works.
Hope this help :)
If you see the error it says...
package ZergZ.ZTeleport;
^^^^^^^^^^^^^^^^^^^^
The package ZergZ.ZTeleport collides with a type
So basically you have created a conflict between the way you have named your class and the package. If you stick to java conventions you could name them as:
// Notice the first character of package name is small character
package zergZ.zTeleport;
// Class Name's first character is capital.
public class ZTeleport implements IVoicedCommandHandler{
..
}