Here you can find the source of exclusive(final JCheckBox first, final boolean firstState, final JCheckBox second, final boolean secondState)
Parameter | Description |
---|---|
first | the first checkbox |
firstState | the state of the first checkbox |
second | the second checkbox |
secondState | the state of the second checkbox |
public static void exclusive(final JCheckBox first, final boolean firstState, final JCheckBox second, final boolean secondState)
//package com.java2s; /*//from w ww.ja v a 2 s .c om * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main { /** * Declares states for two checkboxes to be mutually exclusive. When one of the checkboxes goes to the specified state, other is * disabled and forced into reverse of the state (to prevent very fast users from selecting incorrect state or incorrect * initial configuration). * * @param first the first checkbox * @param firstState the state of the first checkbox * @param second the second checkbox * @param secondState the state of the second checkbox */ public static void exclusive(final JCheckBox first, final boolean firstState, final JCheckBox second, final boolean secondState) { ActionListener l = new ActionListener() { /** * One way check for the condition * @param checked the first to check * @param checkedState the state to match * @param changed the changed control * @param impliedState the implied state */ private void check(final JCheckBox checked, final boolean checkedState, final JCheckBox changed, final boolean impliedState) { if (checked.isSelected() == checkedState) { changed.setSelected(impliedState); changed.setEnabled(false); } else { changed.setEnabled(true); } } /** * {@inheritDoc} */ public void actionPerformed(ActionEvent e) { check(first, firstState, second, !secondState); check(second, secondState, first, !firstState); } }; first.addActionListener(l); second.addActionListener(l); l.actionPerformed(null); } }