Write your own panel class that extends JPanel
. Add a new method to this class called isOnTheScreen()
, which returns a boolean value indicating whether the panel is added to the window or not.
public class MyPanel extends JPanel { boolean isAdded = false; public boolean isOnTheScreen() { return isAdded; } public void setOnTheScreen(boolean isAdded) { this.isAdded = isAdded; } }
After creating your own panel objects, use the above methods to find out if the panel is added to the main panel / frame or not. Suppose you add a panel to the frame:
JFrame frame = new JFrame() MyPanel panel = new MyPanel(); frame.getContentPane().add(panel); panel.setOnTheScreen(true);
As soon as you add it to the main screen, in this case the frame call setOnTheScreen(true)
And likewise call setOnTheScreen(false)
when the panel is removed.
After this design, you can determine whether the panel is added to the main window or not, simply by clicking isOnTheScreen()
somewhere else in your code. Hope this design helps you.
source share