JButton在actionListener中屈服时保持灰色

时间:2016-01-25 21:39:00

标签: java swing jbutton

在我的程序中,我有一个按钮,点击后将“生成一个点击模式”(Simon Says),在生成模式功能中,它会将按钮的颜色设置为“变亮”,然后默认为屈服之间。问题是,在屈服时,按钮会保持“灰色”状态,就好像它已被点击一样。有没有办法防止没有多线程的灰色(我不希望它变得凌乱而不是它)?如果需要,我可以发布完整的源代码,但这是正在执行它的部分。 最后一点,我知道答案可能非常明显,但正如你可以通过我的代码告诉我的大脑以非正统的方式工作。

for(int i = 0; i < 4; i++){ //button creation within init of applet
        JButton button = new JButton(); 
            button.setName("" + colorToChar[i]);
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    if(simonDebounce == false && pattern[currentIndex] == (button.getName().charAt(0))) { //debounce is false and the current check is equal to the pattern
                        score ++;
                        currentIndex ++;
                        if(currentIndex > (pattern.length-1)){
                            sleep(100);
                            generatePattern(currentIndex);
                        }; //make it harder by increasing the pattern length by "1" will change later
                    }else if(simonDebounce == false && pattern[currentIndex] != (button.getName().charAt(0))){ //you can click and the you clicked a wrong button
                        score = 0;
                        sleep(100);
                        generatePattern(3);
                    };
                };
            });
            button.setBackground(defaultColors[i]);
        root.add(button); //root is a JComponent container
        button.setBounds( 100 + (i > 1 ? 150 : 0), 100 + ( i % 2 == 1 ? 150 : 0 ), 125, 125);
        buttons[i] = button;
    };
    sleep(3000);
    pattern = generatePattern(3); //start with three

这是generatePattern

protected char[] generatePattern(int count){
    char[] newPattern = new char[count];
    currentIndex = 0;
    simonDebounce = true; //Dont count button clicks
    for(int i=0; i<count; i++){
        int patternIndex = pseudoRandom(1, 4) - 1; //Random color
        newPattern[i] = colorToChar[patternIndex]; //'r', 'g', 'b', 'y' -> Don't mind this weird way of doing this, I'm much more used to more fluid languages
        buttons[patternIndex].setBackground(brightenedColors[patternIndex]);
        sleep(500);
        buttons[patternIndex].setBackground(defaultColors[patternIndex]);
        sleep(500);
    };
    pattern = newPattern; //a global 
    simonDebounce = false; //You can click a button
    return(newPattern); //returned, although not used anymore
};

0 个答案:

没有答案