Search code examples
javaswingjradiobuttonjava-5

JRadioButton setMnemonic broken Java 1.5


I am attempting to convert a short JComboBox to a JRadioButton group. When defining the radio buttons, it is telling me it doesn't like my setMnemonic syntax.

My code:

public JRadioButton mailRadio = new JRadioButton("Mail");
mailRadio.setMnemonic(KeyEvent.VK_M);

It will show setMnemonic(int) in intellisense (or whatever the java version is called), but as soon as I accept that, mailRadio.setMnemonic is underlined for a syntax error. Hovering over it gives the error "Type mailRadio.setMnemonic not found." Compiling gives the error "Invalid method declaration; return type required."

As far as I know, I am attempting to do neither of these things. I haven't used Java in a long time, and I'm very rusty. I don't know what I'm doing wrong.

I have three JRadioButtons like this, and it will only show the error on the first one, until I comment it or remove then, then the error moves down to the next.

I am using JDeveloper 10.1.3.5, Java 1.5.0_06. Upgrading either is not an option at the moment, unfortunately.


Solution

  • Seeing that you used public to declare the variable, I'm assuming the code snippet is inside a class declaration.

    You can't use statements (and a method call such as setMnemonic is a statement) in a class declaration. You should call this method inside a constructor :

    public class XXX {
        public JRadioButton mailRadio = new JRadioButton("Mail");
    
        public XXX() {
            mailRadio.setMnemonic(KeyEvent.VK_M);
        }       
    }
    

    An alternative that looks more like what you initially tried to do is an initializer block:

    public class XXX {
        public JRadioButton mailRadio = new JRadioButton("Mail");
    
        {
            mailRadio.setMnemonic(KeyEvent.VK_M);
        }
    }
    

    But this is bad practice, I'm only mentioning it for completeness' sake.

    More details in the doc.