I'm creating custom popup menu, using just extended JComponent
as a menu items and extended JWindow
to hold them. My question is - how to send signal from JComponent
instance when it's clicked (has MouseListener
) to JTextField
to perform cut/copy/paste actions?
EDIT:
I will try to explain more precisely.
JTextField class (simplified):
public class TextInputField extends JTextField implements FocusListener {
private MenuPopupWindow popUp;
public TextInputField() {
popUp = new MenuPopupWindow();//MenuPopupWindow class extends JWindow
MenuItem paste = new MenuItem("Paste",
new ImageIcon(getClass().getResource("/images/paste_icon.png")),
"Ctrl+V");//MenuItem class extends JComponent, has implemented MouseListener - and when mouseClicked(MouseEvent e) occurs, somehow action signal have to be sent to this class
MenuItem copy = ....
MenuItem cut = ....
Action pasteAction = getActionMap().get(DefaultEditorKit.pasteAction);
paste.setAction(pasteAction);//How to make it to work?
popUp.addMenuItem(paste);
popUp.addMenuItem(cut);
popUp.addMenuItem(copy);
}
}
How to do it right?
In light of your posted code, I think all you need to do in your TextInputField class, is add:
paste.addActionListener(pasteAction);
then in your MenuItem class you have to put in code to call those action listeners.
public class MenuItem implements MouseListener
{
...
@Override public void mouseClicked(MouseEvent event)
{
ActionListener[] listeners = (ActionListener[])
MenuItem.this.getListeners(ActionListener.class);
for(int i = 0; i < listeners.length; i++)
{
listeners[i].actionPerformed
(
new ActionEvent(MenuItem.this,someID, someCMDName)
);
}
}
In your class that extends JComponent (I'll call it class 'A') you will need to get a reference to your JTextField. A simple way to do this is to add a private instance variable of type JTextField to class A, and pass in the JTextField through the constructor.
so your class should look something like this:
public class A extends JComponent implements ActionListener
{
private JTextField updateField;
public A(JTextField updateField[,<your other contructor arguments>...])
{
this.updateField = updateField;
this.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource().equals(this)
{
//copy, paste or do whatever with the JTextField
//by way of this.updateField;
//e.g. this.updateField.setText(...);
//or to simply pass the event along to the JTextField's handlers
//this.updateField.dispatchEvent(event);
}
}
}
then you just have to remember to pass the jtextField into the constructor when you create your component