Abstract static?

Hi. I have this question. I have a class, say "City", which has a static method, City.getList(), which returns an Object[] with all the available cities. I also have a Class "State" , which also has a .getList() method which returns an Object[] with all available states.
I made a JPanel with a Jtextfield and a JList. The textfield, when the user has entered 3 or more characters, does a .getList(String filter) that loads the JList with the data from the database, so I can make a quick search.
The problem is that I want to make it generic, so I made an interface "ProvidesAList" with the methods getList() and getList(String filter). So when I call the constructor for this JPanel, I have to provide it with the kind of "thing" i want to be able to search. That is, if I want to search cities, I call the constructor referencing a City object. But the problem is that I don't want to provide an object, but just a class name, as in, for example, new SearchBox(Class.forName("City"));
What I did was, declare the constructor as
SearchBox(ProvidesAList thing)
and then calling it as
new SearchBox(new City());
it works because City implements ProvidesAList.
My problem is, I don't want to create an instance of city, or state, or whatever, every time I want to make a quick search. Also I use the .getList() methods elsewhere in the code, and I don't want to create an object jus to use that methods. So I want to define the methods as static, so all I have to do is ClassName.getList();
But I can't define the methods in ProvidesAList as static (because Interfaces cannot have static methods).
How can I have this? I wouldn't want to make parent class with the static methods because it would be nasty to have a "ProvidesAList" class and City extends ProvidesAList, State extends ProvidesAList, and Customer extends ProvidesAList.

Well, if the City and State classes have things going on other than merely providing these lists, then yeah, you should preserve their identities rather than combining them. But I still think you should write a class for AutoCompleteModel and consider your city and state data separate from those classes. Why hard code a list of cities when the requirements could change tomorrow?
Also, the City and State model is going to collapse if someone in Japan ever tries to use your program. So the model I would suggest at this point is this:
class Area
Has a String member for its name and a single Area member for a parent area (for example, if this instance represents a city then the parent instance is a state... if the instance is a state the parent represents the U.S.) and an Area[] for children areas (if this instance is a state, its children are cities). Methods for traversing parents and children make this class a kind of node that can be used to build arbitrary hierarchies. Maybe has a String member for indicating its geopolitical classification ("city", "state", "ward", "principality"...)
class AutoCompleteModel
Has a String[] for the data to be matched against, and methods for matching. Can be instantiated from an array and/or file, InputStream, etc.
Isn't that solution both more conceptually simple (albeit not coding-simple) and comprehensive?
If you do not want to spend the extra time to program a truly GOOD solution, because for example this is just for some lame homework project or something, then my answer changes to:
Just get over the peeve about instantiating objects and use the solution you have already come up with. There is no need for multiple instances - just keep a reference to the instance you already made.
Rule of thumb: if the way the language is structured conflicts with your design approach, there is a high chance that your design approach is not so good anyway.
Not to be all high and mighty or anything. Actually I ran into this exact issue a few months ago (a couple months after I started Java), except that there was no question of pre-set data in my case. The solution I settled on was pretty much what I say above.
Drake

