JPanel #setVisible无法正常工作。

时间:2013-03-05 18:53:22

标签: java swing netbeans jpanel

我在使用Netbeans的JPanel的可见性方面遇到了问题;我做了一个简单的例子来告诉你发生了什么。 当我设计组合和面板时,Netbeans会创建代码 - >直到“private void TheFrame(java.awt.event.WindowEvent evt)”。

在窗口中激活了框架我把panelOne(JPanel).setVisible(false)和 这个有效! 从组合中选择一个项目(item2 / item4)后,我希望显示panelOne,但这不起作用。

/**
 *
 * @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                   
}

2 个答案:

答案 0 :(得分:3)

您的switch-case不正确。对于案例你有错误的字符串,你也错过了break语句。

您添加的项目是

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

而在切换案例中,您正在比较

"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()添加了test和新的selectedString变量。现在,如果您当前的选择是“第1项”并选择“第3项”,则会触发两个ItemEventtest的值在两种情况下都会有所不同,因为它引用了不同的项目,而所选项目将是您可能想要的相同。

  

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

答案 1 :(得分: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();
    }