【问题标题】:Set toggleButton non-clickable设置toggleButton不可点击
【发布时间】:2016-09-23 07:38:12
【问题描述】:

这是我的电影GUI。有 30 个JToggleButton。我希望它通过检查MySQL 中的值来找出选择了哪个座位。如果未选择座位,则它们是可点击的,否则不可点击。

public selectSeat(String title, String day, String time) throws Exception
{
    JPanel topPanel= new JPanel(new GridLayout(1, 15));
    RectDraw rect= new RectDraw();
    rect.setPreferredSize(new Dimension(30,25)); 
    topPanel.add(rect);

      JToggleButton[] ButtonList = new JToggleButton[30];

        JPanel ButtonPanel= new JPanel(new GridLayout(5,15,45,25)); // row,col,hgap,vgap
        for(int i = 0; i < 30; i++) {
            a=i+1;
            ButtonList[i]= new JToggleButton(""+a);
            ButtonPanel.add(ButtonList[i]); 
        }
         int no= findNo(day,title,time); // get hall number
         System.out.println(no); 
         List<String> seats= checkSeat(no);  // get selected seats value
         System.out.println(seats); // [22,23]
        for(String s : seats)
        {
            for(int j = 0; j<30;j++)
            {
                if(s.contains(ButtonList[j].getText()))  // if seats label with 22 and 23
                {
                    ButtonList[j].setEnabled(false); // non-clickable
                }
            }

        }

但是,标有 2、3、22 和 23 的切换按钮变得不可点击。

【问题讨论】:

    标签: java mysql loops for-loop togglebutton


    【解决方案1】:

    好的,我就是这样解决的

    for(String s : seats) // remove [] brackets (22,23)
                {
    
                    String[] selected=s.split(","); // remove the comma
                    for (String t: selected) 
                    {
                        for(int j = 0; j<30;j++)
                        {
                            if(ButtonList[j].getText().equals(t))  // if seats label with 22 and 23
                            {
                                ButtonList[j].setEnabled(false); // non-clickable
                            }
                        }
                    }
    
                }
    

    【讨论】:

    • 不,这过于复杂且不必要。调试的噩梦。
    • 是的,根据我的回答。只需要一个简单的 for 循环即可。
    【解决方案2】:

    您正在检查“23”是否包含“2”或“3”并且确实包含。摆脱 outer for 循环,而是简单地检查 ArrayList contains 字符串,而不是 List 的字符串是否包含子字符串:

    for(int j = 0; j < ButtonList.length; j++) {
        ButtonList[j].setEnabled(!seats.contains(ButtonList[j].getText()));
    }
    

    【讨论】:

    • 我试过你的代码,但切换按钮仍然可以点击。我认为应该拆分arrayList
    • @JohnJoe:我/我们不知道,因为我们不知道数组列表包含什么。我最初假设它包含代表座位号的字符串,但我似乎假设不正确。
    • System.out.println(seats); // [22,23] 座位打印 [22,23]
    【解决方案3】:

    错误是if语句if(s.contains(ButtonList[j].getText())) 您正在检查您的字符串 s 是否包含您应该比较的按钮数量,如果它们与 s.equals() 相等

    【讨论】:

    • 我试过了,但切换按钮仍然可以点击。我认为应该拆分arrayList
    • @JohnJoe:你的 ArrayList 到底包含什么?你的意思是它不仅仅是一个数字的字符串表示?然后你需要改进这个问题,以便它实际上可以回答。
    猜你喜欢
    • 1970-01-01
    • 2013-07-30
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多