I want to add a JPanel in a frame if a certain button is clicked and I don't know how to manage that from an anonymous ActionListener. Here is the code:
public class MyFrame extends JFrame {
JPanel panel;
JButton button;
public MyFrame() {
button = new JButton("Add panel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
panel = new JPanel();
//here I want to add the panel to frame: this.add(panel), but I don't know
//how to write that. In these case "this" refers to ActionListener, not to
//frame, so I want to know what to write instead of "this" in order to
//refer to the frame
}
}
this.add(button);
}
Thank you in advance!
here I want to add the panel to frame: this.add(panel), but I don't know how to write that. In these case "this" refers to ActionListener, not to frame, so I want to know what to write instead of "this" in order to refer to the frame
Instead of this.add(...)
just use add(..)
or you can use MyFrame.this.add(..)
cause using this
in anonymous class means that you are referring to ActionListener
instance.
Actually you may also have to call revalidate()
and repaint()
after you add a component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With