Alpan67
Alpan67

Reputation: 105

JPanel#setVisible not working.

i have problems in the visibility of JPanel using Netbeans; i made a simple example to show you what happens. Netbeans creates the code when i design the combo and the panel -> until "private void TheFrame(java.awt.event.WindowEvent evt)".

In the windowActivated of the frame i put the panelOne(JPanel).setVisible(false) and this works ! After chosing an item(item2/item4) from the combo i would like the panelOne to be shown but this does not work.

/**
 *
 * @author Alessandro
 */
public class UIFrame extends javax.swing.JFrame {

    /**
     * Creates new form UIFrame
     */
    public UIFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        panelOne = new javax.swing.JPanel();
        comboBox = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                TheFrame(evt);
            }
        });

        javax.swing.GroupLayout panelOneLayout = new javax.swing.GroupLayout(panelOne);
        panelOne.setLayout(panelOneLayout);
        panelOneLayout.setHorizontalGroup(
            panelOneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 349, Short.MAX_VALUE)
        );
        panelOneLayout.setVerticalGroup(
            panelOneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 52, Short.MAX_VALUE)
        );

        comboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                ItemListener(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(panelOne, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(122, 122, 122)
                        .addComponent(comboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(comboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addComponent(panelOne, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(175, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void TheFrame(java.awt.event.WindowEvent evt) {                          
        panelOne.setVisible(false);
    }                         

    private void ItemListener(java.awt.event.ItemEvent evt) {                              
        String test = (String)(evt.getItem());   
        switch (test)
        {
            case "Item1":
                panelOne.setVisible(false);
            case "Item2":
                panelOne.setVisible(true);
            case "Item3":
                panelOne.setVisible(false);
            case "Item4":
                panelOne.setVisible(true);
        }               
    }                             

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UIFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UIFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UIFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UIFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UIFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JComboBox comboBox;
    private javax.swing.JPanel panelOne;
    // End of variables declaration                   
}

Upvotes: 1

Views: 5044

Answers (2)

Rajshri
Rajshri

Reputation: 4153

If you use if ...else rather than switch Statement then it is more easy to code and also understand if you are new in java language.

just try this code at jComboBox event

private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
       PanelChange();
    } 


 private void PanelChange() {
         String test = jComboBox1.getSelectedItem().toString();
        if (test.equals("Item 1") || test.equals("Item 3")) {
            jPanel1.setVisible(false);
        }else{
            jPanel1.setVisible(true);
        }
    }

The reason for creating PanelChange() is that at the first time "Item 1" is a selected item and as per your statements when "Item 1" is selected then jPanel is not visible for that you must copy this method in constructor like :

public UIFrame() {
        initComponents();
        PanelChange();
    }

Upvotes: 0

Ankit
Ankit

Reputation: 6980

Your switch-case is incorrect. You are having wrong strings for cases and also you are missing the break statements.

The items that you have added are

"Item 1", "Item 2", "Item 3" and "Item 4"

whereas in the switch case, you are comparing

"item1", "item2", "item3" and "item4"

Second, I believe part of the problem is the way you are getting the selected string. Try to use this method instead:

private void ItemListener(java.awt.event.ItemEvent evt) {
    String test = (String) (evt.getItem()); //do not use this
    System.out.println(test);

    JComboBox box = (JComboBox)evt.getSource();
    String selectedString = (String) box.getSelectedItem();

    switch (selectedString) { //replaced test with selectedString
    case "Item 1":
        panelOne.setVisible(false); break;
    case "Item 2":
        panelOne.setVisible(true); break;
    case "Item 3":
        panelOne.setVisible(false); break;
    case "Item 4":
        panelOne.setVisible(true); break;
    }
}

I hope this helps. The cause of the problem could be the fact that when you change an item in a combobox, the item selection change event is fired twice. First, for the deselected item and then for the selected item.

As you can see I have added a println() for test and the new selectedString variable. Now, if your current selection is "Item 1" and you select "Item 3", then two ItemEvent will be fired, the value for test will be different in both cases as it refers to different items, whereas the selected item will be the same, as you would probably want.

PS: This is why you need the break statement. When you write:

switch(var){
case 1: doOne();
case 2: doTwo();
case 3: doThree();
}

what happens when case 1 succeeds is that all the cases below it are not checked and will be executed sequentially. So, all of doOne(), doTwo() and doThree() will be executed.

switch(var){
case 1: doOne(); break;
case 2: doTwo(); break;
case 3: doThree(); break;
}

What this does is that whenever a case succeeds and its corresponding code is executed, break will terminate the switch-case thereby executing only the code that you want to execute.

To avoid this, you need to use break statements:

Also, here is the code that I have

import java.awt.BorderLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class UIFrame extends JFrame {
    final private JPanel panelOne = new JPanel();
    private JComboBox comboBox;

    public UIFrame() {
        initComponents();
    }

    private void initComponents() {
        setLayout(new BorderLayout());
        comboBox = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        comboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                ItemListener(evt);
            }
        });
        panelOne.add(new JTextField("Hello"));
        add(comboBox, BorderLayout.CENTER);
        add(panelOne, BorderLayout.NORTH);

    }


    private void ItemListener(java.awt.event.ItemEvent evt) {
        panelOne.setVisible(false);
        String test = (String) (evt.getItem());
        System.out.println(test);

        JComboBox box = (JComboBox)evt.getSource();
        String selectedString = (String) box.getSelectedItem();

        switch (selectedString) {
        case "Item 1":
            panelOne.setVisible(false);
            break;
        case "Item 2":
            panelOne.setVisible(true);
            break;
        case "Item 3":
            panelOne.setVisible(false);
            break;
        case "Item 4":
            panelOne.setVisible(true);
            break;
        }



    }

    public static void main(String[] args) {
        final UIFrame frame = new UIFrame();
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

Upvotes: 3

Related Questions