Subclassing the AbstractButton class

I am having problem to define my own button class that subclasses the AbstractButton class. I used setBorder(Border b) to set the border for the button but how can I draw the text(caption) of the button. And what should I do to change the background color of the button when the button is pressed. (I have tried to use ActionListener and MouseListener but it didn't work) ????
any help is highly appreciated!
regards,

Check if this is what you are looking for. Hope it helps
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
class TestCustomButton
     public static void main(String args[])
          JFrame fr = new JFrame("Testing Custom button");
          JButton button = new JButton("My Button");
          button.addActionListener(new MyListener());
          fr.getContentPane().add(button);
          fr.setSize(200,200);
          fr.setVisible(true);
class MyListener implements ActionListener
     public void actionPerformed(ActionEvent ae)
          ((JButton)(ae.getSource())).setText("");
}

Similar Messages

  • Calling the super class method from the subclass

    Hi all,
    I have a question about inheritence and redefinition of methods. Is it possible to call the superclass implementation of a method which is redefined in the subclass in another method of the subclass?There are possbilities like creation of an explicit super class instance or delegating the super class method implementation to another method which is also protected etc. What i mean is, is there a direct way of calling it?We have ,me,   as the reference for the instance we have(which is the subclass instance in this case), is there also a way of pointing the superclass implementation(with super we can reference in the subclass redefinition, my question is if we have such a parameter in other methods of the subclass too)
    Thanks in advance
    Sukru

    Hi,
    The super reference can only be used in redefined methods to call superclass implementation . So probably what you can do is use upcasting and access the required superclass implementation. I can think of only this way...;-)
    Ex data lr_super type ref to cl_superclass
    lr_super = lr_subclass.
    lr_super->method().
    ~Piyush Patil

  • How to Create a Class, do something, and return the name of the child class

    Hello Java Experts,
    I am relatively new to using java. Particularly when it comes to creating something on my own (ie without some of the good samples sun and o'reilly provide!).
    Here is what I am trying to learn how to do:
    I want a class, I am calling in Message. The Message
    class with have various message types. I know what I want to call these message types: one example is what I will call a "ZeroSpace" ("0 143321 4 070302") message, another type is BracketHex, and yet another is BracketNN ("[99]").
    I will test a string (which will be a message received via a serial port, java serial, etc). Then after testing the string (like "0 143321 4 070302"). I will look for the "0" and the space (chr(32)) and want to return ZeroSpace as the message type. Not a string "ZeroSpace". Something like an enumeration in C or Delphi Pascal (ordinal list??)
    the hierarchy is like this: class Message msg;
    msg zsp = new ZeroSpace();
    msg bhex = new BracketHex();
    etc. Depending on the message type I what to do different processing - something like class Shape, and Circle, Square, etc are shapes, but their areas are different, etc
    any tips will help!
    Thank you
    eric w. holzapfel

    one way is to make Message an abstract class, make it a factory, eg with public static Message Create( String str ) method. have it check the string in determining the subclass to instantiate and return. eg if begins with "0 ..", then return new ZeroSpace( str ), where ZeroSpace extends Message. similar for BracketHex and BracketNN.

  • How to get the current class name in static method?

    Hi,
    I'd like to get the current class name in a static method. This class is intended to be extended. So I would expect that the subclass need not to override this method and at the runtime, the method can get the subclass name.
    getClass() doesn't work, because it is not a static method.
    I would suggest Java to make getClass() static. It makes sense.
    But in the mean time, does anybody give an idea to work around it?
    Thank you,
    Bill

    Why not create an instance in a static method and use getClass() of the instance?
    public class Test {
       public static Class getClassName() {
          return new Test().getClass();

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • Subclassing a Java Class in JRuby

    Hello, everyone. I'm studying JRuby by writing a minimal Swing app in Ruby. It seems to be an effective way of finding Ruby <-> Java integration issues. ;)
    I am trying to create a subclass of AbstractAction for a button whose name will be "Quit" and will exit the program. The natural Java way to do this is to have the subclass call its superclass' (AbstractAction's) constructor, as in super("Quit").
    This is what I tried:
    class QuitAction < javax.swing.AbstractAction
        def initialize
            super.initialize "Quit"
        end
        def actionPerformed(e)
            System::exit 0
        end
    endWhen the interpreter read the file, it complained:
    frame-sample.rb:78:in `initialize': private method `initialize' called for org.jruby.javasupport.proxy.gen.AbstractAction$Proxy0@911a2d:Java::JavaObject (NoMethodError)How can I call AbstractAction's constructor?
    Thanks,
    Keith

    All -
    I found the answer. The syntax to use is:
    super 'Quit'So the corrected class is:
    class QuitAction < javax.swing.AbstractAction
        def initialize
            super "Quit"
        end
        def actionPerformed(e)
            System::exit 0
        end
    end- Keith

  • Subclassing and inner classes

    Hi there,
    I have an existing class "A", supplied by a third party, that contains a private inner class "I".
    I have subclassed "A" to a new class "B" to add new functionality, and I also want to replace the inner class "I" with new behaviour. The inner class "I" is invoked by methods within "A" that I have not overridden in "B". Replacing "I" appears to be impossible under these circumstances.
    My initial experiment was to create a new inner class "I" within "B" with the same name and signature as the "I" defined within "A", so...
    Class B extends A {
    private class I {}
    The code that invokes "I" is still within "A" and so my version of the "I" class is ignored, and the original "I" is invoked instead.
    Let's be clear about this, I am not surprised by this behaviour, I'm just wondering if there is any way I can get my "I" invoked by the methods in "A". If that is indeed impossible I will have to write new methods in "B" that override the invoking methods in "A".
    I did a search on the forums using the title I gave this topic, and got some fairly close hits, but nothing seemed to quite answer my question.
    Hope that all made sense. Thanks for any help.
    Regards,
    Tim

    When a class is compiled, all the references are resolved. So in the 'A' class file, a call to method someMethod() in inner class I is resolved as
    some.package.A$I.someMethod()
    Short of replacing the A$I class file, I don't know what you can do. (I think)

  • Why does the child class need to implement the parent classes constructor?/

    As I was playing around with some code I came across this point :
    First Class
    public class A {
         public int x;
         A(int i){
              x=i;
              System.out.println("A is initialised");
    }Second Class extending it :
    public class B extends A{
         private int y;
       // Why do I need this constructor to call parents constructor?
      // My guess is so that when i make an object of class B referring to class A it should make sense?
         B(int i) {                     
              super(i); 
              y=test;
    public static void main(String args[]){
          A a = new A(1);
          A b = new B(1); make an object of class B referring to class A it should work!!
          B c = new B(2);
          B d =(B) new A(2);  --> gives class cast exception!
    }I am little confused here, Can someone throw more light on it.
    Thanks

    You don't override constructors. However, every class, in it's constructor, must call some constructor from the class it's extending. In most cases this is simply super(). However, if your class does not have a default constructor (i.e. you've declared any other constructor, or the sub class does not have access to it, I.E. you've declared it private) then you must include a call to some other constructor in the super class. The constructor in the subclass does not have to be the same as the super class one, but you do have to invoke a constructor from the super class. I.E.
    class A {
      A(int i) {}
    class B extends A {
      B(String b) {
        super(0);
    }

  • Assigning the base class

    I have a bunch of DefaultMutableTreeNodes already created and I
    want to convert them all to myTreeNode objects which extends
    DefaultMutableTreeNode. Is there an easy way for assigning the super class of myClass which is DefaultMutableTreeNode.
    I know this doesn't work but what I want to do is something like
    setting the super class= passed in DMTN.
    I know I could create the original node1,node2 as myTreeNodes instead but these nodes are created in a bunch of different places and I would prefer not having to modify that code.
    node1 = new DefaultMutableTreeNode();
    node2 = new DefaultMutableTreeNode();
    new myTreeNode(node1);
    class myTreeNode extends DefaultMutableTreeNode{
    boolean isSelected;
    public myTreeNode(DefaultMutable TreeNode node){
    super = node.clone(); }
    }

    So you're saying you have this code:
    node1 = new DefaultMutableTreeNode();but you want to arrange things so that when it runs, it actually creates an object of some subclass of DMTN?
    No can do. While you're changing all the instances of that code, think about refactoring your application so that you don't have so many instances of it.

  • When do we override our own clone method not the Object class clone method

    Hi,
    I have a confusion in overriding clone method.We can create clone object by writing Object.clone() but some times I have seen writing our own clone method ,when do we write this,also clone() is defined protected and when we write our own clone it is said to write it public,why?
    Thanks
    Sumit

    protected methods can only be called in the same class and it subclass. You can make clone protected if this is all you need.
    However if you need to clone() the object from another class, it need to be public.
    This is the same for any method.
    Also as Object.clone() is protected you cannot make it private or package-local (this is true of any protected method)

  • How can I extend the Vector class?

    Hi All,
    I'm trying to extend the Vector class so I can get add a .remove(item:T) method to the class.  I've tried this:
    public class VectorCollection extends Vector.<T>
    That gives me the compile error "1017: The definition of base class Vector was not found"
    So then I tried:
    public class VectorCollection extends Vector
    Which gives me the compile error "1016: Base class is final."
    There must be some way to extend the Vector class, though, as on the Vector's official docs page it says:
    Note: To override this method in a subclass of Vector, use ...args for the parameters, as this example shows:
         public override function splice(...args) {
           // your statements here
    So there must be a way to extend the Vector class.  What am I doing wrong?

    No. AS3 doesn't currently have full support for generic types; Vector.<T> was added in an ad-hoc ("ad-hack"?) way. We are considering adding full support in a future version of ActionScript.
    Gordon Smith
    Adobe Flex SDK Team

  • Inheritance in the java class heirarchy

    ok two questions.
    1. in the java class heirarchy, do the subclasses inherit all of the concrete methods from the superclass, that the subclass has not overridden. Or just some of them as Sun has deemed necessary?
    2. In the situation where you have a custom class that extends another class, can you invoke all of the constructors in the superclass using the super keyword, or just some of the constructors?
    Thanks.

    Fguy wrote:
    ok well the Java Tutorial is clear enough on inheritance I suppose. A subclass inherits all of the public and protected members of its parent so I suppose in as much as Sun probably wrote some private methods then that would answer that question.
    But it isn't quite so clear on invoking super class constructors. You mention "the usual access rules" which is fair enough, but the Tutorial isn't too clear on those rules that I can see. Al I can see is the constructor of the superclass can be invoked from the subclass. http://java.sun.com/docs/books/tutorial/java/IandI/super.html
    But you are implying that there are in fact access rules that can prevent a superclass constructor from being invoked from the subclass. Can you give an example? Would it be a situation where said superclass constructor is accessing one of it's private methods? or does that not matter?
    Thanks.If the superclass has an inaccessible constructor (for example, a private constructor which can only be invoked from the superclass itself), there you go.

  • Extending the Socket class...

    I need some help. The class below, SimpleSocket, extends the built-in
    Socket class and adds two methods to it. These methods are meant to
    make the class a bit more user-frienly but simplifying the reading-from
    and writing-to a Socket object. Here it is:
    bq. import java.net.*; \\ import java.io.*; \\ public class SimpleSocket extends Socket { \\ BufferedReader in; \\ PrintWriter out; \\ public void println(String line) throws IOException \\ { \\ if (out == null) { out = new PrintWriter(this.getOutputStream(), true); } \\ out.println(line); \\ } \\ public String readLine() throws IOException \\ { \\ if (in == null) { in = new BufferedReader( new InputStreamReader(this.getInputStream())); } \\ return in.readLine(); \\ } \\ }
    If I want to create a new SimpleSocket, it's easy - I can instantiate it like a normal Socket:
    bq. SimpleSocket socket = new SimpleSocket(host,port); // assume host & port have been defined
    Now, lets say I have a Socket object that I didn't created - for
    example, a Socket returned from the ServerSocket class - like this:
    bq. ServerSocket serverSocket = new ServerSocket(port); \\ Socket clientSocket = serverSocket.accept(); // returns the socket for communicating with a client
    Now that I have a regular Socket object, is there some what to
    "upgrade" it to a SimpleSocket? Something like this: (pseudocode):
    bq. clientSocket.setClass(SimpleSocket); // this is pseudocode
    Or, could I make a SimpleSocket constructor that accepted a Socket
    object as a parameter and then used it instead of creating a new
    object? Like this: (psuedocode):
    bq. public SimpleSocket(Socket S) \\ { \\ super = S; // this is pseudocode \\ }
    Any ideas would be greatly appreciated.
    Lindsay
    Edited by: lindsayvine on Sep 15, 2007 10:50 PM

    lindsayvine wrote:
    Ok, this makes sense and this is what I will probably do. However, there are three limitations to this method that I don't like:
    1. I would like to be able to pass the SimpleSocket object around as a normal Socket. I would like SimpleSocket to be castable to a Socket.Would you? What for? Are you sure? Would input and output streams not be better objects to pass around? You might well have the requirement you say you have, but I say it's an assumption to be challenged, at the very least
    2. I would like every method of the Socket object to be available - this would means that I have to rewrite out every method in SimpleSocket - instead of just saying "hey SimpleSocket, you should have every method Socket has"Yep. But using inheritance simply to avoid some typing is no reason to use inheritance. This is all providing that you need to have every method available. Remember, if any dependent code needs the underlying socket object, your interface can always expose it
    3. If I do write out every method, but then the Socket object gets new methods in future versions of Java, I will have to add the new ones.Likewise, in the case of such a change to java.net.Socket, your subclass has a very real chance of breaking. Again, consider if your code needs to exactly replicate everything a Socket does
    Can you think of any way around these problems?
    Sure. Re-think your design

  • Can we change the Super class attribute scope in Sub class

    Hi.
    I created a super class. In that i have 4 attributes. That attributes are PUBLIC.
    I created a sub class. In that i got all super class attributes. I want to change that attributes as a Private. Is it possible.
    If it is possible.Give me an Example with code or Pseudo code.
    Regards.
    Krishna.

    Hi Krishna,
    It is not possible... If you declare the Attributes again in Subclass of the same name as that of Super class
    then the way of accessing them would be different from that of attributes in the main class.
    Hope this would help you
    Good luck
    Narin

  • Instantiation of similar object over a super class deciding the sub class

    Hello all
    First, sorry if I'm duplicating an already answered question. I didn't searched very deep.
    Initial position:
    I have 2 Object (A1 and A2) which share the most (about 90%) of their instance variables an the associated methods. The values of the instance variables are retrieved in the real implementation from a stream. Depending of the data of the stream, I have to instantiate either a A1 or A2 object.
    A test implementation (using an int in case of the stream):
    The super class A:
    package aaa;
    public class A
      protected int version = -1;
      protected String name = null;
      protected AE ae = null;
      protected A()
      protected A(int v)
        // Pseudo code
        if (v > 7)
          return;
        if (v % 2 == 1)
          this.version = 1;
        else
          this.version = 2;
      public final int getVersion()
        return this.version;
      public final String getName()
        return this.name;
      public final AE getAE()
        return this.ae;
    }The first sub class A1:
    package aaa;
    public final class A1 extends A
      protected A1(int v)
        this.version = v;
        this.name = "A" + v;
        this.ae = new AE(v);
    }The second subclass A2:
    package aaa;
    import java.util.Date;
    public final class A2 extends A
      private long time = -1;
      protected A2(int v)
        this.version = v;
        this.name = "A" + v;
        this.time = new Date().getTime();
        this.ae = new AE(v);
      public final long getTime()
        return this.time;
    }Another class AE:
    package aaa;
    public class AE
      protected int type = -1;
      protected AE(int v)
        // Pseudo code
        if (v % 2 == 1)
          this.type = 0;
        else
          this.type = 3;
      public final int getType()
        return this.type;
    }To get a specific object, I use this class:
    package aaa;
    public final class AFactory
      public AFactory()
      public final Object createA(int p)
        A a = new A(p);
        int v = a.getVersion();
        switch (v)
        case 1:
          return new A1(v);
        case 2:
          return new A2(v);
        default:
          return null;
    }And at least, a class using this objects:
    import aaa.*;
    public final class R
      public static void main(String[] args)
        AFactory f = new AFactory();
        Object o = null;
        for (int i = 0; i < 10; i++)
          System.out.println("===== Current Number is " + i + " =====");
          o = f.createA(i);
          if (o instanceof aaa.A)
            A a = (A) o;
            System.out.println("Class   : " + a.getClass().getName());
            System.out.println("Version : " + a.getVersion());
            System.out.println("Name    : " + a.getName());
            System.out.println("AE-Type : " + a.getAE().getType());
          if (o instanceof aaa.A2)
            A2 a = (A2) o;
            System.out.println("Time    : " + a.getTime());
          System.out.println();
    Questions:
    What would be a better way to encapsulate the logic into their respective objects ? Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?
    Thanks in advance
    Andreas

    Hello jduprez
    First, I would thank you very much for taking the time reviewing my problem.
    Just for the record: have you considered regular serialization? If you control the software at both ends of the stream, you could rely on standard serialization mechanism to marshall the objects and unmarshall them automatically.In my case, I can't control the other site of the stream. At the end, the data comes from a FileInputStream and there aren't objects on the other site, only pur binary data.
    - It seems you have one such factory class. Then you already have encapsulated the "determine class" logic, you don't need to add such logic in superclass A.I thought from an OO view, that the super class A is responsible of doing that, but that's where the problem starts. So at the end, it's better doing it in the factory class.
    - A itself encapsulates the logic to load its own values from the stream.
    - A1 and A2 can encapsulate the logic to load their own specific value from a stream (after the superclass' code has loaded the superclass' attributes values).
    My advise would be along the lines of:
    public class A {
    .... // member variables
    public void load(InputStream is) {
    ... // assign values to A's member variables
    // from what is read from the stream.
    public class A1 extends A {
    ... // A1-specific member variables
    public void load(InputStream is) {
    super.load(is);
    // now read A1-specific values
    public class AFactory {
    public A createA(InputStream is) {
    A instance;
    switch (is.readFirstByte()) {
    case A1_ID:
    a = new A1();
    break;
    case A2_ID:
    a = new A2();
    break;
    a.load(is);
    }The example above assumes you have control over the layout of the data in the stream (here for a given A instance, the attributes defined in A are read first, then come the subclass-specific attributes.
    The outcome is: you don't have to create a new A( ) to later create another instance, of a subclass.I like the idea. In the AFactory, is the "A instance;" read as "A a;" ?
    Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?Note I initially read this question as "can an instance of a class mutate into another class", to which the answer is no (an object has one single, immutable class; it is an instance of this class, and of any superclass and superinterface, but won't change its class at runtime).Yes, I have been thinking about a way for mutating into a subclass to keep the already initialized values from the A class without copying or parsing again. But preventing an instance of an A class will be my way. So, in this aspect, Java didn't changed in the last 10 years... It's a long time ago I've used Java for some real projects.
    You can, however, create an instance of another class, that copies the values off a priori A instance. Your example code was one way, another way could be to have a "copy constructor":
    public class A {
    public A(A model) {
    this.att1 = model.att1;
    this.att2 = model.att2;
    public class A1 {
    public A1(A model) {
    super(model);
    ... // do whatever A1-specific business
    )Still, I prefer my former solution less disturbing: I find the temporary A instance redundant and awkward.Nice to know. I prefer the first solution too.
    Thank you again for the help and advices. My mind is searching sometimes for strange solutions, where the real is so close ;-)
    Andreas

Maybe you are looking for

  • Language problem on import

    hi everyone! i ve oracle 10g2 XE Universal already installed on my pc. i changed NLS_LANG in registry in GREEK_GREECE.EL8ISO8859P7. i am trying to import a file in XE that i exported from oracle 10g2EE (charset AMERICAN_AMERICA.EL8ISO8859P7). import

  • How to display mouse coordinates???

    I wanted to display my custom cursors x and y coordinates on my movie. It seems like it should only be a few lines of actionscript but I can't seem to figure it out. Has anyone done this. If so I would appreciate some help. Thx I am using Flash MX by

  • How to set the View instance and view  attribute to lov field ?

    Hi I created lov and textfield programatically. I want to set the viewattribute and view instance to that items(lovbean, texfieldbean). How to set programatically? Thanks in Advance Awadesh

  • Solaris 10 with Qlogic card facing network issue

    Dear Community, I am facing network issue with one of M5000 server card vender is qlogic and switch is brocarde, if we reset the port from switch side, it will work for nearly 2 hours. after that ping will stop. here is the details. and there is no e

  • Remote Silent Monitoring (RSM) Disabling Supervisor Team Structure

          We have a need to silent monitor across UCM clusters and UCCE instances.  According to the the installation/admin guide (re. version 9.1), this is how cross cluster/instance monitoring can be possible.  My question, from a relatively high level