PeterMmm
PeterMmm

Reputation: 24630

JRadioButton in JPopupMenu does not close the menu after selecting

With the above code i want to close the popup right after click on one of the radio buttons but the popup stays open.

Is there something build-in in swing or must i call actionPeformed and close the popup explicity ?

public class NewClass extends JFrame {

    NewClass() {
        setSize(100,100);

        JPopupMenu pop = new JPopupMenu();

        JRadioButton log1 = new JRadioButton("Level 1");
        pop.add(log1);

        JRadioButton log2 = new JRadioButton("Level 2");
        pop.add(log2);

        JPanel p = new JPanel();
        add(p);
        p.setComponentPopupMenu(pop);
    }

    public static void main(String[] args) {
        new NewClass().setVisible(true);
    }
}

Upvotes: 1

Views: 766

Answers (2)

mKorbel
mKorbel

Reputation: 109813

look at JRadioButton#addItemListener() and check if ButtonGroup is usefull in your case

EDIT:

Is there something build-in in swing or must i call actionPeformed and 
close the popup explicity ?

I don't know..., good question, but if you adds JRadioButton to the JMenuItem then is build-in look here

Upvotes: 1

Jonas
Jonas

Reputation: 1234

I would have added actionlisteners on the buttons so when you press a button you then use:

public void actionPerformed(ActionEvent e){
    pop.setVisible(false);
    pop.dispose();
}

Upvotes: 0

Related Questions