简体   繁体   中英

How to setVisible(true or false) multiple components with single statement

I am making Store inventory App using netbeans JFrame. In there I have used almost 50+jLabels. what I want to do is when some one click the button, all components within the button action should be setVisible true or False. I have to write multiple lines to do that, which makes my code looks complex.

I want that code in very short lines. Is there any way to do so? I have multiple MouseClicked events. Here is the sample code:

private void jLabel15MouseClicked(java.awt.event.MouseEvent evt) {                                      

    jScrollPane1.setVisible(true);
    jLabel42.setVisible(false);
    jLabel43.setVisible(false);
    jLabel44.setVisible(false);      
    jLabel48.setVisible(false);
    jLabel40.setVisible(false);
    jLabel20.setVisible(false);
    jLabel19.setVisible(false);
    jLabel18.setVisible(false);
    jLabel17.setVisible(false);
    jLabel22.setVisible(false);
    jLabel21.setVisible(true);
    jLabel37.setVisible(false);
    jLabel38.setVisible(false);
    jLabel39.setVisible(false);

}                                

Put them into a single container and make the container visible/invisible

Also, you might consider using a CardLayout

one way you can put all lables in array then you can loop throw it and change visibility

create a array of jlabels

JLabel[] labels=new JLabel[]{jLabel1,jLabel2};

then loop and change visibility

private void jLabel15MouseClicked(java.awt.event.MouseEvent evt) {  

    for (JLabel label : labels) {
           label.setVisible(false); // use your logic to set visibility 
    }

}

try this Use SwingUtilities.getWindowAncestor(Component) to find the parent window of the current component. You can then call setVisible on it.

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