Reputation: 37
this is my first time posting a question here. I'm new to java and currently taking a course on it. This is the assignment: "Modify your button GUI program so that the buttons change color about every one second unless they've been pressed." ...that's all the instructions I was given. haha its like nothing!
So I know right now that when the button is clicked it turns white and stops changing. Technically that satisfies the instructions given, right? I don't think thats what they want though...Plus I'm just changing the opacity, so it's still changing color, you just can't see it, right? So what I wanted to know is if there was a way to maybe stop the button from changing color but keeping the color it already has like freezing it, instead of turning it white? I have a static JFrame jf, static Boolean pressed outside main and all the proper imports. My getColor() function just returns a random color. Thanks for the help/advice!!
public static void main(String[] args) {
jf = new JFrame("Homework 2");//constructed
jf.setSize(400,400);//sets window size
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//closes program
jf.setLayout(new GridLayout(2,4));
ArrayList<JButton> buttons = new ArrayList<JButton>();//array of button
pressed = true;
for(int i=1; i <= 8; i++) { //creates 8 buttons
JButton jb = new JButton();
jb.setText("Button " + i);
jb.setOpaque(pressed);
jb.setBorderPainted(false);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton theButton = (JButton)e.getSource();
theButton.setOpaque(!pressed);//makes it white if it has been clicked
}
});
buttons.add(jb);//add the button to the array
jf.add(jb);//adding to frame
}
jf.setVisible(true);//makes the window appear
while(true) {
for (JButton button : buttons){
button.setBackground(getColor());//change colors
}
try {
Thread.sleep(1000);//unless
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
Upvotes: 2
Views: 519
Reputation: 168825
To remove (stop) the button from further color changes, remove it from the buttons
array list when an action is performed.
Upvotes: 2
Reputation: 1240
I would create an array of 8 booleans to track the buttons. And check here whether the button should change its color:
for (int i = 0; i < 8; ++i){
if(!pressedArr[i]){
button.setBackground(getColor());//change colors
}
}
Also you need to track all the eight values, and when all of them are true
, just break out of the while
loop
Upvotes: 0