简体   繁体   中英

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?

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.

"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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM