hamza-don
hamza-don

Reputation: 465

Limit the number of selected JToggleButton

I'm new on swing java, I maked an array of jtoggle buttons and my problem is that I want to limit the number of selected(toggled) buttons for 4 toggled buttons. Is there any property that allows me to do that ? Here is my code example.

package adad;

import java.awt.*; import java.awt.event.*; 
import javax.swing.*;
public class essayer extends JFrame
{
 private JToggleButton jb_essai[] = new JToggleButton[6];

 JButton pressme = new JButton("Press Me");
 essayer()        // the frame constructor
 {
super("Toggle boutons");
setBounds(100,100,300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
JPanel pane = getContainer();
con.add(pane);    
setVisible(true);
 }

 class ToggleAction implements ActionListener
{
private JToggleButton jb_essai[];
public ToggleAction(JToggleButton a_jb_essai[])
{
  jb_essai = a_jb_essai;
}

public void actionPerformed(ActionEvent e)
{
  String etatBoutons = "";
  int size = jb_essai.length;

  for(int i=0;i<size;i++)

  {
    String tmp = "Bouton "+(i+1)+" : ";
    if(jb_essai[i].isSelected()==true  )
    {
      tmp+="enfonce";
    }
    else
    {
      tmp+="relache";
    }
    tmp+="\n";
    etatBoutons +=tmp; 
  }
  System.out.println(etatBoutons+"\n---------");
     }

   }
private JPanel getContainer() 
 {

GridLayout thisLayout = new GridLayout(6,2);
JPanel container = new JPanel();
ToggleAction tga = new ToggleAction(jb_essai);
container.setLayout(thisLayout);
int j=6;
for (int i=0;i<j;i++)
{
  String s = String.valueOf(i+1);

  container.add(jb_essai[i]= new JToggleButton(s)); // actuellement tt s'affiche sur un   même colone.
  jb_essai[i].addActionListener(tga);

}
return container;
}

 public static void main(String[] args) {new essayer();}
  }

Upvotes: 0

Views: 585

Answers (2)

camickr
camickr

Reputation: 324098

Is there any property that allows me to do that ?

No, you need to write your own code.

Add a common ItemListener to every toggle button. Then when a button is selected you loop though your toggle button array to count the number of selected toggle buttons.

If the count is greater than 4 then you display a JOptionPane with an error message and your reset the last selected button to be unselected. You can use the getSource() method of the ItemListener to get the toggle button.

Or maybe you can extend the ButtonGroup class to implement similar behaviour.

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168815

Is there any property that allows me to do that ?

No. There is a ButtonGroup that allows 'one of many'. But that is 1, not N of many. Anything beyond that you'll need to code yourself.

Upvotes: 1

Related Questions