Similar Messages

  • Abstract static methods

    Hello,
    I've written an abstract class, called AbstractNetworkParticipant. I've also written two sub classes that extend this class. I'm in the process of writing a Viewer class that I'm intending to parameterized with some subclass of AbstractNetworkParticipant,
    public class Viewer<T extends AbstractNetworkParticipant> I would like to include a couple of static methods that return Strings for Labeling information to a particular subclass in the Viewer.
    So for example, if I have NetworkUser and NetworkAdministrator, both of which extend AbstractNetworkParticipant, I would like to set the text of a JLabel labeling the participant's name to "User Name", or "Administrator Name" depending on the type of participant being viewed.
    I would like the method that returns these strings to be static, so that I don't have to have an instance of the current subclass when I initializes the JLabel. An abstract method cannot be static. I attempted to make a non-abstract static method in the abstract class,
      public static getDescriptor() {
         return "Participant";
      }and then override it in each sub class to a more descriptive string (User, or Administrator). However, when I reference the method, it always invokes the method defined in the abstract parent class, rather than in the subclass, whichever it may be.
    Can anyone suggest a solution. Should I just forget about the method being static? Is there a better way to implement a solution to this problem?
    Thanks
    Edited by: paulwooten on Mar 27, 2009 9:58 AM

    paulwooten wrote:
    The whole point of my original post was in order to learn something about Java that I'm not particularly familiar with. I was having a difficult time articulating the problem precisely, so I tried to draw an analogy between C++ and Java. It turns out I was mistaken in the way C++ works. Fortunately I described my problem adequately enough to both 1. be corrected about how virtual functions actually work in C++, and 2. get advice on how to approach the problem in Java. I never claimed I was a C++ expert, or that I was asking a question about C++. I was just trying to explain my problem as precisely as possible.
    I don't mean to disrespect, but your post, and slimy's aren't nearly as constructive as all the other posts that actually addressed my question; either to me personally, or to anyone else who has a similar question and may happen to read this thread. It's not like I dumped a bunch of C++ code here and begged someone to translate it for me. I asked a question, to the best of my ability, several other forum members replied (without giving me a mini lecture on how to learn Java), and now the problem is resolved.Sorry for the confusion. I wasn't complaining about your post. My post wasn't directed at you at all. It's fine to know C++, and to ask how to do something similar in Java. As you said, that wasn't even how you asked your original question. You asked a legitimate question to learn Java, a few people made suggestions, you made a comparison to C++, and people corrected your understanding both of C++ and Java. That's all well and good, and it's a fair way to learn. I see no problem with any of that.
    What exactly does "learn Java properly" mean? Read the tutorials and pretend like no other programming languages exist?I was referring to slimy's post where he talked about "knowing C++ properly if you use it as an input to Java". The point of my post was supposed to be that "you can know C++ properly, but +you shouldn't always use that as your input to Java+". A very simple example I've seen of what I meant by "non-proper" Java code, in real [but +bad+ ] Java code at a real company is for String comparison:
    String abc = "abc";
    String xyz = "xyz";
    String another = "xyz";
    if (abc.compareTo(xyz) != 0) { // Not "proper" Java
       doSomething();
    if (xyz.compareTo(another) == 0) { // Not "proper" Java
       doSomethingElse()
    }To me, that looks like someone who copied their C++ knowledge (or, at least, C knowledge) to the extreme. In C, the only function to test equality of two C "strings"--i.e., "null-terminated char arrays" is 'strcmp', and you test equality of the strcmp result to 0 to determine whether two "null-terminated char arrays" represent the same thing:
    char abc [] = "abc";
    char xyz [] = "xyz";
    char another [] = "xyz";
    if (strcmp(abc, xyz)) { // could include explicit != 0, but not needed in C
       doSomething();
    if (!strcmp(xyz, another)) { // anything non-zero is true in C, so !0 is true
       doSomethingElse();
    }"compareTo" sounds like "strcmp", and the comparison to 0 is the same in my above examples.
    But, in Java, there is a real "equals" method for Strings, and it should be used:
    String abc = "abc";
    String xyz = "xyz";
    String another = "xyz";
    if (!abc.equals(xyz)) { // "proper" Java
       doSomething();
    if (xyz.equals(another)) { // "proper" Java
       doSomethingElse()
    }I would argue that using "compareTo" to test equality of Strings in Java is "non-proper" Java, and using "equals" to test equality of Strings in Java is "proper" Java. That was my definition of "learning Java properly".
    I certainly don't think anyone learning Java needs to pretend that no other programming languages exist--it is fine to know other languages, and to look for the similarities (and differences). However, someone learning Java (or any other language new to them) does need to know that things don't work the same in all languages, so, if they base all of their knowledge by trying to get Java to work exactly the same as C++ (or whatever previous language they knew), their Java will not be "proper" Java. There are often multiple ways to do things "properly" in Java, but copying a C++ program verbatim into Java syntax is not necessarily going to result in the best Java code that you could have. When doing the translation from another language to Java (I realize that isn't your goal, but for some people, that is the goal), you need to be sure that your Java code follows Java rules and standards, and not just assume that the architecture of your Java code should be the same as the architecture of your code in the original language.
    I hope that clarifies my intentions. As I said, I wasn't directing my previous comment to you. I think your question and learning approach are absolutely fine.

  • I really need abstract static methods in abstract class

    Hello all.. I have a problem,
    I seem to really need abstract static methods.. but they are not supported.. but I think the JVM should implement them.. i just need them!
    Or can someone else explain me how to do this without abstract static methods:
    abstract class A {
    abstract static Y getY();
    static X getX() {
        // this methods uses getY, for example:
        y=getY();
       return new X(y); // or whatever
    class B extends A {
    static Y getY() { return YofB; }
    class C extends A {
    static Y getY() { return YofC; }
    // code that actually uses the classes above:
    // these are static calls
    B.getX();
    A.getX();I know this wont compile. How should i do it to implement the same?

    Damn i posted this in the wrong thread.. anyways.
    Yes offcourse i understand abstract and static
    But i have a problem where the only solution is to use them both.
    I think it is theoretically possible ot implement a JVM with support for abstract static methods.
    In fact it is a design decision to not support abstract static methods.. thats why i am asking this question.. how could you implemented this otherwise?
    There is an ugly soluition i think: using Aspect Oriented Programming with for example AspectJ.. but that solution is really ugly. So anyone has an OO solution?

  • Static abstract inner classes

    Sorry to sound stupid, but why would a class be static? I've encountered an example of an abstract static inner class and I'm not sure why it's static. Static methods I understand -- they are methods of the class and not the instance. So then, can someone explain to me a static class?
    Thanks,
    Erik

    You have encountered a static nested class (not a static inner class - an inner class is a nested class that is not static).
    A static nested class is a nested class that does not require an instance of its enclosing class to exist in order that it can be instantiated. - It is mainly used for code organisation, and can be treated just like a top-level class.
    In practice, most nested classes (except perhaps event handlers), tend to be static.
    For an example of a static nested class from the core APIs, have a look at HasMap.Entry

  • Forcing implementation of an inherited static method/field?

    Suppose I have some classes - BlueAction, RedAction etc - extending an abstract base class called BaseAction. I put an abstract method called getColour() in BaseAction, and implement it in all the classes that extend it, so BlueAction returns blue, and so on. Fine.
    I now want to use a class loader to get their colour, but crucially, I don't want to instantiate them, so instance methods are out.
    If you could declare abstract static methods, I'd do that, and be assured that every implementation of BaseAction contained the necessary info. Obviously you can't do this.
    I think I could just put a static method or field in each one, and access that via something like Class.getField("COLOUR")but then there's nothing to force me to put that code into each implementation.
    Is there anything clever I can do?
    Cheers,
    Rob
    Edited by: arewenotmen on Jun 20, 2008 3:51 AM

    baftos wrote:
    I guess it should be possible. Me, I did play with runtime annotations, but I am scared like hell
    of compile time annotation. My reasons, but maybe I am wrong:All good reasons.
    - Modify the build process to use APT instead of javacYou could use in -nocompile mode and add a task to the build script.
    - Writing annotation processors, big overheadI had a play, was not too hard to get started with, but then it started to get wierd and data I expected was not being returned.
    - Using com.sun classes in the processors instead of java/javax classes (subject to change?)Java 6 has the javax.annotations package (also works with javac rather than a different tool), but this seams less powerful than apt.
    A fair few things now mean the "don't touch the com.sun package" rule is being eroded. The httpd is in it as well.

  • Static methods in interfaces

    Java cognoscenti,
    Anyone know why I can't declare a method as static in an interface, but I can in an abstract class. Surely, semantically it's the same - defering the implementation of a static method, not an abstract class and an interface. By the way, I'm using JDK 1.2.2 if that makes a difference

    No, it's not the same. You are not "defering the
    implementation of a static method" because static
    methods are never polymorphic.
    Static methods cannot be abstract for this reason, and
    only abstract methods are allowed in interfaces.I didnt't know that. I thought that - because you can override static methods and you can call them onto an actual instance the method binding would be done at run-time, not at compile-time. So I was trying to prove you wrong, but you are correct !
    A short summary of what I've learnt so far:
    - interfaces cannot contain static methods
    - abstract classes cannot contain abstract static methods
    - static methods can be overriden, but they are not polymorphic; this means that the compiler decides which method to call at compile-time.
    /* output
    SuperClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    SuperClass.someMethod()
    SubClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    public class Test {
      public final static void main(String[] args) {
          // output: SuperClass.someMethod()
          new SuperClass().someMethod();
          // output: SubClass.someMethod()
          new SubClass().someMethod();
          // output: 2x SuperClass.someMethod()
          SuperClass someClass1 = new SubClass();
          someClass1.someMethod();
          showSuper(someClass1);
          // output: 2x SubClass.someMethod()
          SubClass someClass2 = new SubClass();
          someClass2.someMethod();
          showSub(someClass2);
          showSuper(someClass2); // SuperClass.someMethod()
      public final static void showSuper(SuperClass c) {
            c.someMethod();
      public final static void showSub(SubClass c) {
            c.someMethod();
    class SuperClass {
      public static void someMethod() {
        System.out.println("SuperClass.someMethod()");
    class SubClass extends SuperClass {
      public static void someMethod() {
        System.out.println("SubClass.someMethod()");

  • Static Interface Fields

    public interface interface {
         static public field = 1;
         public void methods();
    when is this correct to use in the OOP/Software Pattern paradigm?
    I thought interfaces were only there to define behaviors (i.e. methods)
    What are static fields doing here?
    Why are static methods not allowed in interfaces while static fields are?
    Thanks

    public interface interface {
         static public field = 1;
         public void methods();
    }Indded it should be public static final (i.e., constants). The compiler supports not specifying final, and adds it automatically, but one should make that explicit.
    when is this correct to use in the OOP/Software
    Pattern paradigm?Unlike the previous posters, I don't find that bad against OO principle.
    If a constant is logically related to the capabilities defined by an interface, it's not a bad thing in itself to declare the constants in the interface's namespace.
    public interface HairDressable {
      public static final int BLONDE = 0;
      public static final int RED = 2;
      public static final int BLACK = 3;
      public void haveHairCut();
      public void haveColorChanged(int newColor);
      public int getHairColor();
    }All classes implementing the interface automaticaly see the constant, and can refer to it without prefixing by the interface name. public class PomPomGirl implements HairDressable {
      public void haveColorChanged(int newColor) {
        if (this.favoriteTeam.getName().equals("Red Socks") && (newColor!=RED)) {...}
    }Any class not implementing the interface can also refer to the constant, by prefixing with the interface's name, as in public class RedTeamFanClub {
    public void makeUp(PomPomGirl pomPomGirl) {
        pomPomGirl.haveColorChanged(HairDressable.RED);
    } What IS bad is to have a class implement the interface only for the sake of referring to the variable without prefixing, like public class HairDresser implements HairDressable {
      public void handleFancyLady(Bimbo bimbo) {
        bimbo.changeColor(RED);
      // Dummy implementation of method that should belong here
      public void haveHairCut() {}
      public void haveColorChanged(int  c) {}
      public int getHairColor() {return BLACK;}
    I thought interfaces were only there to define
    behaviors (i.e. methods) I would say "to advertise capabilities".
    Here both changing the color and getting the current color are capabilities that involve a notion of color that is common to all HairDressable implementing classes. I deem defining this notion in the interface itself makes sense.
    (OK, defining this notion as a bunch of int constants is not very well engineered, but let's keep the discussion focused).
    Now there's the pragmatic approach too : if you define constants in your interface, you run the risk that a bad programmers will someday implement the interface only to lazily refer to the constant.
    But you run that risk with abstract classes too - yes, I've seen that!
    Why are static methods not allowed in interfaces while
    static fields are?Only static final fields, which makes a difference.
    Static methods don't advertise the capabilites of an object. And they can't be overridden.
    Neither does a constant, in itself, but there's a point in defining the constant in the scope where it makes the most logical sense.
    For completeness, note there's an RFE on the BugParade to add statis methods to interfaces (http://developer.java.sun.com/developer/bugParade/bugs/4093687.html).
    As I understand it, and although I don't support it, I think there's a point in defining a static method and its implementation in an interface, so as to, in the same vein as for the constants, put in the interface's scope a method whose implementation logically has a meaning for all implementing classes of the interface
    (I'd say such methods are rare enough not to deserve a language change).
    But it seems ugly (and fortunately impossible at that point) to add the notion of "abstract static methods" that an interface could declare and all implementing class would have to implement.

  • Abstract Singleton Class?

    hi all
    i have an abstract class and i want to extend it such that it becomes a singleton. However i wish i can also gain the benefits of abstraction so that i can reference the abstract class whatever the concrete class that extends it
    so how can i write the "getInstance()" method in both the abstract and concrete classes knowing that i can't create an abstract static method?!
    thanks in advance

    this has nothing to do with my question
    my question is:
    if you have class A abstract and class B inherits from class A
    then i want to make class A a singleton with a single underlaying instance of class B
    such that when i call A.getInstance() it first checks if the instance it has is null it creates a new object from class B and use it as an instance but ofcourse it has to be general to all several subclasses to be used according to each case.

  • Inner static class implementing interface

    Hello,
    I have a sample program to test on reflections. here the code goes
    import java.lang.reflect.*;
    import java.awt.*;
    import java.lang.*;
    import java.io.*;
    public class SampleName {
       public static void main(String[] args) {
          NewClass b = new NewClass();
           System.out.println("Calling printModifiers");
           printModifiers(b);
             System.out.println("Calling printInterfaces");
           printInterfaces(b);
       static void printModifiers(Object obj){
              Class cl = obj.getClass();
              int mod = cl.getModifiers();
              if(Modifier.isPublic(mod ))
                   System.out.println("Public");
              if(Modifier.isPrivate(mod ))
                   System.out.println("Private");
              if(Modifier.isFinal(mod ))
                   System.out.println("Final");
              if(Modifier.isStatic(mod ))
                   System.out.println("Static");
              if(Modifier.isAbstract(mod ))
                   System.out.println("Abstract");
       static void printInterfaces(Object o) {
              Class c = o.getClass();
              String str = c.getName();
              System.out.println("name  " +str);
              Class[]  theInterfaces= c.getInterfaces();
              if(theInterfaces.length ==0)
                   System.out.println("no interfaces here ");
              else
                   for(int counter = 0; counter<theInterfaces.length;counter++)
                             String interfaceName = theInterfaces[counter].getName();
                             System.out.println("Interface Name :- " +interfaceName);
    static class NewClass implements newInterface {
    }i have an interface in t same folder as
    public interface newInterface
    }i get an error as below while compiling this java code
    SampleName.java:54: cannot resolve symbol
    symbol  : class newInterface
    location: class SampleName.NewClass
    static class NewClass implements newInterface {
                                      ^
    1 errorplease explain me what is the fault i am making and how can it be resolved.
    tnx

    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    The Gateway to Classpath Nirvana
    Setting the class path (Windows)
    How Classes are Found

  • Abstraction problem

    I'm trying to develop a CommandFactory that can, given a known set of parameters, instantiate one Command in a dynamic set of Commands.
    class CommandFactory
      Hashtable commandKeys;
      private static CommandFactory instance = null;
      private CommandFactory()
        //code that initializes and populates commandKeys
      public static CommandFactory getInstance()
        if( instance == null ) instance = new CommandFactory();
      public Command parse( String cmd )
        String key = cmd.substring(0,cmd.indexOf(" "));
        String cmd_parms = cmd.substring( cmd.indexOf(" ")+1 );
        Method m = (Method)commandKeys.get(key);
        return (Command) m.invoke( null, new Object[] { cmd_parms } );
    public abstract class Command
      public abstract execute();
    }Now, I'd like to be able to know at compile time that every sub-class of Command has a static method defined such as:
    //adding to my above Command a bit
    abstract class Command
      public abstract void execute();
      public abstract static Command parse( String cmd );
    class CommandSubclass
      public void execute()
        //do something
      public static Command parse( String cmd )
        //does something
       return newCommand;
    }The closest thing I can think of to naming what I want here is an abstract static method. That way at compile-time I know with certainty that the Command subclasses have the proper tidbits to initialize and give me back a Command.
    Now, I know that Java does not support abstract static methods. And what I've done instead is just assume that my various Command classes have the "parse" static method. But I run the risk of not knowing until run-time that a Command subclass does not have the needed static method.
    Essentially, I need a means to enforce a uniform way of initializing subclasses of an abstract superclass. Anyone know how to get that other than reflection, hoping, and praying? Or, is there a different pattern I should be using here?
    Thanks,
    --mb

    It removes the ability of the Factory to say what it should/should not have. No, an interface places no such restriction. What you have is three different problems:
    1/how to delegate the instantiation of command objects to command specific mappings.
    2/how to load the mappings of command names to the instantiation mechanism at runtime
    and now you have
    3/ the factory to have a say in what mappings it will support.
    1/ is handled perfectly well using interfaces and registry/delegate factory objects; it's convienent to implement these factories as command prototypes, but not necessary, hence there are separate factory and command interfaces.
    2/ would be handled by loading the mappings from some data source together with an expression for instantiting the factory instances, together with a controlling registry factory that delegates to the specific factories. One mechanism for this is java.beans.XMLEncoder, or you can hand craft your own restricted version using Class.forName().newInstance. In the above example I didn't do this for you, and created the registry as part of initialising the application.
    3/ you've just introduced and you haven't specified what more control you want inside the factory-registery that 1 + 2 don't give you.
    I already have the mechanism of telling the Factory what factories it should use to build it's look-up table.So use that mechanism to populate the registry, instead of the test code above.
    I suppose an alternative is to have the Factory act as a kind of security manager. This seems to be extra to the previous requirements; what do you want it to do as well as being a factory?
    As CommandFactory subclasses are loaded, they create an instance of them, and attempt to register with the top-level CommandFactory to build a look-up or chain of responsibility -- just like your static block. Yes. Though typically I'd use a more flexible mechanism, so that you can load the class without it registering. The static block above in is the class that sets up the application, not the class that implements CommandFactory. If you put the registration code there, then you are forced to have a singleton registry and it becomes tightly bound to one use pattern, and hard to maintain.
    Also, when the CommandFactory is instantiated, it can forName all the classes it knows it's looking for to ensure they are loaded.They will be loaded when you create an instance to register. You don't need to do any extra calls to forName. You can use the forName to implement the creation of an instance to register, or you can use the more flexible mechanism built into XmlEncoder. Don't rely on subclasses implementing a particualar registration mechanism, but separate that to a different place. So the only thing that a correct implementation of CommandFactory does is implement a method that creates a command. That way, everything is part of the contract.
    ...but isn't it bad coding practice to initialize in static code blocks?No. They exist exactly for the purpose of initialising static state; you just have to ensure you don't throw any exceptions and are aware of load-order dependencies. They're also useful for throwaway stuff like the example above, where you want to set up global state for tests rather than writing a full application. But don't use them to do things which are not required to load the class- there's a very big difference between flow of control in the code above and:class EchoCommand extends PrototypeCommand {
      public void execute () {
        System.out.println(args);
      static {
        MB10Command.register.register("echo", new EchoCommand());
    class SortCommand extends PrototypeCommand {
      public void execute () {
        List sort = new ArrayList(args);
        Collections.sort(sort);
        System.out.println(sort);
      static {
        MB10Command.register.register("sort", new SortCommand());
    public class MB10Command {
      static CommandRegister register = new CommandRegister();
      static {
        new EchoCommand();
        new SortCommand();
      public static void main (String[] args) {
        register.parse(args).execute();
    }Because EchoCommand is tied to one particular global registry, it's unusable in any other context, and you end up thinking about adding extra code to overcome the hard coded global variable (otherwise known as singleton anti-pattern).
    You also lose the expression of intent- in the previous code, when you load the main class, you explicitly create a registry, then register a couple of prototypes with it. If you start using static blocks so that a side-effect of loading a class is that it registers a prototype with a third party, and then use Class.forName so that registration is a side-effect of a side-effect, you will get very confused very rapidly. Keep both implementation and state as local as possible.
    Pete

  • Retrieve values from database

    Hi,
    one of the search form contains the select option for country , state and
    distributor type.
    the country drop down has 2 values - US and canada
    the conditions needed to be satisfied are :
    (1) if the country selected is US - then the states dropdown should only show the states that are associated with US in the table in the database(TABLE name is - "distributors")
    and if country selected is Canada - then should show states in canada only
    (2) if canada is selected in the country dropdown, the distributor type which has 2 values - stationary and automotive - should show only the stationary in the dropdown and not show the automotive
    This is done with the LocateQueryServlet.java...can someone please tell me how this needs to be updates so that the above conditions are satisfied...
    Attaching the code from LocateQueryServlet.java and the prolog.sql
    --------------------------------------------------------------------------------------------------LocateQueryServlet.java
    package com.dupont.refrigerants.distributorlocator;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Iterator;
    import java.util.List;
    import javax.ejb.CreateException;
    import javax.naming.NamingException;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.proxicom.util.MiscEJBFunctions;
    * This servlet displays a query form for locating distributors. It relies on
    * the 'countries', 'states' and 'types' tables in the database to fill its
    * forms. If a table is empty, it doesn't display the corresponding select
    * (pulldown) widget. This only displays the form fragment of HTML, and should
    * be included in a complete page, probably with JSP or the like.
    * XXX Currently, the form is populated when the servlet is initialized, which
    * is a hack because I don't remember the appropriate j2ee idiom.
    * @web.servlet name="queryServlet" display-name="Distributor Locator Query
    * Servlet" description="Servlet that gets a query form for finding
    * distributors in a given region"
    * @web.servlet-mapping url-pattern="/queryServlet"
    public class LocateQueryServlet extends HttpServlet {
         * Abstract class for converting a java object into
         * an option element for an HTML select form widget.
         private abstract static class Object2Option {
              * Gets the default option at the top of the select.
              * To have no default, override this to return the
              * empty string.
              * @return <code>>option selected='true' value=''<-- Select One -->/option<</code>
              public String getDefault() {
                   return "<option selected='true' value=''>-- Select One --</option>";
              * The option element that represents the given info object.
              * @param o the info object
              * @return an unselected HTML option element.
              abstract public String getOptionFor(Object o);
              * Helper method for generating a select option element
              * with the given un-encoded value and text.
              * @param value
              * unencoded string to be passed as the form
              * value when selected
              * @param text
              * unencoded string to be displayed in the select
              * box pulldown
              * @return the concatenated and appropriately escaped
              * option element
              protected static String getOptionWith(String value, String text) {
                   return "<option value='" + Utilities.webify(value, false) + "'>"
                             + Utilities.webify(text, false) + "</option>";
         * Function object for generating 'Country' select box items.
         private static class Object2CountryOption extends Object2Option {
              * Converts a CountryInformation object into an appropriate
              * HTML option element.
              public String getOptionFor(Object o) {
                   CountryInformation c = (CountryInformation) o;
                   return getOptionWith(c.getCode(), c.getName());
         * Function object for generating 'Distributor Type' select box items.
         private static class Object2DistributorTypeOption extends Object2Option {
              * Converts a DistributorTypeInformation object into an appropriate
              * HTML option element.
              public String getOptionFor(Object o) {
                   DistributorTypeInformation c = (DistributorTypeInformation) o;
                   return getOptionWith(String.valueOf(c.getId()), c.getDescription());
         * Function object for generating 'State/Province' select box items.
         private static class Object2StateOption extends Object2Option {
              * Converts a StateInformation object into an appropriate
              * HTML option element.
              public String getOptionFor(Object o) {
                   StateInformation c = (StateInformation) o;
                   return getOptionWith(c.getCode(), c.getName());
         private String countries;
         private String states;
         private String types;
         * Constructs a simple locate query servlet.
         public LocateQueryServlet() {
              super();
         * Generates an HTML select form widget for the given list of values.
         * @param formName the name of the widget for the HTML name attribute
         * @param values the values to convert into a list
         * @param factory the method for converting each value into an option.
         * @return the complete 'select' element
         private String generateSelectFor(String formName, List values,
                   Object2Option factory) {
              StringBuffer sb = new StringBuffer();
              sb.append("<select name='").append(Utilities.webify(formName, false)).append("'>");
              sb.append(factory.getDefault());
              for (Iterator iter = values.iterator(); iter.hasNext();) {
                   sb.append(factory.getOptionFor(iter.next()));
              sb.append("</select>");
              return sb.toString();
         * Initializes the servlet. Actually results in some queries getting run.
         * @param config
         * @throws ServletException
         public void init(ServletConfig config) throws ServletException {
              try {
                   DistributorDBABeanHome distBean = (DistributorDBABeanHome) MiscEJBFunctions.getBeanHomeInterface(null, null, Utilities.EJB_DISTRIBUTOR_DBA_NAME);
                   DistributorDBABean dists = distBean.create();
                   this.countries = this.generateSelectFor("country", dists.getCountries(),
                             new Object2CountryOption());
                   this.states = this.generateSelectFor("state", dists.getStates(),
                             new Object2StateOption());
                   this.types = this.generateSelectFor("type", dists.getDistributorTypes(),
                             new Object2DistributorTypeOption());
              } catch (NamingException e) {
                   throw new ServletException("Lookup of "
                             + Utilities.EJB_DISTRIBUTOR_DBA_NAME + " failed", e);
              } catch (CreateException e) {
                   throw new ServletException(
                             "Error while creating distributor session bean", e);
              } catch (java.rmi.RemoteException e) {
                   throw new ServletException(
                             "Error while initializing distributor locator", e);
         * Executes the HTTP request and return the appropriate HTML form fragment.
         * @param request
         * @param response
         * @throws ServletException
         * @throws IOException
         protected void doGet(HttpServletRequest request,
                   HttpServletResponse response) throws ServletException, IOException {
              PrintWriter out = response.getWriter();
              response.setContentType("text/html");
              String action = request.getParameter("action");
              if (action == null) {
                   action = "where-to-buy-results";
              } else {
                   action = Utilities.webify(action, false);
              // Open form and table elements.
              out.println("<form id='distributorLocator' action='" + action + "' method='get'>"
                                  + "<table width='100%' border='0' cellpadding='4' cellspacing='0'>");
              // buffer row
              //out.println("<tr><td colspan='2'><hr width='65%' size='1' noshade></td></tr>");
              // 'Country' row
              out.println("<tr><td><div align='right' class='formSubHead'>Country:</div></td>"
                                  + "<td>" + this.countries + "</td></tr>");
              // 'States' row
              out.println("<tr><td><div align='right' class='formSubHead'>State/Province:</div></td>"
                                  + "<td>" + this.states + "</td></tr>");
              // 'Application' row
              out.println("<tr><td><div align='right' class='formSubHead'>Application:</div></td>");
              out.println("<td>" + this.types + "</td></tr>");
              // or row
              out.println("<tr><td><div align='right'></div></td><td><em><strong>or</strong></em></td></tr>");
              // zip code row
              out.println("<tr><td><div align='right' class='formSubHead'>Zip Code/Postal Code: </div></td>"
                                  + "<td><input id='zip' name='zip' type='text' /></td></tr>");
              // buffer row
              out.println("<tr><td colspan='2'><hr width='65%' size='1' noshade></td></tr>");
              // submit row
              out.println("<tr><td> </td><td><input type='submit' value='Find' /></td></tr>");
              // end table and form
              out.println("</table></form>");
    prolog.sql
    SET DEFINE OFF;
    CREATE SEQUENCE distributor_id_seq START WITH 1 INCREMENT BY 1 NOMAXVALUE;
    CREATE TABLE countries (code CHAR(2), name VARCHAR(254),
         CONSTRAINT country_pk PRIMARY KEY(code));
    CREATE TABLE states (code CHAR(5), name VARCHAR(254), country CHAR(2),
         CONSTRAINT state_pk PRIMARY KEY(code),
         CONSTRAINT fk_country FOREIGN KEY(country) REFERENCES countries(code));
    CREATE TABLE distributorTypes (id INTEGER, name VARCHAR(254),
         CONSTRAINT distributorType_pk PRIMARY KEY(id));
    CREATE TABLE distributors
         (id INTEGER,
         name VARCHAR(254),
         zip VARCHAR(12),
         country CHAR(2),
         state CHAR(5),
         city VARCHAR(63),
         address1 VARCHAR(254),
         address2 VARCHAR(254),
         fax VARCHAR(32),
         phone VARCHAR(32),
         managers VARCHAR(254),
         type INTEGER,
         email VARCHAR(254),
         url VARCHAR(254),
         CONSTRAINT distributor_pk PRIMARY KEY(id),
         CONSTRAINT fk_dist_country FOREIGN KEY(country) REFERENCES countries(code),
         CONSTRAINT fk_dist_state FOREIGN KEY(state) REFERENCES states(code),
         CONSTRAINT fk_dist_type FOREIGN KEY(type) REFERENCES distributorTypes(id));
    CREATE TABLE statesApply (state CHAR(5), distributor INTEGER,
         CONSTRAINT fk_apply_state FOREIGN KEY(state) REFERENCES states(code),
         CONSTRAINT fk_apply_distributor FOREIGN KEY(distributor) REFERENCES distributors(id));
    INSERT INTO
              distributorTypes (id, name) VALUES (1, 'Air Conditioning - Stationary and Refrigeration');
    INSERT INTO
              distributorTypes (id, name) VALUES (2, 'Air Conditioning - Automotive');
    INSERT INTO
              countries (code, name) VALUES ('CA', 'Canada');
    INSERT INTO
              countries (code, name) VALUES ('US', 'United States of America');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_AL', 'Alabama');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_KS', 'Kansas');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_ND', 'North Dakota');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_AK', 'Alaska');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_KY', 'Kentucky');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_MP', 'N. Mariana Islands');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_AS', 'American Samoa');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_LA', 'Louisiana');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_OH', 'Ohio');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_AZ', 'Arizona');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_ME', 'Maine');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_OK', 'Oklahoma');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_AR', 'Arkansas');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_MH', 'Marshall Islands');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_OR', 'Oregon');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_CA', 'California');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_MD', 'Maryland');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_PW', 'Palau');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_CO', 'Colorado');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_MA', 'Massachusetts');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_PA', 'Pennsylvania');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_CT', 'Connecticut');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_MI', 'Michigan');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_PR', 'Puerto Rico');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_DE', 'Deleware');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_MN', 'Minnesota');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_RI', 'Rhode Island');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_DC', 'District of Columbia');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_MS', 'Mississippi');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_SC', 'South Carolina');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_FM', 'FS Micronesia');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_MO', 'Missouri');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_SD', 'South Dakota');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_FL', 'Florida');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_MT', 'Montana');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_TN', 'Tennessee');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_GA', 'Georgia');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_NE', 'Nebraska');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_TX', 'Texas');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_GU', 'Guam');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_NV', 'Nevada');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_UT', 'Utah');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_HI', 'Hawaii');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_NH', 'New Hampshire');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_VT', 'Vermont');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_ID', 'Idaho');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_NJ', 'New Jersey');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_VI', 'Virgin Islands');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_IL', 'Illinois');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_NM', 'New Mexico');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_VA', 'Virginia');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_IN', 'Indiana');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_NY', 'New York');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_WA', 'Washington');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_IA', 'Iowa');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_NC', 'North Carolina');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_WV', 'West Virginia');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_WI', 'Wisconsin');
    INSERT INTO
              states (country, code, name) VALUES ('US', 'US_WY', 'Wyoming');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_AB', 'Alberta');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_BC', 'British Columbia');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_MB', 'Manitoba');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_NB', 'New Brunswick');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_NL', 'Newfoundland and Labrador');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_NS', 'Nova Scotia');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_NT', 'Northwest Territories');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_NU', 'Nunavut');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_ON', 'Ontario');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_PE', 'Prince Edward Island');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_QC', 'Qu�bec');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_SK', 'Saskatchewan');
    INSERT INTO
              states (country, code, name) VALUES ('CA', 'CA_YT', 'Yukon');
    Any immediate help is truly appreciated.
    Thanks in advance

    I thank you for the link, it's something I've already done several times ....
    actually this code tries to manage a key incremental, I am obliged to do that because I am in MS SQL Server and therefore what works for oracle does not work for SQL Server, which is why I want to do it manual, I also posted this in a previous post and I was asked to retrieve the field value by Code: Help please : dbsequence refresh on MS sql server
    now admitting that it is not what I want to do and I have the following code:
    if (it1.getValue () == null) (
    Connection connection = ConnectionManager.getInstance (). GetConnection ();
    Statement statement = connection.createStatement ();
    ResultSet resultset = statement.executeQuery ("SELECT id FROM WHERE name = spider" it2.getValue + () + "");
    while (resultSet.next ())
    it1.setValue (resultSet.getInt (1));
    BindingContainer getBindings bindings = ();
    OperationBinding operationBinding bindings.getOperationBinding = ("Commit");
    OperationBinding.execute Object result = ();
    if (! operationBinding.getErrors (). isEmpty ()) (
    return null;
    else (
    BindingContainer bindings2 getBindings = ();
    OperationBinding operationBinding2 bindings2.getOperationBinding = ("Commit");
    OperationBinding2.execute Object result = ();
    if (! operationBinding2.getErrors (). isEmpty ()) (
    return null;
    What code ADF BC I will put in place of jdbc code

  • Set fields of derived class in base class constructor via reflection?

    Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
    Many thanks for your feedback!
    Norman
    public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
    abstract static class A {
        A() {
            try {
                getClass().getDeclaredField("x").setInt(this, 42);
            } catch (Exception e) {
                throw new RuntimeException(e);
    static class B extends A {
        int x;
        B() {
        B(int x) {
            this.x = x;
    public void testThatItWorks() {
        assertEquals(42, new B().x);
        assertEquals(99, new B(99).x);
    }

    why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
    Framework:
    public abstract class Operator {
        public abstract void initialize();
    }Plug-In:
    public class SomeOperator extends Operator {
        @Parameter(defaultValue="42", interval="[0,100)")
        double threshold;
        @Parameter(defaultValue="C", valueSet="A,B,C")
        String mode;
        public void setThreshold(double threshold) {this.threshold = threshold;}
        public void setMode(String mode) {this.mode = mode;}
        // called by the framework after default values have been set
        public void initialize() {
    }On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance.

  • Compiles well with eclipse but not with javac

    Hello.
    I am using Windows XP and eclipse 3.0.2.
    I have j2sdk-1_4_2_07-windows also.
    I built class files from the code below with eclipse.
    On jre, It silently runs and exits as expected.
    But when compiled with javac, It does not.
    It dumps a stack trace.
    Which compiler is right?
    public class ANullPointerException {
         private Object o = new Object();
         private Sub sub = new Sub();
         private abstract static class Super {
              protected abstract Object access();
              private Super() {
                   access();
         private class Sub extends Super {
              protected Object access() {
                   return o;
         public static void main(String[] args) {
              new ANullPointerException();
    }the stack trace was as below
    java.lang.NullPointerException
         at ANullPointerException.access$200(ANullPointerException.java:1)
         at ANullPointerException$Sub.access(ANullPointerException.java:15)
         at ANullPointerException$Super.<init>(ANullPointerException.java:9)
         at ANullPointerException$Super.<init>(ANullPointerException.java:5)
         at ANullPointerException$Sub.<init>(ANullPointerException.java:13)
         at ANullPointerException$Sub.<init>(ANullPointerException.java:13)
         at ANullPointerException.<init>(ANullPointerException.java:3)
         at ANullPointerException.main(ANullPointerException.java:20)
    Exception in thread "main" I found 3 class files built by eclipse. They were
    ANullPointerException$Sub.class,
    ANullPointerException$Super.class and
    ANullPointerException.class.
    No missing or extra files found, I think.
    But I found 4 class files built by javac. They were
    ANullPointerException$1.class,
    ANullPointerException$Sub.class,
    ANullPointerException$Super.class and
    ANullPointerException.class.
    I do not know why ANullPointerException$1.class is needed.
    Thank you in advance.

    I found the answer myself.
    I have been setting the eclipse's .class file compatibility to 1.4.
    But it is not javac's default.
    So all I need to do is javac -target 1.4 ANullPointerException.java.
    Sorry for a noise

  • Incorrect ClassDoc for nested classes

    Hello,
    I think there is a bug in Javadoc concerning nested classes ClassDoc records extracted through the doclet API.
    In particular, ClassDoc records are correct if the container class is directly specified on the command line as a .java file or part of a package (i.e. the source is available), but they are (at times) wrong if the records are built from .jar (.class) files through the classpath.
    Example with "java.io.ObjectOutputStream" from JDK 1.3.1_01:
    If the ClassDoc for this class comes from RootDoc.specifiedClasses(), its nested classes are correctly listed as:
    private static final class java.io.ObjectOutputStream.HandleTable
    public abstract static class java.io.ObjectOutputStream.PutField
    static final class java.io.ObjectOutputStream.PutFieldImpl
    private static final class java.io.ObjectOutputStream.ReplaceTable
    private static final class java.io.ObjectOutputStream.Stack
    but if the ClassDoc of the container class is extracted from a method parameter, like in org.apache.xerces.dom.ParentNode.writeObject(ObjectOutputStream out), this is the result:
    final synchronized class java.io.ObjectOutputStream$HandleTable
    public abstract static class java.io.ObjectOutputStream.PutField
    static final class java.io.ObjectOutputStream.PutFieldImpl
    final synchronized class java.io.ObjectOutputStream$ReplaceTable
    final synchronized class java.io.ObjectOutputStream$Stack
    According to my tests, at least ClassDoc.modifiers(), ClassDoc.qualifiedName() and ClassDoc.containingClass() return incorrect results for HandleTable, ReplaceTable and Stack.
    This behaviour seems common to both Javadoc 1.3.1_01 and 1.4beta3. I admit I didn't test 1.4 final, but I searched the Javadoc site, the forum and the bug database without finding anything similar.
    Thanks in advance for any help.
    Amedeo Farello

    Thank you for looking into this.
    This is beyond my understanding of the Doclet API.
    Please submit this as a bug using the instructions at:
    http://java.sun.com/j2se/javadoc/faq/index.html#submitbugs
    and please email the ID number you get back to me
    at [email protected] so I can make sure it gets
    past our initial reviewers and into our bug database so
    our javadoc engineer can look at it.
    -Doug Kramer
    Javadoc team

  • High CPU consumption with repaint while dragging

    Hi! I certainly hope someone can help me with this. I am building a graphical user interface for a graph with custom nodes and edges, the nodes being draggable. I have tried making each network component (node or edge) a JComponent. Now, I'm trying using only one JPanel to paint all the components. Either way, I find that dragging takes up too much CPU % especially when using full screen graphics, usually around 92%. And that is on a machine with >1.9GHz.
    It does not really make much of a difference when I paint outlines of the components while dragging. Any ideas about this? Thanks.
    My runnable test code is rather long so I've uploaded it to : http://web.mit.edu/jabos/www/SyncTest/GUILoad2.java.
    -Bosun

    Comments about changes to your code:
    1 - trouble in rendering with setOpaque(false). Set this to true and add super.paintComponent(g) in paintComponent to take care of background paint updates
    2 - had to doctor your ConnComp class; the constructor was under construction...
    3 - I'm using j2se 1.4 so I converted your:
    ArrayList generics to the old Object casts and
    the JFrame setPreferredSize to setSize
    This runs okay now. The highest cpu usage numbers I saw were 52% in full screen and 37% in regular mode (2.6 GHz).
    The painting part seems okay; I think the trouble is in excessive data storage and manipulation. I would re&#8211;design your program to eliminate all the type checking with the instanceof operator. Specifically I would try to use only one ArrayList for the node objects and draw the connection lines between them inside paintComponent depending on how a boolean is set, eg if(showLines). As an aside, GradientPaint is for fill operations and will not benefit your line display.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.ArrayList;
    * This demo paints all network components in a single JComponent
    * @author jabos
    public class DragTest extends JPanel {
         * all components
        public ArrayList comps;
        public ArrayList compsDragged; // actually only RectComps
         * arraylist of all connection components
        public ArrayList conncomps;
        public boolean dragging = false, repaintWhileDragging = true;
        Point2D initp = null;
        public JLabel repaintDrag;
        public DragTest() {
            repaintDrag = new JLabel("repaintWhileDragging : " + repaintWhileDragging);
            repaintDrag.setForeground(Color.MAGENTA);
            add(repaintDrag);
            add(new JLabel("Press \"R\" to change repaint protocols during dragging"));
            comps = new ArrayList();
            compsDragged = new ArrayList();
            conncomps = new ArrayList();
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseDragged(MouseEvent e) {
                    //* // Remove initial slash to disable repainting while dragging
                    if (repaintWhileDragging) {
                        Point2D pp = e.getPoint();
                        AffineTransform t = AffineTransform.getTranslateInstance(
                                                    pp.getX() - initp.getX(),
                                                    pp.getY() - initp.getY());
                        initp = pp; // reset initp
                        for (int j = 0; j < compsDragged.size(); j++) {
                            Comp comp = (Comp)compsDragged.get(j);
                            if (comp instanceof RectComp)
                                comp.updateCompLocation(t);
                        // and again to update ConnComps
                        for (int j = 0; j < conncomps.size(); j++) {
                            Comp comp = (Comp)conncomps.get(j);
                            if (comp instanceof ConnComp)
                                comp.updateCompLocation(t);
                        dragging = true;
                        repaint();
                    dragging = true;
            addMouseListener(new MouseAdapter() {
                // does final repaint if dragging just finished
                public void mouseReleased(MouseEvent e) {
                    if (dragging) {
                        Point2D pp = e.getPoint();
                        AffineTransform t = AffineTransform.getTranslateInstance(
                                                    pp.getX() - initp.getX(),
                                                    pp.getY() - initp.getY());
                        for (int j = 0; j < compsDragged.size(); j++) {
                            Comp comp = (Comp)compsDragged.get(j);
                            if (comp instanceof RectComp)
                                comp.updateCompLocation(t);
                        // and again to update ConnComps
                        for (int j = 0; j < conncomps.size(); j++) {
                            Comp comp = (Comp)conncomps.get(j);
                            if (comp instanceof ConnComp)
                                comp.updateCompLocation(t);
                    repaint();
                    dragging = false;
                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                // Updates list of components being dragged
                public void mousePressed(MouseEvent e) {
                    compsDragged.clear();
                    initp = e.getPoint();
                    for (int j = 0; j < comps.size(); j++) {
                        Comp comp = (Comp)comps.get(j);
                        if (comp.graphic.contains(initp))
                            compsDragged.add(comp);
                    setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
            addKeyListener(new KeyAdapter() {
                public void keyReleased(KeyEvent e) {
                    if(e.getKeyCode() == KeyEvent.VK_R) {
                        repaintWhileDragging = !repaintWhileDragging;
                        repaintDrag.setText("repaintWhileDragging : " +
                                             repaintWhileDragging);
    //        setOpaque(false);
            setFocusable(true);
            requestFocusInWindow();
        public static void main(String[] args) {
            GraphicsDevice device =
                GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
            JFrame f = new JFrame("GUILOAD2", device.getDefaultConfiguration());
            //* // remove initial slash to disable full screen
            device.setFullScreenWindow(SwingUtilities.getWindowAncestor(f));
            //needs to be set AFTER fullscreenmode so that the toolbar is NOT draggable!
            f.setExtendedState(JFrame.MAXIMIZED_BOTH);
                // enable use of Look and Feel
                f.setUndecorated(true);    // Set false, EE is still minimizable
                f.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
            f.setBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().
                                getMaximumWindowBounds());
            DragTest p = new DragTest();
            p.setBackground(Color.WHITE);
            RectComp[] rc = new RectComp[100];
            int n = -1, x = 30, y = 30, b = 100, inc = 40;
            // add REctComps
            for (int i = 0; i < 10; i++) {
                p.add(rc[++n] = new RectComp(new Point2D.Double(x += inc, y += inc),
                                             new Color(x % 255, y % 255, (b += 10) % 255)));
            x = 34; y = 32; b = 32;
            // add ConnComps
            while (n > 0) {
                p.add(new ConnComp(rc[n--], rc[n],
                                   new Color((x += inc) % 255, (y += inc) % 255,
                                             (b += inc) % 255),
                                   new Color((x += inc) % 255, (y += inc) % 255,
                                             (b += inc) % 255)));
            f.setContentPane(p);
            f.setSize(700, 700);
            makeFramex(f, false);
            /* // remove initial slash to disable full screen; Also, uncomment above
            f.setResizable(false);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setIgnoreRepaint(true);
            f.setVisible(true);
        public static void makeFramex(JFrame frame, boolean resizable) {
            frame.setSize(frame.getSize());
    //        frame.setResizable(resizable);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //        frame.pack();
            frame.setVisible(true);
         * Adds network component c to this simulation
         * @param c
        public void add(Comp c) {
            comps.add(c);
            if (c instanceof ConnComp) {
                conncomps.add((ConnComp)c);
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2D = (Graphics2D) g;
            g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                 RenderingHints.VALUE_ANTIALIAS_ON);
            for (int j = 0; j < comps.size(); j++) {
                Comp comp = (Comp)comps.get(j);
                //for (Comp i : dragging ? compsDragged : comps) {
                try {
                    g2D.setPaint(comp.color);
                    if (comp instanceof ConnComp) {
                        g2D.setStroke(((ConnComp) comp).compStroke);
                        g2D.draw(comp.graphic);
                    if (comp instanceof RectComp)
                        g2D.fill(comp.graphic);
                } catch (Exception e) {
                    e.printStackTrace();  //To change body of catch statement
                                          // use File | Settings | File Templates.
         * A network component that simulates a node
        private static class RectComp extends Comp {
            RectComp(Point2D centero, Paint c) {
                super(c);
                center = centero;
                graphic = new Ellipse2D.Double(center.getX() - radius,
                                  center.getY() - radius, radius * 2 - 2, radius * 2 - 2);
            public void updateCompLocation(AffineTransform t) {
                graphic = t.createTransformedShape(graphic);
                Rectangle2D r = graphic.getBounds2D();
                center = new Point2D.Double(r.getCenterX(), r.getCenterY());
                //System.out.println("newCenterX=" + r.getCenterX());
         * A network component that simulates a connection between two nodes
        private static class ConnComp extends Comp {
            Stroke compStroke;
            RectComp origin, destination;
            Paint color;
            ConnComp(RectComp origino, RectComp desto, Color c1, Color c2) {
                super(c1);
                if (c2 != null)
                    color = new GradientPaint(origino.center, c1, desto.center, c2);
                else
                    color = c1;
                graphic = new Line2D.Double(origino.center, desto.center);
                this.origin = origino;
                this.destination = desto;
                compStroke = new BasicStroke(3);
    //            updateCompLocation(new AffineTransform());
            public void updateCompLocation(AffineTransform t) {
                ((Line2D)graphic).setLine(origin.center, destination.center);
                if(color instanceof GradientPaint)
                    color = new GradientPaint(((Line2D)graphic).getP1(),
                                              ((GradientPaint)color).getColor1(),
                                              ((Line2D)graphic).getP2(),
                                              ((GradientPaint)color).getColor2());
                //System.out.println("newLineX:" + ((Line2D) graphic).getX1() +
                //                     "---" + ((Line2D) graphic).getX2());
         * demo Superclass for all network components
        private abstract static class Comp {
            Point2D center;
            Shape graphic;
            int radius = 20;
            Paint color;
            Comp(Paint c) {
                color = c;
             * Updates internal parameters of Comp necessary for correct repaint
             * @param t
            public abstract void updateCompLocation(AffineTransform t);
    }

Maybe you are looking for

  • Submit button to local/network folder

    Goal: Place a Submit button on a PDF form that will save a copy of the entire form to a local/network folder. Software: Windows 7, Adobe Acrobat X Pro Per the Adobe Acrobat X Pro help files, it states that you can add a folder path in the URL field w

  • Help with creating AQ JMS

    Hiello, I'm trying to create JMS resource on WLS 10.3 to connect to AQ on a different server Here is what I'm trying to do: 1. I have an Oracle application (OTM) that can en-queue payload in an AQ. I have configured the AQ on the OTM server 2. I want

  • Setting tuning in preferences

    Trying to set the calibration of the tuning in preferences to 442 Hz. But when I've done this, and close the preference window, the actual tuning on the channelstrip shows 441,7. Bug number?

  • Where can i download 11.5.10.2 software

    Hello Experts, I need to download oracle apps 11.5.10.2 software. I have searched in edelivery by selecting the product type as "E-Business suite" and Platform as "Linux x86-64", but i didn't find the software. It has only R12 media pack. And after s

  • Fix for SDRQCR21

    Hi All, Has SAP come up with permanent fix for this MD04 problem? Please let me know. I would really appricite any response on this. We are getting this issue quite frequently. We need to run this report quite frequently. We want permanent fix. Thank