MaciekPaluch
MaciekPaluch

Reputation: 1

Java: How to disable a button in java?

I want to automatically disable a few buttons. I wrote the code:

import javax.swing.*;

public int[] zamrozone = new int[4];

a1 = new JButton("A1");
a2 = new JButton("A2");
a3 = new JButton("A2");
a4 = new JButton("A2");
a5 = new JButton("A2");

   private void zamroz()
    {

        zamrozone[0]=1;
        zamrozone[1]=1;
        zamrozone[2]=1;
        zamrozone[3]=0;
        zamrozone[4]=0;

        for(int i=0; i<8; i++) //losuje 8 statkow
            {
                if(zamrozone[i]==1)
                   "a"+i.setEnabled(false); // here is an error
            }
    }

Unfortunately this is not working. Anyone know how to do this?

Upvotes: 0

Views: 256

Answers (2)

sam
sam

Reputation: 4397

You can put the JButtons in an array and then use their index:

import javax.swing.*;

final int SIZE = 5;

JButton[] buttons = new JButton[SIZE]
for (int i=0; i<SIZE;i++) {
    buttons[i] = new JButton("A" + i)
}

public int[] zamrozone = new int[SIZE];

private void zamroz()
{ 
    zamrozone[0]=1;
    zamrozone[1]=1;
    zamrozone[2]=1;
    zamrozone[3]=0;
    zamrozone[4]=0;

    for (int i=0; i<SIZE; i++) //losuje SIZE statkow
    {
        if (zamrozone[i]==1) {
            buttons[i].setEnabled(false); // here is an error
        }
     }
     :
}

Use defined SIZE rather then constant values all over your code to avoid OutOfBounds exception and make the code easier to change/maintain.

Upvotes: 1

Dragondraikk
Dragondraikk

Reputation: 1679

"a"+i.setEnabled(false); cannot work as variables don't work that way. What you are doing right there is trying to call setEnabled on the integer i and then adding the return value (which does not exist as setEnabled returns void) to the String literal "a".

I would suggest storing your buttons in an array as well and then simply calling buttonArray[i].setEnabled(false) inside the loop.

Upvotes: 0

Related Questions