I want to call outer class' method getContentPane() from inner Action class. I don't understand why my code doesn't work.
public class MainFrame extends JFrame {
public MainFrame() {
super("My app");
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu myMenu = new JMenu("File");
menuBar.add(myMenu);
Action myAction = new AbstractAction("Do everything") {
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
panel.setBackground(Color.CYAN);
getContentPane().add(panel, BorderLayout.CENTER);
}
};
myMenu.add(myAction);
}
}
You must call validate();
method after getContentPane().add(...);
.
The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.