samedi 12 mai 2018

CheckBox problems

I'm currently learning gui by myself, I'm having troubles with the JCheckBox. How can I make only one answer mark? currently, I can mark the two answers. mt ideal is that the user could pick only one choice at a time, and if he picks the other one it deletes the pick of the first one. can somebody help? thanks!

import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class CheckBoxTry 
{
    JCheckBox show1,show2;
    JLabel label1, label2;
    private JFrame jf; 
    public CheckBoxTry(){
        jf= new JFrame();
        jf.setSize(300,300);
        jf.setVisible(true);
        jf.setLayout(new GridLayout(2,2));
        label1= new JLabel("");
        jf.add(label1);
        label2= new JLabel("");
        jf.add(label2);
        show1=new JCheckBox("show1");
        show2=new JCheckBox("show2");
        jf.add(show1);
        jf.add(show2);
        event e= new event();
        show1.addItemListener(e);
        show2.addItemListener(e);
    }
    public class event implements ItemListener{
        public void itemStateChanged (ItemEvent e){
            if (show1.isSelected())
            {
                label1.setText("1 selected");
            }else{
                label1.setText("");
            }

            if (show2.isSelected())
            {
                label2.setText("2 selected");
            }else{
                label2.setText("");
            }
        }
    }
    public static void main(String[] args)
    {
        CheckBoxTry as= new CheckBoxTry();
    }
}




Aucun commentaire:

Enregistrer un commentaire