简体   繁体   中英

How can I use JPopupMenu actionlistener inside a class constructor?

I making a GUI that has a lot of buttons doing the exact same function, so I decided to make a special class of a JButton that does what I want which includes a JPopupMenu in it. However, an error comes with show , getHeight and getWidth that I don't understand: "The method getHeight() is undefined for the type new ActionListener(){} " and "The method getWidth() is undefined for the type new ActionListener(){} ."

NB: I copied the code from the JPopupMenu ; I don't know how it works.

public class MyButton extends JButton {
    
    JPopupMenu menu = new JPopupMenu("Menu");
    //create menu item
    JMenuItem a = new JMenuItem("A");
    JMenuItem b = new JMenuItem("B");
    JMenuItem c = new JMenuItem("C");
    JMenuItem d = new JMenuItem("D");

    public MyButton() {
        super();
        
        menu.add(a);
        menu.add(b);
        menu.add(c);
        menu.add(d);
        
        this.addActionListener(new ActionListener() {
            
            @SuppressWarnings("deprecation")
            public void actionPerformed(ActionEvent ae) {
                menu.show(this, this.getWidth() / 2, this.getHeight() / 2); //here is the error 
            }
        });
    }
}

You are creating an anonymous instance of ActionListener and attempting to access the MyButton to which you adding the listener via this - but this is the ActionListener . You should be able to use the source of the ActionEvent but you'll need to cast it.

JComponent source = (JComponent)ae.getSource();
menu.show(source, source.getWidth()/2, source.getHeight()/2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM