views:

104

answers:

3

I'm making a custom button in Java that has two states, mousePressed, and mouseReleased. At the same time, if I wanted to reuse this button, so that other event listeners can register with it, are these the appropriate steps I should do (This is a hw assignment so although a JButton could be used, I think we are trying to show that we can create our own Button to act like JButton:

  • override addActionListener(ActionListener action)
  • override removeActionListener(ActionListener action)
  • have a private variable like List list = new List () to keep track of when events get added and some sort of function with for loop to run all the actions. Here is what I have so far:

    public class CustomButton { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CustomButtonFrame frame = new CustomButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); }

        public void addActionListener(ActionListener al)
        {
            listenerList.add(al);
        }
    
    
    
    public void removeActionListener(ActionListener al)
    {
        listenerList.remove(al);
    }
    
    
    private void notifyListeners()
    {
        for (ActionListener action : listenerList) {
            action.actionPerfomed();
        }
    }
    
    
    List<ActionListener> listenerList = new ArrayList<ActionListener>();
    
    }

I'm getting the compile errors: line 38: reference to List is ambiguous, both class java.util.List in java.util and class java.awt.List in java.awt match List listenerList = new ArrayList();

and line 34: cannot find symbol, method actionPerfomed() in interface java.awt.event.ActionListener action.actionPerformed();

+1  A: 

No, completely not!

A JButton has everything you need. Just add your own listener to the button. Don't override something. Just like this:

public class MyButton extends JButton implements MouseListener // maybe you want to add other listeners... separate them with comma's.
{
     public MyButton(String caption)
     {
         super(caption);
         addMouseListener(this);
     }

     // implement your listener methods here

}
Martijn Courteaux
A: 

Could you explain if you would like to use the same button, or the same mechanizem, on another button in the same application or in another application?

I will add an answer once you elaborate...

TacB0sS
A: 

I'm making a custom button in Java that has two states, mousePressed, and mouseReleased

Maybe you should be using a JToggleButton.

camickr