简体   繁体   中英

Access an extended JPanel from a listener in another class

I would like to access an extended JPanel from a listener in another class, in order to re-size that panel when the button is clicked.

I tried to access it using Buttons.this.setPreferredSize ...., but i got this error

No enclosing instance of the type Buttons is accessible in scope

My Buttons class looks like this

public class Buttons extends JPanel {
    public Buttons() {

    //code

    }
}

and the other from where i want to change the size of the Panel

public class InterfaceCalc extends JPanel {
    // others codes 
    expandIcon = new ImageIcon("src\\img\\expand.png");
    expand = new JButton("", expandIcon);
    expand.setBorderPainted(false);
    expand.setContentAreaFilled(false);
    expand.setFocusPainted(false);
    expand.setOpaque(false);
    expand.setMargin(new Insets(0, 0, 0, 0));
    expand.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (!on) {
                Buttons.sqrt.setVisible(true);
                Buttons.log.setVisible(true);
                Buttons.cos.setVisible(true);
                Buttons.sin.setVisible(true);
                // this is where is want to access the panel
                Buttons.this.setPreferredSize(new Dimension());

                on = true;

            } else {
                Buttons.sqrt.setVisible(false);
                Buttons.log.setVisible(false);
                Buttons.cos.setVisible(false);
                Buttons.sin.setVisible(false);

                on = false;

            }

        }

    });
  // others codes 
}

How can achieve that ?

I fixed the problem by creating an instance of Buttons outside the listener. before ,the extended panel was added directly like this in this.add(new Buttons()) in theInterfaceCalc panel, now after i created the instance I added it to the panel and i used it to change the size.

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