I was trying to make a button that switches the window background from default to red.
I haven't found any preset colors to match the default so i tried to get it from panel.getBackground when i created it. I have an error at line 11, i don't know how to check the current background color.
JPanel panel = new JPanel();
panel.setBounds(0, 0, 434, 262);
frame.getContentPane().add(panel);
panel.setLayout(null);
panel.setVisible(true);
Color c=panel.getBackground();
JButton btnRed = new JButton("Red");
btnRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(panel.getBackground(c));{
panel.setBackground(Color.RED);
}
else{
panel.setBackground(c);
}
}
});
解决方案
You want to compare the Color, this is an Object so equals() is the way... also an if expects a boolean and will finish when ; is found, so this:
if(panel.getBackground(c));{
// ↑ not a boolean ↑
// ↑
// ; is wrong
must be
if(panel.getBackground().equals(c)){