How to recognize the Java component displayed on the screen

I want to find out if there is a JPanel on the screen or not. This does not mean that the isVisible() method can be used for this situation. I want to say that I want to find out if the component that was initiated earlier is currently one of the components in my main panel or not.

Change and more explanation. I have several panels that were initiated earlier in my program, and use them in my form as needed. I want to know, for example, jpanel1 currently on any of the panels that are now in my form.

Example:

 public class GUI extends JFrame() { private JPanel1, jPanel2; public static void main(String[] args) { GUI gui = new GUI(); jPanel1 = new JPanel(); jPanel2 = new JPanel(); gui.setContentpane(jPanel1); gui.setVisible(true); } } 

jpanel1 is now displayed on the screen bu jPanel2 not displayed. How can I find out?

+6
source share
4 answers

After research, it turns out that this method shows whether the component is displayed on the screen or not:

isDisplayable ()

in my example:

jPanel1.isDisplayable() // returns true

jPanel2.isDisplayable() // returns false

as simple as that!

+10
source

jPanel1.isVisible()==true jPanel1.isVisible()==false

for jPanel1.isShowing() panel also works

+4
source

If you are looking for children on the main panel, you can call getComponents() on the main toolbar to return an array of its components, and then go through them to check whether any of them bar you're looking for, you may have to call this is recursive if the panel is not a direct child of the main panel.

0
source

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.

0
source

Source: https://habr.com/ru/post/910172/


All Articles