Why do we subclass EventQueue?

I see applications creating own custom EventQueues.
Toolkit.getDefaultToolkit().getSystemEventQueue().push(customEventQueue);
Why do we create our own eventqueues? Please explain. I was not able to find much documentation on java tutorial.

For an example reason, see http://www.javaspecialists.co.za/archive/Issue075.html

Similar Messages

  • Why assigning a subclass instance to a variable of type of superclass ?

    Hi all,
    What is the significance of assigning an instance of a subclass to a variable whose type is a superclass's type.
    For eg. List list=new ArrayList();
    If I do so is it possible to execute the methods of the subclass ?
    regards
    Anto Paul.

    In addition, this is what polymorphism is all about:
    abstract class Animal {
      String name;
      Animal(String name) {
        this.name = name;
      public abstract void voice();
    class Dog extends Animal {
      Dog(String name) { super(name); }
      public void voice() {
        System.out.println(name+" barks");
    class Cat extends Animal {
      Cat(String name) { super(name); }
      public void voice() {
        System.out.println(name+" miaows");
    public class Polymorphism {
      public static void main(String args[]) {
        Animal[] animals = {
          new Dog("Fido"),
          new Cat("Felix")
        for (int i = 0; i < animals.length; i++) {
          animals.voice();
    Here, we are looping through an array of Animals. In fact, these are concrete subclasses of the abstract Animal class. In this simple example, you can see from the code that the animals array contains a dog and a cat. But we could even extend this to read in an arbitrary Animal object that had been serialized into a file. At compile time, the exact class of the serialized animal would not be known. But polymorphism occurs at runtime to ensure the correct voice() method is called.
    For the List, or Map example, conisder this:
    public SomeClass {
      public HashMap map1 = new HashMap();  // this ties you to hashmap
      public Map map2 = new HashMap();      // this allows you to change Map implementation
      public void process(HashMap map) {}   // this ties you to hashmap
      public void process(Map map) {}       // this allows you to change Map implementation
    }Suppose you use a HashMap for map2 to start with. But at some point in the future you would like to ensure your map is sorted. By specifying map2 to be a Map, you can change the implementation without having to modify each method call by simplying changing the initiliastion to be:
    Map map2 = new TreeMap();Hope some of this helps :) Cheers, Neil

  • How to intercept posts on EventQueue to change for instance focusOwner?

    Hi all,
    I am subclassing EventQueue to intercept the event processing mechanism only to find out how focus events reach the KeyboardFocusManager. I can only see the dispatchEvent that obviously reaches dispatchEvent on KeyboardFocusManager. But I can't see who posts this type of events. I only see that InvocationEvent instances passing that are mainly related with repainting. But nothing that smells a bit like focus processing. Can anyone tell me who posts changes in the focus system (methods like Component.requestFocus, but I don't see where exactly). Or how I can see posts of that type on EventQueue.
    Many thanks,
    Marcel

    What are you calling the "Control Panel?"  If you are referring to the bottom row of apps on your home screen, you can move the apps by holding your finger on any app until they all jiggle.  Then with your finger move the apps around to suit your needs.
    If you are referring to the actual control center when you swipe up from the bottom of the screen, you can not alter anything in that.

  • Apple Match-O Linker Error

    I am making a menu bar app and it is going fine and all but I get an error saying "clang: error: linker command failed with exit code 1 (use -v to see invocation)" here it is in more detail:
    duplicate symbol _OBJC_METACLASS_$_View in:
        /Users/Tom/Library/Developer/Xcode/DerivedData/PowerBar-exvfuprqkuwxevgldxdbgyr ypvlx/Build/Intermediates/PowerBar.build/Debug/PowerBar.build/Objects-normal/x86 _64/AppDelegate.o
        /Users/Tom/Library/Developer/Xcode/DerivedData/PowerBar-exvfuprqkuwxevgldxdbgyr ypvlx/Build/Intermediates/PowerBar.build/Debug/PowerBar.build/Objects-normal/x86 _64/View.o
    duplicate symbol _OBJC_CLASS_$_View in:
        /Users/Tom/Library/Developer/Xcode/DerivedData/PowerBar-exvfuprqkuwxevgldxdbgyr ypvlx/Build/Intermediates/PowerBar.build/Debug/PowerBar.build/Objects-normal/x86 _64/AppDelegate.o
        /Users/Tom/Library/Developer/Xcode/DerivedData/PowerBar-exvfuprqkuwxevgldxdbgyr ypvlx/Build/Intermediates/PowerBar.build/Debug/PowerBar.build/Objects-normal/x86 _64/View.o
    ld: 2 duplicate symbols for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    So basically I am trying to make a custom veiw and get this error. I know it has something between the Veiw.m file and the AppDelegate.m file because when I remove to #import "Veiw.m" at the top of AppDelegate.m the error is gone. Here is my relevent code:
    //Veiw.m
    #import "View.h"
    @implementation View
    - (void)mouseDown:(NSEvent *)event
        NSLog(@"mouseDown");
    @end
    //Veiw.h (Some stuff is // out so I didn't include it)
    #import <Cocoa/Cocoa.h>
    #import "AppDelegate.h"
    @interface View : NSControl {
    @end
    //AppDelegate.m
    #import "AppDelegate.h"
    #import "View.m"
    @implementation AppDelegate
    @synthesize aboutWindow;
    //AppDelegate.h
    #import <Cocoa/Cocoa.h>
    #import "View.h"
    @interface AppDelegate : NSObject <NSApplicationDelegate>{
    Please Help.

    I don't know why you keep starting new threads for this. But this will be ny last response
    @interface View : NSControl {
    @end
    //AppDelegate.m
    #import "AppDelegate.h"
    #import "View.m"
    You have a number of problems just in this small section of code.
    First why are you subclassing an object you are calling  view off of NSControl? Makes no sense. If you want to have a view object it should be a subclass of NSView.
    Second why are you importing a .m file?
    #import "View.m"
    The project I told you I put up in Dropbox had all this worked out for you. What you have show here will not work.
    good luck
    regards

  • AWTPermission "accessClipboard" issue in JRE 1.6.0_07

    Is AWTPermission check of "accessClipboard" removed from Java Applet AWTEvent event processing in JRE 1.6.0_07?
    In JRE 1.6.0_07, I can now copy from JTextArea to system clipboard, without signing the applet and without granting the AWTPermission "accessClipboard" in java.policy.
    In JRE 1.6.0_04, it didn’t allow copy unless you sign the jar or grant the permission.
    Is this a security bug in JRE 1.6.0_07? Or is it a new feature?
    My second question is about EventQueue class. I used the following code to subclass EventQueue and register it to Event stack.
    In JRE 1.6.0_07, this code doesn’t allow copy from JTextArea to system clipboard unless I sign the jar or grant the "accessClipboard" permission in java.policy.
    Is this expected? Is there any way to get around jar signing or granting permission?
    Thanks in advance
    class MyEQ extends EventQueue {
      protected void register (){
        Toolkit.getDefaultToolkit().getSystemEventQueue().push(this);
      protected void dispatchEvent(AWTEvent e) {
        doProcess(e);
        super.dispatchEvent(e);
      private void doProcess(AWTEvent e) {
    }

    Reposted in the AWT forum.
    [http://forums.sun.com/thread.jspa?threadID=5334933]

  • Extending a class (newbie)

    I'm very new to Java. I'm making use of custom web classes from a proprietary application.
    I want to write my own class by extending another class. My class need to do exactly what the super class does. The super class extends another class.
    Here is how it looks,
    MY CLASS:
    public RmCopyCommand extends DwCopyCommand
    THE SUPER CLASS:
    public DwCopyCommand extends DwDocbaseCommand
    The super class, DwCopyCommand, has four methods defined (plus many inherited). To make my class, RmCopyCommand, mimic the super class, I did the following:
    1. I made a constructor
    RmCopyCommand()
                   super();
    2. I duplicated the methods
    public boolean hasTransaction()
                   return super.hasTransaction();
    I did the above to all four methods defined in the super class. I also used TRY...CATCH blocks where necessary. The source compiled.
    Off course, this doesn't work. I got a nullPointerException error. What I want to do is use the exact functionality of DwCommand, but write another method that makes a call to an inherited method.
    Could anyone tell me what I might be doing wrong?
    I hope I included enough details. If you need further details, let me know.
    Thanks,
    Moshe

    Lets go through this point by point:
    I'm very new to Java. I'm making use of custom web
    classes from a proprietary application.
    I want to write my own class by extending another
    class. My class need to do exactly what the super
    class does. The super class extends another class.Does you class really need to do exactly what the super class does? If the super class has everything you need why are you subclassing it.
    Here is how it looks,
    MY CLASS:
    public RmCopyCommand extends DwCopyCommandThe above statement is all you need followed by {} according to your description.
    THE SUPER CLASS:
    public DwCopyCommand extends DwDocbaseCommand
    The super class, DwCopyCommand, has four methods
    defined (plus many inherited). To make my class,
    RmCopyCommand, mimic the super class, I did the
    following:
    1. I made a constructor
    RmCopyCommand()
    super();
    }You only need to do this for constructors with arguments. If you don't create a default constructor, one is created for you. Also if you don't call super() in your constructor it will automatically before anything else is executed.
    2. I duplicated the methods
    public boolean hasTransaction()
    return super.hasTransaction();
    }This is unneccesary. By subclassing a class all its public and protected members are part of the sub class.
    I did the above to all four methods defined in the
    super class. I also used TRY...CATCH blocks where
    necessary. The source compiled.
    Off course, this doesn't work. I got a
    nullPointerException error. What I want to do is use
    the exact functionality of DwCommand, but write
    another method that makes a call to an inherited
    method.Nothing that you have stated here would cause that.
    Could anyone tell me what I might be doing wrong?
    I hope I included enough details. If you need further
    details, let me know.
    Thanks,
    Moshe

  • Turning an icon into a button in a table

    Currently, I access a database in my program, and if I find an 'X' in a specific column, I place an icon in that field. What I would like to do is have that icon act as a button, that will pop up a screen with further information about the table line item. I am new at Java, and not sure what to do next.
    Here is the code for my table model:
    class sciTableModel extends javax.swing.table.DefaultTableModel
         public sciTableModel()
              super();
         public sciTableModel(java.util.Vector data, java.util.Vector columnNames)
              super(data, columnNames);
    and here is the code for my renderer
    class IconRenderer extends DefaultTableCellRenderer
         public Component getTableCellRendererComponent(JTable table,
         Object value, boolean isSelected, boolean hasFocus, int row, int column)
              ImageIcon iconl = new ImageIcon("info.gif");
              String headerText = (String)value;
              // System.out.println(headerText);
              JLabel headerComponent =
              ((JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column));
              headerComponent.setHorizontalAlignment(SwingConstants.CENTER);
              if (headerText != null)
                   headerComponent.setIcon(iconl);
                   headerComponent.setText("");
              else
                   headerComponent.setIcon(null);
                   headerComponent.setText(null);
              return headerComponent;
    In the public class I set the renderer, and in the actionevent that runs the database access I use the tablemodel.
    Any help on how I can turn this icon into a button would be appreciated.

    In A JTable, the render has the job of drawing one or more cells, but it's a rubber stamp -- it doesn't
    respond to events like a true component. What you describe isn't the job of an cell editor either,
    since, obviously, nothing is being edited. That leaves JTable itself: I suggest you write a mouse
    listener for your JTable and respond appropriately when the right cell is clicked:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test {
        public static void main(String[] args) {
            JTable table = new JTable(20, 5);
            table.addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent evt) {
                    JTable t = (JTable) evt.getSource();
                    Point point = evt.getPoint();
                    int col = t.columnAtPoint(point);
                    int row = t.rowAtPoint(point);
                    if (col != -1 && row != -1) {
                        int modelCol = t.convertColumnIndexToModel(col);
                        System.out.println("clicked on model cell (" + row + "," + modelCol + ")");
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(table));
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }As the code demonstrates, don't forget to translate from view columns to model columns.
    By the way, why are you subclassing the default table model? You aren't changing any behavior...

  • Inheritance/Overriding question

    Morning :)
    Here is my situation. I have the following situation, within the same package
    Class C, with a protected method doStuff(int x), and a public startStuff() method. This startStuff method calls the doStuff method.
    Class IC, which extends C, which also has a separate protected doStuff(int x) method, and a public startStuff() method
    I am instantiating an object of class IC, and calling the startStuff method, which first calls super.startStuff(), which in turn (in my mind) should call the doStuff method within Class C, but it isn't. In the stack trace, I can see Class C.startStuff being called, but when it gets to the doStuff method, it invokes the one in class IC, which isn't what I want.
    Any way for me to fix this, or am I going about it all wrong?

    I think you are talking about something like this :
    public class SuperClass
         protected void doStuff()
              System.out.println("doStuff in SuperClass");
         public void startStuff()
              System.out.println("startStuff in SuperClass");
              doStuff();
    public class SubClass extends SuperClass
         protected void doStuff()
              System.out.println("doStuff in SubClass");
         public void startStuff()
             super.startStuff();
              System.out.println("startStuff in SubClass");
         public static void main(String args[])
              SubClass aSubClass=new SubClass();
              System.out.println("This is main ");
              aSubClass.startStuff();          
    }What is happening here (why doStuff() in SubClass is getting invoked)is as follows:
    We invoke any method on a target reference(i.e.aSubClass.startStuff()),the invoked method has a reference to the target object so that it may refer to the invoking(or target )object during the execution of the program.That reference is represented by this.
    In method overriding the instance method is chosen according to the runtime class of the object referred to by this.So during the execution of statrStuff() in SuperClass , the doStuff() is invoked on the this reference that is the actual run time type of the target object i.e. SubClass.
    That's why doStuff() in SubClass is getting invoked.
    If you want to invoke SuperClass.doStuff(),declare doStuff() as class method (Static) in both the classes.The class methods are not invoked by the runtime class of the object,because these are not related with any instance od a class.

  • Casting objects question

    class SuperClass {
         public static void staticMethod() {
              System.out.println("static SuperClass method");
         public void instanceMethod() {
              System.out.println("instance SuperClass method");
    class SubClass extends SuperClass {
         public static void staticMethod() {
              System.out.println("static SubClass method");
         public void instanceMethod() {
              System.out.println("instance SubClass method");
    public class TestSuperSub {
         public static void main(String[] args) {
              SuperClass superclass = new SuperClass();
              SubClass subclass= new SubClass();
              superclass.instanceMethod();
              subclass.instanceMethod();
              ((SuperClass)subclass).instanceMethod(); //<--uses the instance method from SubClass
              superclass.staticMethod();
              subclass.staticMethod();
              ((SuperClass)subclass).staticMethod(); //<---uses the static method from SuperClass
    I don't understand why calling the SubClass instance method when SubClass is cast to SuperClass runs the SubClass method but not with the static method. What is actually happening on the last line?
    RON

    RonNYC2 wrote:
    What I'm asking is, why doesn't upcasting retrieve the instance method of the superclass since it retrieves the static method of the superclass? I know that the instance method is overridden and static method cannot be. What I'm asking is, what kind of object is (SuperClass)Subclass? Is it an object which uses only the superclass methods (it doesn't seem so)?Casting it doesn't change the fact that the underlying object is still a Subclass type.
    When invoking a static method however, you're telling the compiler to use the version from the SuperClass. The line of code in question is just as if you had coded:
    SuperClass.staticMethod();which is one reason why you should ALWAYS (or at least almost always, there are probably corner cases - statements with absolutes just ask for someone to shoot it down with an exception example) invoke static methods via the class name itself rather than through an object instance.

  • Design issue : Discuss

    I'm currently designing the architecture for implementing a turn-based game logic. The game looks a bit like Magic: The Gathering, in that it uses cards for instance.
    The code will include a TriggerManager : a class responsible for registering triggered effects and then detecting when it needs to fire one of them. A triggered effect is in fact an OrderedPair <Trigger, Effect>.
    Anytime a Trigger is hit, the TriggerManager is kept aware. He then checks his registered triggers list and fires the corresponding effects if any Trigger matches.
    public class TriggerManager {
      public void registerTriggeredEffect(Trigger t, Effect e) { ... }
      public void hit(Trigger t) { ... }
    public abstract class Trigger {
      public boolean isSameConcreteClassAs(Trigger t);
    public abstract Effect extends Trigger {
      public void resolve() {
        triggerManager.hit(this);
    public DrawEffect extends Effect {
      public boolean isSameConcreteClassAs(Trigger t) {
        return t instanceof DrawEffect;
    }My issue concerns the matching criterium isSameConcreteClassAs, declared inside the Trigger class. I gave an example of its implementation in the DrawEffect class.
    When calling registeredTriggeredEffect(Trigger t, Effect e), a sample Trigger will be passed. The only thing that will be exact about that sample Trigger is its concrete class.
    I will probably have to write ~50 Effect concrete classes. Thus this design choice is quite important to me.
    I feel the solution is correct, but I'm not 100% sure because it looks a bit weird. And I don't like having to compare concrete classes, but maybe I should feel alright about that.
    Any help or insight on this will be most welcome.
    Edited by: bestam on Mar 10, 2009 6:52 AM

    Hello,
    sorry if I'm being dense, but there are several things I don't understand in your design, and I think that's related to naming choices - but that may be biased, as I'm not a native english speaker either, and as a properly english-speaking person such as dubwai did seem to understand your need.
    That being said, here are a few questions, and a couple of suggestions, assuming I did get your intention right:
    The code will include a TriggerManager : a class responsible for registering triggered effects and then detecting when it needs to fire one of them. A triggered effect is in fact an OrderedPair <Trigger, Effect>.So you design two abstractions:
    Trigger represents a condition (specifically, the algorithm to determine if an actual situation matches the condition)
    Effect represents what is done then (the fact that it's in response to a certain condition is not relevant to this abstraction, but you choose to link both in your implementation).
    Anytime a Trigger is hit, the TriggerManager is kept aware. He then checks his registered triggers list and fires the corresponding effects if any Trigger matches.Who does notify the triggerManager? Your example code shows it's an Effect instance, in its method resolve(); but who/when does call resolve() ?
    public abstract class Trigger {
        public boolean isSameConcreteClassAs(Trigger t);
    public DrawEffect extends Effect {
      public boolean isSameConcreteClassAs(Trigger t) {
        return t instanceof DrawEffect;
    }Note: first the method name isSameConcreteClassAs looks like an implementation detail. It would be more flexible that Trigger exposes an abstract method: public boolean matches(Trigger t)Second, if you're certain that all implementations of this method will always compare the class (and nothing else), you can write a single implementation of this method, in Trigger or in an abstract suclass, based on the class name or, if you want a Trigger to match its subclasses, as your current implementation does, based on java.lang.Class.isAssignableFrom(...).
    My issue concerns the matching criterium isSameConcreteClassAs, declared inside the Trigger class. I gave an example of its implementation in the DrawEffect class.
    When calling registeredTriggeredEffect(Trigger t, Effect e), a sample Trigger will be passed. The only thing that will be exact about that sample Trigger is its concrete class.
    I will probably have to write ~50 Effect concrete classes. Thus this design choice is quite important to me.I don't understand why Effect does subclass Trigger. Is this beacuse you want to keep the codes that implements the condition and the response to the condition close? This makes sense, but then why do you keep pairs of <Trigger, Effect>?
    I feel the solution is correct, but I'm not 100% sure because it looks a bit weird. And I don't like having to compare concrete classes, but maybe I should feel alright about that.It probably wouldn't be good that the TriggerManager compare classes. But the fact that each trigger subclass implements its match algorithm based on its own class is not absurd. Think about method equals(Object): most implementation will indeed check the class of the argument.
    Could you clarify the relationship between Trigger and Effect?
    Edited by: jduprez on Mar 11, 2009 2:34 PM

  • Why do we create custome EventQueue?

    I see applications creating own custom EventQueues.
    Toolkit.getDefaultToolkit().getSystemEventQueue().push(customEventQueue);
    Why do we create our own eventqueues? Please explain. I was not able to find much documentation on java tutorial.
    thanks
    vineet

    [url http://forum.java.sun.com/thread.jsp?thread=480382&forum=31]Cross-post.
    For an explanation of why cross-posting is poor etiquette, see http://pjt33.f2g.net/javafaq/posting.html#forumChoice

  • Why isn't there a simpler way to initialize a subclass with its super class

    Let me explain my doubt with an example...
    public class Parent {
    �    public String parent;
    public class Child extends Parent{
    �    public String child;
    I've an instance of Parent p. I want to construct Child c, with the data in p.
    The only way that is provided by Java language seems to be, having a constructor in Child like
    public class Child extends Parent{
    �    public String child;
    �    public Child(Parent p){
    �    �    parent = p.parent;
    �    }
    The problem with this is there is lot of redundant assignment code.
    What I don't understand is why there is not a simpler way of doing this when a subclass is after all super class data + some other data(excuse me for not looking at the bahavior part of it)
    I'm looking for something as simple as Child c = p, which I know is wrong and know the reasons too.
    Yes, we can wrap Child over Parent to do this, but it necessitates repeating all the methods in Parent.
    Why is the language writers didn't provide a simple way of doing this? I should be missing something here...I'm just searching for an explanation. May be I'm asking a dumb question, but this bugs me a lot...
    Regards,
    Kothapalli.

    To answer DrClap, I'm demanding it now :-). Let me
    not suggest something that Mr.Gosling didn't think of;
    he should be having some reasons in not providing it.Because it's essentially impossible in the general case. One of the reasons you may be extending a class is to add new invariants to the superclass.
    eg- extend java.awt.Rectangle by BoundedRectangle - extra invariant that none of its corner points may be less than 0 or more than 100 in any dimension. (The rectangle must be entirely contained in the area (0,0)-(100,100))
    What would happen if you try to create a BoundedRectangle from a rectangle representing (50,50)-(150,150)? Complete invariant breakdown, with no generic way to handle it, or even recognise it.
    Actually, BIJ and sgabie are asking for it. Provide an
    automatic copy constructor. Every object should have
    an implicit copy constructor defined. From any
    subclass, I should be able to invoke
    super(parentClass). From the subclass, we can invoke
    super(parentClass) first and then go on to initialize the
    subclass data.
    I really don't know the implementation issues of this,
    but what I'm looking for is something like this. I'm just
    curious to know the implementation issues.Implementation issue #1: Classes that should not, under any circumstane, be copied.
    * eg 1- Singleton objects. If there's an automatic copy constructor, then multiple singletons can be created, making them essentially useless. This by extension kills the Typesafe Enum pattern also.
    * eg 2- Objects with extra information, such as java.sql.Connection - if you copied this, would the copy be using the same socket connection, or would another connection be required? What happens if opening another connection, and the JDBC driver requires the password to be entered for every new connection? If the wrong password is entered, what happens to the newly creating connection?
    Implementation issue #2: Copying implementation?
    * Already mentioned by RPWithey. The only guaranteed way to perform the copy would be with a shallow copy, which may end up breaking things.
    Why can't you write the copy constructor yourself? If it's a special case, it only has to be done once. If it's a recurring case, you could write a code generation tool to write them for you, along with most of the rest of the class.

  • Why can't classes with private constructors be subclassed?

    Why can't classes with private constructors be subclassed?
    I know specifying a private nullary constructor means you dont want the class to be instantiated or the class is a factory or a singleton pattern. I know the workaround is to just wrap all the methods of the intended superclass, but that just seems less wizardly.
    Example:
    I really, really want to be able to subclass java.util.Arrays, like so:
    package com.tassajara.util;
    import java.util.LinkedList;
    import java.util.List;
    public class Arrays extends java.util.Arrays {
        public static List asList(boolean[] array) {
            List result = new LinkedList();
            for (int i = 0; i < array.length; i++)
                result.add(new Boolean(array));
    return result;
    public static List asList( char[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Character(array[i]));
    return result;
    public static List asList( byte[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Byte(array[i]));
    return result;
    public static List asList( short[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Short(array[i]));
    return result;
    public static List asList( int[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Integer(array[i]));
    return result;
    public static List asList( long[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Long(array[i]));
    return result;
    public static List asList( float[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Float(array[i]));
    return result;
    public static List asList( double[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Double(array[i]));
    return result;
    // Now that we extend java.util.Arrays this method is not needed.
    // /**JCF already does this so just wrap their implementation
    // public static List asList(Object[] array) {
    // return java.util.Arrays.asList(array);
    public static List asList(Object object) {
    List result;
    Class type = object.getClass().getComponentType();
    if (type != null && type.isPrimitive()) {
    if (type == Boolean.TYPE)
    result = asList((boolean[])object);
    else if (type == Character.TYPE)
    result = asList(( char[])object);
    else if (type == Byte.TYPE)
    result = asList(( byte[])object);
    else if (type == Short.TYPE)
    result = asList(( short[])object);
    else if (type == Integer.TYPE)
    result = asList(( int[])object);
    else if (type == Long.TYPE)
    result = asList(( long[])object);
    else if (type == Float.TYPE)
    result = asList(( float[])object);
    else if (type == Double.TYPE)
    result = asList(( double[])object);
    } else {
    result = java.util.Arrays.asList((Object[])object);
    return result;
    I do not intend to instantiate com.tassajara.util.Arrays as all my methods are static just like java.util.Arrays. You can see where I started to wrap asList(Object[] o). I could continue and wrap all of java.util.Arrays methods, but thats annoying and much less elegant.

    Why can't classes with private constructors be
    subclassed?Because the subclass can't access the superclass constructor.
    I really, really want to be able to subclass
    java.util.Arrays, like so:Why? It only contains static methods, so why don't you just create a separate class?
    I do not intend to instantiate
    com.tassajara.util.Arrays as all my methods are static
    just like java.util.Arrays. You can see where I
    started to wrap asList(Object[] o). I could continue
    and wrap all of java.util.Arrays methods, but thats
    annoying and much less elegant.There's no need to duplicate all the methods - just call them when you want to use them.
    It really does sound like you're barking up the wrong tree here. I can see no good reason to want to subclass java.util.Arrays. Could you could explain why you want to do that? - perhaps you are misunderstanding static methods.
    Precisely as you said, if they didn't want me to
    subclass it they would have declared it final.Classes with no non-private constructors are implicitly final.
    But they didn't. There has to be a way for an API
    developer to indicate that a class is merely not to be
    instantiated, and not both uninstantiable and
    unextendable.There is - declare it abstract. Since that isn't what was done here, I would assume the writers don't want you to be able to subclass java.util.Arrays

  • OOPs Concept ! - Why Static Methods can't be redefined in its subclass ?

    Dear Experts ,
    I had searched the SDN , but unable to find out the satisfactorily answers ..
    Can anybody let me know the reason for the following Confusion in Oops Concept
    Question 1: As we know , We can Inherit the Static Methods in the Sub Class , But we can't redefine it in the base class  or       Sub Class  ?
    Question 2 : Why can't Static Method be Abstract ?
    Question 3 : Can a Class be Abstract or Final Both, If yes, then why ?
    Thanks in Advance
    Saurabh Goel

    As per the above discussion two of your doubts have already been clarified  so I am taking only third one.
    A class cannot never be Abstract and final both coz Abstract signifies that the implementation of the class has not been defined completelyi.e. may be some methods have been defined but few methods are still missing implementation. 'Final' is used for those classes/methods which cannot be redefined  means the complete implementation of the method has been defined no one can implement further logic under the same method.
    If you are saying your method is Final then it cannot be overridden and Abstract implies that method implementation is yet to be defined which can only be implemented if that class/method is not 'Final'. So both the terms are contradictory.
    Hope it clarifies!!!
    Thanks,
    Vishesh

  • Why Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException?

    Hello,
    In my netbeans generated swing code I get the following stacktrace:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at javax.swing.text.PlainView.updateMetrics(PlainView.java:188)
         at javax.swing.text.PlainView.lineToRect(PlainView.java:589)
         at javax.swing.text.PlainView.modelToView(PlainView.java:327)
         at javax.swing.text.FieldView.modelToView(FieldView.java:248)
         at javax.swing.plaf.basic.BasicTextUI$RootView.modelToView(BasicTextUI.java:1498)
         at javax.swing.plaf.basic.BasicTextUI.modelToView(BasicTextUI.java:1036)
         at javax.swing.text.DefaultCaret.repaintNewCaret(DefaultCaret.java:1291)
         at javax.swing.text.DefaultCaret$1.run(DefaultCaret.java:1270)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:633)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)The code is @ http://code.google.com/p/memorizeasy/source/browse/trunk/MemorizEasy/src/com/mysimpatico/memorizeasy/engine/executables/Input.java

    So the problem is given by these two lines, of the Swing-X library:
    AutoCompleteDecorator.decorate(expField, exps, false);
    AutoCompleteDecorator.decorate(defField, exps, false);
    However, the functionality intended from them is given. The problem now seems to do with expField.setText() and expField.selectAll(). I've inline initialized expField, and now it works.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * Input1.java
    * Created on Feb 21, 2010, 11:56:00 AM
    import java.util.ArrayList;
    import javax.swing.*;
    import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
    public class Input1 extends javax.swing.JFrame {
         private static final long serialVersionUID = 2819528413930929081L;
         private static final ArrayList<String> exps = new ArrayList<String>();//Database.getAllExps();
         private static final Input1 instance  = new Input1();
         /* private void defFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_defFieldFocusGained
                 defField.selectAll();
         }//GEN-LAST:event_defFieldFocusGained
             private void expFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_expFieldActionPerformed
                final String exp = expField.getText();
               /* if (defField.isVisible() && exp != null && exps.contains(exp)){
                    status.setText("to change the spelling select Spelling from the Edit Menu.");
                else if (!defField.isVisible()){ //in spelling mode
                    Database.editExpression(exSpell, exp);
                    status.setText("spelling for " + exSpell + " changed to " + exp);
                    defField.setVisible(true);
                    spellingMenuItem.setEnabled(false);
             }//GEN-LAST:event_expFieldActionPerformed
         private void initComponents() {
              contentPanel = new javax.swing.JPanel();
              expField = new javax.swing.JTextField();
               expField.setText("expression");
                    /*  expField.addActionListener(new java.awt.event.ActionListener() {
                          public void actionPerformed(java.awt.event.ActionEvent evt) {
                              expFieldActionPerformed(evt);
                      expField.addFocusListener(new java.awt.event.FocusAdapter() {
                          public void focusGained(java.awt.event.FocusEvent evt) {
                              expFieldFocusGained(evt);
                      defField.setText("definition");
                      defField.addActionListener(new java.awt.event.ActionListener() {
                          public void actionPerformed(java.awt.event.ActionEvent evt) {
                              defFieldActionPerformed(evt);
                      defField.addFocusListener(new java.awt.event.FocusAdapter() {
                          public void focusGained(java.awt.event.FocusEvent evt) {
                              defFieldFocusGained(evt);
              setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
              contentPanel.add(expField);
              expField.setVisible(true);
              this.setContentPane(contentPanel);
              pack();
         }// </editor-fold>
         /** Creates new form Input1 */
         private Input1() {
              initComponents();
              AutoCompleteDecorator.decorate(expField, exps, false);
         private void expFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_expFieldFocusGained
                 expField.selectAll();
          * @param args the command line arguments
         public static void main(String args[]) {
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        instance.setVisible(true);
         // Variables declaration - do not modify
         private javax.swing.JPanel contentPanel;
         private javax.swing.JTextField expField;
         // End of variables declaration
    }Edited by: simpatico_gabriele on Mar 11, 2010 8:09 PM

Maybe you are looking for