简体   繁体   English

Java:如何在Java中禁用按钮?

[英]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: 您可以将JButtons放入数组中,然后使用它们的索引:

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. 在代码中使用已定义的SIZE而不是常量值,以避免OutOfBounds异常并使代码更易于更改/维护。

"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上调用setEnabled ,然后将返回值(因为setEnabled返回void ,该值不存在)添加到字符串文字“ a”中。

I would suggest storing your buttons in an array as well and then simply calling buttonArray[i].setEnabled(false) inside the loop. 我建议也将按钮存储在数组中,然后在循环内简单地调用buttonArray[i].setEnabled(false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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