Search code examples
javajbuttondice

Limit Number of Times JButton can be clicked?


I have a dice program in Java that roll 5 dice by clicking a "Roll" button.

I am trying to make the button so that after it is clicked 3 times, it is disables and can not be clicked unless it is closed and re-opened.

Thank you!

topPanel.add(button1);
int i = 0;
button1.setToolTipText("Click this button to roll the dice.");
button1.setForeground(Color.red);
button1.setContentAreaFilled(false);
button1.setFocusPainted(false);
button1.setBorderPainted(false);
if (i >= 3) {
  button1.setEnabled(false);
} else {

  i++;
}
button1.setFont(new Font("Arial", Font.BOLD, 15));
button1.setPreferredSize(new Dimension(40, 25));
button1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
          die1.roll();
          die1.draw(dk);
          die2.roll();
          die2.draw(dk);
          die3.roll();
          die3.draw(dk);
          die4.roll();
          die4.draw(dk);
          die5.roll();
          die5.draw(dk);

Solution

  • use a variable and if condition declare variable outside

    int i=0;
    

    inside button action performed event

    if(i>=3){
      button.setEnabled(false);
    }else{
      // do anything
    }
    i++;
    

    move code outside of event

        int i = 0;
    
        topPanel.add(button1);
        button1.setToolTipText("Click this button to roll the dice.");
        button1.setForeground(Color.red);
        button1.setContentAreaFilled(false);
        button1.setFocusPainted(false);
        button1.setBorderPainted(false);
    
        button1.setFont(new Font("Arial", Font.BOLD, 15));
        button1.setPreferredSize(new Dimension(40, 25));
        button1.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent event) {
    
    if (i >= 3) {
          button1.setEnabled(false);
        } else {
    
                  die1.roll();
                  die1.draw(dk);
                  die2.roll();
                  die2.draw(dk);
                  die3.roll();
                  die3.draw(dk);
                  die4.roll();
                  die4.draw(dk);
                  die5.roll();
                  die5.draw(dk);
        }
    i++;
    }