Overriding Methods on JRadioButton and JButton

public class CustomRadioButton extends JRadioButton {
    private final Color pressedForeground = Color.YELLOW;
    private final Color foreground = Color.WHITE;
    private final ImageIcon icon = new ImageIcon(getClass().getResource("/com/project/Graphics/Button_UP.gif"));
    private final ImageIcon pressedIcon = new ImageIcon(getClass().getResource("/com/project/Graphics/Button_DOWN.gif"));
    public CustomRadioButton() {
        setBorderPainted(false);
        setFocusPainted(false);
        setIcon(icon);
        setForeground(foreground);
        setSelectedIcon(pressedIcon);
        setContentAreaFilled(false);
        setHorizontalTextPosition(SwingConstants.CENTER);
        setFont(new Font("Arial", Font.BOLD, 12));
        setMargin(new Insets(0, 0, 0, 0));
        setMinimumSize(new Dimension(101,25));
        setMaximumSize(new Dimension(101,25));
        setPreferredSize(new Dimension(101,25));
        setBorder(null);
    @Override
    public Icon getIcon() {
        setForeground(foreground);
        return super.getIcon();
    @Override
    public Icon getSelectedIcon() {
        setForeground(pressedForeground);
        return super.getSelectedIcon();
}Why does this code cause an infinite loop when it's in a selected state? I ran a profiler on my project and found that it infinitely calls painComponent(), getIcon(), and getSelectedIcon() when it's pressed. Yet when I create my object as a regular JRadioButton with all of these setting and an ActionListener to change the foreground color there is no infinite loop. Am I missing something here?

A paintComponent override doen't seem to trigger the repaint loop.import java.awt.*;
import javax.swing.*;
public class SelectedForegroundRadioButtonTest {
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            new SelectedForegroundRadioButtonTest().makeUI();
   public void makeUI() {
      ButtonGroup group = new ButtonGroup();
      JPanel panel = new JPanel(new GridLayout(0, 1));
      for (int i = 0; i < 5; i++) {
         JRadioButton button = new SelectedForegroundRadioButton("Button " + i);
         panel.add(button);
         group.add(button);
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
class SelectedForegroundRadioButton extends JRadioButton {
   private final Color pressedForeground = Color.ORANGE;
   private final Color defaultForeground = Color.BLUE;
   private final int iconSize = 16;
   public SelectedForegroundRadioButton(String text) {
      super(text);
      setIcon(new DefaultIcon());
      setPressedIcon(new PressedIcon());
      setSelectedIcon(new SelectedIcon());
   @Override
   public void paintComponent(Graphics g) {
      setForeground(isSelected() ? pressedForeground : defaultForeground);
      super.paintComponent(g);
   class DefaultIcon implements Icon {
      public void paintIcon(Component c, Graphics g, int x, int y) {
         g.setColor(isSelected() ? pressedForeground : defaultForeground);
         g.drawOval(0, 0, iconSize, iconSize);
         g.drawOval(1, 1, iconSize - 2, iconSize - 2);
      public int getIconWidth() {
         return iconSize;
      public int getIconHeight() {
         return iconSize;
   class PressedIcon extends DefaultIcon {
      @Override
      public void paintIcon(Component c, Graphics g, int x, int y) {
         super.paintIcon(c, g, x, y);
         g.setColor(Color.GREEN);
         g.fillOval(3, 3, iconSize - 6, iconSize - 6);
   class SelectedIcon extends PressedIcon {
      @Override
      public void paintIcon(Component c, Graphics g, int x, int y) {
         super.paintIcon(c, g, x, y);
         g.setColor(Color.RED);
         g.fillOval(5, 5, iconSize - 10, iconSize - 10);
}db

Similar Messages

  • Extending classes and overriding methods

    If I have a class which extends another, and overrides some methods, if I from a third class casts the extending class as the super class and calls one of the methods which gets overrided, is it the overrided method or the method of the superclass which get executed?
    Stig.

    Explicit cast can't enable the object to invoke super-class's method. Because dynamic binding is decided by the instance. The cast can just prevent you from using methods only defined in sub-class, but it does not let the object to use super-class's method, if the method's been overrided. Otherwise, the polymophism, which is one of the most beautiful feature of Object-Oriented thing, can't be achieved. As far as I know, the only way to use super-class's method is the super keyword in the sub-class, and seems no way for an object to do the same thing (I may wrong, since I haven't read the language spec).
    here's a small test:
    public class Test {
    public static void main(String[] args){
    A a = new B();
    a.method();
    ((A)a).method();
    class A{
    public void method(){
    System.out.println("A's method");
    class B extends A{
    public void method(){
    System.out.println("B's method");
    The output is:
    B's method
    B's method

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • Override method on an object construted by somebody

         customMenuComponent.addCustomLink(new CustomLinkComponenet("strlink","Storage Inbox",Index.class) {
                   protected BookmarkablePageLink getBookmarkablePageLink() {
                        BookmarkablePageLink bookmarkablePageLink=   new BookmarkablePageLink("link",clazz){
                             protected void onBeforeRender() {
                                  super.onBeforeRender();
                        return bookmarkablePageLink;
              customMenuComponent.addCustomLink(new CustomLinkComponenet("strlink","Storage Inbox",Index.class) {
                   protected BookmarkablePageLink getBookmarkablePageLink() {
                        BookmarkablePageLink bookmarkablePageLink=   super.getBookmarkablePageLink(){
                             protected void onBeforeRender() {
                                  super.onBeforeRender();
                        return bookmarkablePageLink;
              });the second block of code does not compile please explain me why and what is the workaround ? i can override a method on a object when I initialize with new but cannot override if I get the object from super or somebody constructs why ?

    miro_connect wrote:
    in my case is there way to copy object returned from super to object created in sub and override methods ?Perhaps. You need to know about the implementation of the original object.

  • Some generic anonymous class overriding methods compile, while others don't

    I have the following (stripped-down) code. The abstract class SessionHandler<T> is used by other code to define and run an operation that needs a session to something. This is best done in my code with anonymous classes, because of the shear number of operations defined. In the EntityOps<T> class, these work great. But, in the last class shown here, SomeClass, the anonymous class definition fails, though the semantics are almost identical. (List<T> vs.List<AnotherClass>) What am I doing wrong here? Or is this a bug in Java?
    Thanks, Tom
    public interface IEntityOps<T> {
        T get();
        List<t> getAll();
    public abstract class SessionHandler<T> {
        abstract T handle(Session session) throws Throwable;
        public final T perform() {
            ... calls handle(session) ...
    // These anonymous class definitions compile fine!
    public class EntityOps<T> implements IEntityOps<T> {
        public T get() {
            T ret = null;
            ret = new SessionHandler<T>() {
                T handle(Session s) throws Throwable {
                    T ret = (some T object calculation);
                    return ret;
            }.perform();
            return ret;
        public List<T> getAll() {
            T ret = null;
            return new SessionHandler<List<T>>() {
                List<T> handle(Session s) throws Throwable {
                    List<T> ret = (some List<T> calculation);
                    return ret;
            }.perform();
    // This anonymous class definition fails with the error:
    // "SomeClass.java": <anonymous someMethod> is not abstract and does not override abstract method handle()
    //     in SessionHandler at line XX, column XX
    public class SomeClass {
        public List<AnotherClass> someMethod() throws {
            List<AnotherClass> ret = null;
            ret = new SessionHandler<List<AnotherClass>>() {
                List<AnotherClass> handle(Session s) throws Throwable {
                    List<AnotherClass> ret = (some List<AnotherClass> calculation);
                    return ret;
            }.perform();
            return ret;
    }

    I added @Override above the abstract method override, and it provides this additional error:
    "HousingConfigImpl.java": method does not override a method from its superclass at line 382, column 17
    I have also reconstructed the code layout in a separate set of classes that have no dependancies, but there's no error coming from these!
    public class CustomThing {
    public interface ISomeInterface<T> {
        List<T> interfaceMethod();
    public abstract class SomeAbstractClass<T> {
        private Class _c = null;
        public SomeAbstractClass(Class c) {
            _c = c;
        protected Class getC() {
            return _c;
        public abstract T methodToOverride(Object neededObject) throws Throwable;
        public final T finalMethod() {
            try {
                return methodToOverride(new Object());
            } catch(Throwable e) {
                throw new RuntimeException(e);
    import java.util.List;
    import java.util.Collections;
    public class SomeInterfaceImpl<T> implements ISomeInterface<T> {
        public List<T> interfaceMethod() {
            return new SomeAbstractClass<List<T>>(CustomThing.class) {
                public List<T> methodToOverride(Object neededObject) throws Throwable {
                    return Collections.emptyList();
            }.finalMethod();
    import java.util.Collections;
    import java.util.List;
    public class SomeOtherClass {
        public List<CustomThing> someMethod() {
            return new SomeAbstractClass<List<CustomThing>>(CustomThing.class) {
                public List<CustomThing> methodToOverride(Object neededObject) throws Throwable {
                    return Collections.emptyList();
            }.finalMethod();
    }So, there's something about my code that causes it to be, somehow, different enough from the example provided above so that I get the error. The only differences in the override method definitions in my actual code are in the return type, but those are different in the example above as well. Here are the class declarations, anonymous abstract class creation statements, and abstract method declarations from the actual code.
    public abstract class SessionHandler<T> {
        abstract T handle(Session session) throws Throwable;
    public class EntityOps<T> implements IEntityOps<T> {
                return new SessionHandler<List<T>>(_mgr, _c, "getAll" + _c.getName()) {
                    List<T> handle(Session s) throws Throwable {
    public class HousingConfigImpl implements IHousingConfigOperations, ISessionFactoryManager {
                ret = new SessionHandler<List<Tenant>>((ISessionFactoryManager)this, Housing.class, "getTenantsInNeighborhood") {
                    List<Housing> handle(Session s) throws Throwable {I can't for the life of me see any syntactical difference between my example and the real code. But, one works and the other doesn't.

  • Do I need to override enum's hashCode() and equals()?

    Hi all:
    I have a enum type let's say it is
    public enum Type
      ONE,
      TWO;
    }If I want to compare the enum value to see if they are same value or not, let's say I have two:
    Type a = Type.ONE;
    Type b = Type.TWO;should I use a.equals(b) or (a == b) If I want to use it as another class's key field, and I want to override this class hashCode() and equals() methods.
    Can enum Type return the correctly hash code?
    For example the class is like:
    public Class A
      Type type;
      pubilc boolean equals(Object other)
        // here skip check class type, null and class cast
        if(other.type.equals(this.type))
           return true;
        else
         return false;
      public int hashCode()
        int result = 31;
        result += 31 * result + type.hashCode() ;
       // can we get correct hash code from enum here?
        return result;
    }

    Answered by the test code by myself.
    We can use either equals or (==) to see if they are the same value.
    The enum's hashCode() use System.identityHashCode() to generate the hashCode and they are always correct

  • ER: Override Methods feature should detect anonymous inner class scope

    Hi,
    Given the following code:
    public class Class1 {
        public static void main(String[] args) {
            Thread t = new Thread() {
                // line 4
            t.start();
    }When the cursor is placed on line 4, activating the Override Method dialog (Source menu), should show Thread methods that I can override, in addition to Object methods. Currently only the method from class Object are being shown. The same treatment should also apply to local method inner classes. This happens with the latest 11g preview 3, and all previous versions.

    Hi,
    I'll file an ER
    Frank

  • How does polymorphism work during overriding methods?

    Is there any example code to explain polymorphism whne overriding methods.

    > I suppose; however, I've read that overloading
    can be
    considered basically just a naming "trick". Ifyou
    extend a class and add a new method with a newname
    it isn't considered polymorphism.
    Overloading != Overriding.
    I'm pretty sure you know this, so I'm assuming you
    misread the subject. :o)
    ~You assume correctly. Ignore everything I said - Monday, tired, raining, <insert other excuse here>.
    Look at that, 1 post from 2000.
    Message was edited by:
    jbish

  • When overriding methods, should i call super at the begining or end

    Hi,
    when overriding methods such as swing's dispose(), and removeNotify(), should i call the super methods at the begining of the method or at the end?
    or does it make a difference....i was under the assumption i should call it at the end, that way i can do whatever necessary things i needed, then call the default....

    In cases where it truly doesn't matter, I think people tend to call super first. If I see it done some other way, it's an indicator that something unusual is going on. I'd liken calling super at the end of a method to iterating through an array in reverse inside of a 'for' loop. One can adopt either convention but people may get confused if you pick the less common one for no particular reason.

  • Polymorphism & Overriding Methods

    Hello all,
    I'm creating a set of objects and trying to achieve polymorphism. However, I've run into some problems with the principles of overriding methods. My class structure is as follows (using pseudocode);
    BaseClass
    - Subclass1
    - Subclass2
    class BaseClass{
    abstract Object get();
    abstract void set(Object);
    class Subclass1 extends BaseClass{
    String get(){ return String; }
    void set(String){ this.String = String; }
    class Subclass2 extends BaseClass{
    Boolean get() { return Boolean; }
    void set(Boolean){ this.Boolean = Boolean; }
    The problem is that the subclasses are capable of setting and returning objects of different types. In order to get the polymorphic behavior I'm looking for, what do I need to do? Should I remove the abstract methods in the baseclass? Should I leave the abstract methods in the baseclass and change the methods in the subclasses?
    Please advise,
    R. Alcazar

    I think the following change will get you what you want:
    class BaseClass{
      abstract Object get();
      abstract void set(Object);
    class Subclass1 extends BaseClass{
      Object get(){ return String; }
      void set(Object){ this.String = (String)Object; }
    class Subclass2 extends BaseClass{
      Object get() { return Boolean; }
      void set(Object){ this.Boolean = (Boolean)Object; }
    }You may also want to check the class of the object in set to catch any errors.
    Jon
    Do you know of a Java job in Orange County, California?
    If so then please contact me: "http://home.pacbell.net/jswinth/Resume.htm"

  • What is happening overriding method  in JVM

    1.what is happeining in JVM while i do overriding method ?
    2. why we cant create object for abstract class. what is happeining in JVM?
    HOW TO I KNOW internal process of JVM above i mentioned . is there any book for this?

    There's plenty of information in the Java Virtual Machine specification available here on this web site.
    http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#14787
    regards,
    Owen

  • I Just received the update to iTunes, when I I look at the screen I do not see the normal icons.  When I select movies I do not get the new downloads unless i select the list in the sub file. How do I get backto the old method of seeing and using iTunes??

    I Just received the update to iTunes, when I I look at the screen I do not see the normal icons.  When I select movies I do not get the new downloads unless I select the list in the sub file. How do I get back to the old method of seeing and using iTunes??

    I can tell you that this is some of the absolutely worst customer service I have ever dealt with. I found out from a store employee that when they are really busy with calls, they have third party companies taking overflow calls. One of those companies is Xerox. What can a Xerox call center rep possibly be able to authorize on a Verizon account?  I'm Sure there is a ton of misinformation out there due to this. They don't note the accounts properly or so everyone can see them. I have been transferred before and have asked if they work for Verizon or a third party also and was refused an answer so, apparently they aren't required to disclose that information. I spent a long time in the store on my last visit and it's not just customers that get the runaround. It happens to the store employees as well and it's beyond frustrating.

  • Payment method is declined and i cannot download neither update them. What can i do please??

    Payment method is declined and I cannot download apps neither update them. What can i do please??

    Do you have a different card that you could try, or does the 'none' option show on the payment's screen (you might not get 'none' if you owe money or if you have a payment coming up e.g. pre-order, auto-renewing subscription) ?
    What are you getting the 'declined' message on, credit card, debit card ... ? If it's a debit card then I don't think that they are still accepted as a valid payment method in all countries - from this page :
    You may be able to use other payment types in your country, like debit and Maestro cards.
    which implies that they are not accepted in all countries, and there have been a number of posts about them being declined.
    For a card to have a chance of being accepted it needs to be registered to exactly the same name and address (including format and spacing etc) that you have on your iTunes account, and have been issued by a bank in the country where you and your iTunes account are. If it is then you could check with the card issuer to see if it's them that are declining it, and if not then try contacting iTunes Support (these are user-to-user forums) and see if they know why it's being declined (but you might not be able to use a debit card) : http://www.apple.com/support/itunes/contact/ - click on Contact iTunes Store Support on the right-hand side of the page, then Account Management

  • I am unable to override the crop area and adjust the crop margins in Acrobat X Standard.

    When cropping in Acrobat X Standard, I am no longer able to override the crop area and make adjustments in Acrobat X Standard. All options are grayed-out.
    This seems to be a relatively new issue, but I'm not sure when I started having the problem. While use the tool frequently, it's not daily, but I'd say that this is within the past couple of weeks.
    I've scoured the settings. I've trolled message boards. I've checked for updates. I'm wondering if there's something I'm missing or if I need to do a full reinstall.
    I've inserted an image below showing the issue. (Changing the page range and/or units seems to make no difference. I tried that out of desperation.
    Thanks, folks!

    Wow!  All fixed.  I ran defaults delete -g which did not show immediate improvement, but then I rebooted.  I must admit I did a Safe Boot, just to throw in one other solution I had seen.  However, everything is back to normal.  Thanks very much.

  • I want to change my account payment method to none and I do not have a credit card yet.Plus, iTunes gave a message saying that I need to review my account and when I go there,the none payment method is hidden.

    I want to change my account payment method to none and I do not have a credit card yet.Plus, iTunes gave a message saying that I need to review my account and when I go there,the none payment method is hidden.

    Assuming that you want help and that you aren't just copying-and-pasting that thread's title and posting a link to it, then have you tried the steps on the post that I linked to in my first reply on that thread ?
    If you don't get the 'none' option when trying those instructions then you will need to enter credit card details before you will be able to use the account - when you've entered credit card details you should get the 'none' option and be able to remove your card details.
    Or you can create a new account, and follow, exactly, the steps on this page when creating it' : http://support.apple.com/kb/HT2534

Maybe you are looking for

  • Can't send mail from my ibook g4 mac os x 10.3.9

    Hello, Everything was working fine until yesterday (Oct 31st)- Suddenly i could receive mail directly via my mac ibook g4 (mac os x 10.3.9) but could no longer send anything out. How can i fix this problem and why did it suddenly happen? I don't thin

  • Help setting up Flash Builder 4.5 for PHP

    I am looking for a concise set of steps for setting up ALL requirements for running Flash Builder 4.5 for PHP.  I have been fighting for three days to get the TestDrive example up and running, with no success.  At every step of the way I have encount

  • Problem with SQLJ

    I am using SQLJ but cant seem to get the Named Iterators to work. // None None package db_interface; import oracle.jdbc.OracleDriver; import oracle.jdbc.*; import entity.*; import java.sql.SQLException; import java.sql.PreparedStatement; import java.

  • HT5625 How to share between iPad and iPhone

    New iPhone 5s. Can I get my apps from my iPad?thanks

  • Lost Album to Picture links

    I use Photoshop Elements 9 with Windows 7 and backed up both my pictures and saved my albums as a XML file.  Then my computer got a virus and the hard drive had to be wiped clean.  I restored my files and pictures from an external hard drive.  I rein