Reputation: 29518
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:
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();
Upvotes: 0
Views: 711
Reputation: 324167
I'm making a custom button in Java that has two states, mousePressed, and mouseReleased
Maybe you should be using a JToggleButton.
Upvotes: 0
Reputation: 68907
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
}
Upvotes: 1