-3

I've been trying to make a Christmas tree decorating, and I try to apply the command design pattern to my buttons by making a commandInterface, buttonHandler class, and button classes as command objects. The class XmasTreeSwing contains the Gui elements and the buttons, below is the code for Button Handler and Command Interface. the Button classes implement the interface and the code goes like this. At run time, the Button handler class throws a cast exception. I want the ButtonHandler class to pass the commands to the proper Command object (lightButton in this example). Inside the XmasTreeClass:

    ButtonHandler handler = new ButtonHandler();
    lightButton.addActionListener(handler);
    ornamentButton.addActionListener(handler);

The commandInterface:

    public interface CommandInterface{
    public void processEvent();
    }

The ButtonHandler class:

public class ButtonHandler extends JButton implements ActionListener {

@Override //coding the event handling routine
public void actionPerformed(ActionEvent event) {

    CommandInterface command = event.getSource();

}

And Finally the LightButton class:

public class lightButton extends JButton implements CommandInterface {

public lightButton() {

}

@Override
public void processEvent() {
  //Some code
}

 public lightButton(String name) {
    super(name);
}
}//class
  • ok, so the cast will definitely not work. what's your thinking behind this? what do you want to achieve? – Ousmane D. Dec 13 '18 at 08:45
  • What does your CommandInterface extend and implement? – Jaybird Dec 13 '18 at 08:45
  • 2
    Evidently the event's source is not an instance of `CommandInterface`. Do you have any reason for thinking it should be? – khelwood Dec 13 '18 at 08:46
  • Does JButton implement your interface, no of course not. You probably need a custom class that implements your interface and that can be instantiated with or assigned a JButton or ActioEvent or whatever it is you want to work with in `processEvent` – Joakim Danielson Dec 13 '18 at 08:50
  • Possible duplicate of [Explanation of "ClassCastException" in Java](https://stackoverflow.com/questions/907360/explanation-of-classcastexception-in-java) – rghome Dec 13 '18 at 09:14

1 Answers1

1

ActionEvent.getSource()returns a javax.swing.jButton. Run time object type of e.getSource i.e javax.swing.jButton must be either same or derived type of CommandInterface otherwise JVM will throw ClassCastException at runtime, read about Object Type Casting.

raviraja
  • 676
  • 10
  • 27