1

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                   
}
4

2 回答 2

3

switch-case的不正确。您的案例字符串错误,并且您缺少 break 语句。

您添加的项目是

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

而在 switch 案例中,您正在比较

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

其次,我认为部分问题是您获取所选字符串的方式。尝试改用此方法:

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;
    }
}

我希望这有帮助。问题的原因可能是当您更改组合框中的项目时,项目选择更改事件被触发两次。首先,对于取消选择的项目,然后对于选定的项目。

如您所见,我添加了println()fortest和 newselectedString变量。现在,如果您当前的选择是“项目 1”并且您选择了“项目 3”,那么ItemEvent将触发两个,test在这两种情况下的值将不同,因为它指的是不同的项目,而选定的项目将是相同的,正如你可能想要的那样。

PS:这就是为什么你需要 break 语句。当你写:

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

成功时发生case 1的情况是,它下面的所有情况都不会被检查,将按顺序执行。因此,所有doOne(),doTwo()doThree()都将被执行。

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

这样做是每当案例成功并执行其相应的代码时,break将终止switch-case从而仅执行您要执行的代码。

为避免这种情况,您需要使用 break 语句:

另外,这是我拥有的代码

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);
            }
        });
    }
}
于 2013-03-05T19:07:29.693 回答
0

如果您使用if ...else而不是switch Statement那么它更容易编码并且如果您是java语言的新手也可以理解。

只需在jComboBox事件中尝试此代码

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);
        }
    }

创建PanelChange()的原因是,在选择“项目1”时, 项目1”是 第一次,而根据您的语句,则不可见jpanel ,因为您必须在构造函数中复制此方法,例如:

public UIFrame() {
        initComponents();
        PanelChange();
    }
于 2013-03-06T06:07:36.233 回答