0

I want to customize a button as the code shows below

public class CustomButton extends JToggleButton{

    public CustomButton() {
    }
  
    public void paintComponent(Graphics g){
        Color bg,text;
        if(isSelected()){
            bg = Color.decode("#000");
            text = Color.decode("#fff");
        }else{
            bg = Color.decode("#fff");
            text = Color.decode("#000"); 
        }
        setBackground(bg);
        setForeground(text);
        super.paintComponent(g);
    }
}

I got this error =>

Incompatible types : CustomButton cannot be converted to jButton

jButton2 = new CustomButton();

Can you tell where is the problem?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Alaey
  • 41
  • 2
  • 8
  • 2
    Read the API for JToggleButton. A JToggleButton is NOT a JButton, so you can't cast it to a JToggleButton. Also, I have no idea what you are attempting to do but your logic is wrong. A painting method should NOT set a property of a component. That is you should NOT invoke setBackground() or setForeground() in the painting method. If you want to change the foreground/background, then add a `ChangeListener` to the button and set the properties when the state changes. So there is no need to extend JToggleButton, just implement the ChangeListener. – camickr Jan 19 '21 at 18:25
  • yes you have right i am using JButton not JToggleButton thank you sir – Alaey Jan 19 '21 at 18:45

0 Answers0