简体   繁体   中英

How to deselect already selected JRadioButton by clicking on it

Let's say we are having some JRadioButton s which belongs to same ButtonGroup , when user clicks on a JRadioButton it got selected. I want to add a feature that when user click on already selected JRadioButton , it gets deselected, that is whole ButtonGroup will have no JRadioButton selected. I already searched which leads me hint to use, ButtonGroup method, clearSelection. but problem is that when user clicks on already selected JRadioButton, it is not generating any ItemStateChangeEvent , which is generating by clicking on other unselected JRadioButton s.

I'd use the approach cited . Because a JRadioButton is a JToggleButton , a mouse gesture is possible but problematic. I'd use a MouseListener on the enclosing panel and Key Bindings on the buttons as shown below. Click in the panel surrounding the buttons or press the escape key to clear the selection of all buttons in the ButtonGroup .

图片

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.KeyStroke;

/**
 * @see https://stackoverflow.com/a/37599961/230513
 */
public class Test {

    private static final String UNSELECT = "UNSELECT";

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new JPanel(new GridLayout(1, 0, 5, 5));
        p.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
        ButtonGroup group = new ButtonGroup();
        JRadioButton r1 = create("One", group);
        JRadioButton r2 = create("Two", group);
        p.add(r1);
        p.add(r2);
        p.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                group.clearSelection();
            }
        });
        f.add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private JRadioButton create(String name, ButtonGroup group) {
        JRadioButton b = new JRadioButton(name);
        group.add(b);
        b.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), UNSELECT);
        b.getActionMap().put(UNSELECT, new AbstractAction(UNSELECT) {
            @Override
            public void actionPerformed(ActionEvent e) {
                group.clearSelection();
            }
        });
        return b;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Test()::display);
    }
}

Or, as an alternate approach, override ButtonGroup#setSelected(...) :

import java.awt.*;
import java.util.Arrays;
import javax.swing.*;

public class Test2 {
  public JComponent makeUI() {
    JPanel p = new JPanel(new GridLayout(2, 1));
      p.add(makePanel("Default ButtonGroup", new ButtonGroup()));
      p.add(makePanel("Custom ButtonGroup", new ButtonGroup() {
          private ButtonModel prevModel;
          private boolean isAdjusting = false;
          @Override public void setSelected(ButtonModel m, boolean b) {
              if (isAdjusting) {
                  return;
              }
              if (m.equals(prevModel)) {
                  isAdjusting = true;
                  clearSelection();
                  isAdjusting = false;
              } else {
                  super.setSelected(m, b);
              }
              prevModel = getSelection();
          }
      }));
    return p;
  }
  private JComponent makePanel(String title, ButtonGroup g) {
    JPanel p = new JPanel();
    p.setBorder(BorderFactory.createTitledBorder(title));
    for (String s: Arrays.asList("aaa", "bbb", "ccc")) {
      AbstractButton r = new JRadioButton(s);
      //AbstractButton r = new JToggleButton(s);
      p.add(r);
      g.add(r);
    }
    return p;
  }
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new Test2().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM