JPanel#setVisible not working.



我在使用Netbeans的JPanel的可见性问题;我举了一个简单的例子来说明会发生什么。Netbeans创建代码时,我设计的组合和面板->,直到"私有void TheFrame(java.awt.event.)"。WindowEvent evt)"。

在框架的windowActivated中,我放置了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                   
}

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

我希望这对你有帮助。问题的原因可能是,当更改组合框中的项时,会触发两次项选择更改事件。首先是未选中的项,然后是选中的项。

您可以看到,我已经为test和新的selectedString变量添加了println()。现在,如果你当前选择的是"Item 1",而你选择了"Item 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;
}

这样做的目的是,每当一个case成功并且相应的代码被执行时,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);
            }
        });
    }
}

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

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);
        }
    }
创建PanelChange()的原因是,在第一次"Item 1"是一个选定的项目,根据你的语句,当"Item 1"被选中时,jPanel是不可见的,你必须在构造函数中复制这个方法,如:
public UIFrame() {
        initComponents();
        PanelChange();
    }

相关内容

  • 没有找到相关文章

最新更新