【问题标题】:Java How to use a JButton that created in for loop, outside the loop?Java如何在循环外使用在for循环中创建的JButton?
【发布时间】:2017-04-06 21:43:10
【问题描述】:

我的观点是如何在 for 循环之外使用方法。我不能在外面使用,因为所有按钮都是为循环创建的。每当我创建一个数组按钮时,我都会给出一些按钮的属性,它们不起作用

private clicks = 0;
JButton[] test = new JButton[24];
for(i=0; i < 24; i++){
    test[i] = new JButton("" + i);
    test[i].setBackground(Color.YELLOW);
    //and some properties ,action listener
    if((clicks < 15) && clicks % 5 !=0 ) {
        test[].setVisible(False);// i don't know what to write in "[]"
    }
    clicks++;
    else if(clicks%5 == 0) {
        JOptionPane.showMessageDialog(p1, calculateAverage(anArrayList));
    } //calculate average is a method that i created it
}
   test[].addActionListener(new ActionListener() {//i dont know what to write in [] 

                public void actionPerformed(ActionEvent e) {    

                    if((clicks < 15) && clicks % 5 !=0 ) {
            test[].setVisible(False);// i don't know what to write in "[]"

        }
        clicks++;
        else if(clicks%5 == 0) {
            JOptionPane.showMessageDialog(p1, calculateAverage(anArrayList));
         } 
     }     

calculateAverage 方法总是给出相同的输出。我怎样才能解决这个问题?当我把if-else 代码放在循环之外时,我无法使用按钮。

【问题讨论】:

  • "我不能在外部使用,因为所有按钮都是为循环创建的" 但是您在循环外部创建了数组,因此您可以访问它。 test[i]。另外,请花时间使用空格键并正确缩进代码。
  • 对不起。我试图展示如何在外面创建按钮。通常按钮是在没有数组的内部创建的
  • 所以听起来您回答了自己的问题 - 如果您想在循环之外使用它们,只需使用您发布的代码即可。如果您可以提供一些澄清,那就太好了,因为我不知道这里有什么问题。
  • 假设这段代码紧跟在 for 循环之后 我为什么要这样假设?而是创建并发布一个有效的minimal reproducible example,我们可以复制粘贴并演示您的问题。请不要使用浏览器的“返回”按钮来编辑您的问题,它会破坏其他人所做的编辑。并正确格式化您的代码
  • calculateAverage 方法总是给出相同的输出 那么,然后以minimal reproducible example 形式发布该代码。否则,您将被否决并且您的问题已关闭。 (重新)阅读help centerHow to Ask 部分

标签: java arrays swing jbutton


【解决方案1】:

不完全确定您要做什么,但我会猜测并声明:

  1. 您不需要数组来跟踪您的按钮
  2. 您不需要为每个按钮都创建一个新的 ActionListener
  3. 在创建按钮时应将 ActionListener 添加到按钮中

相反,您创建一个由所有按钮共享的通用 ActionListener,并在创建按钮时将侦听器添加到按钮。然后,您同时将按钮添加到面板,因此不需要阵列。代码的基本结构可以是这样的:

ActionListener al = new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        JButton button = (JButton)e.getSource();

        if (...)
            button.setVisible( false ); 
    }
};

for (...)
{
    JButton button = new JButton(...);
    button.addActionListener( al );
    panel.add( button );
}

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 2015-12-12
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多