2013-05-31 80 views
0

我有一個有三個狀態(三個項目,從0到2)的jcmbobox的jframe。在jcombobox中選擇一個項目時顯示jlabel

我想當用戶選擇第二項(1)我的jlabel應顯示!

但現在,當我選擇第二項,不要顯示它!在我的IDE菜單

public class LoginFrame extends javax.swing.JFrame { 


public LoginFrame() { 
    initComponents(); 
    this.setTitle("Library Management System Login"); 
    this.setLocation(300, 50); 
    this.setResizable(false); 
    if (jComboBox1.getSelectedIndex() == 1) { 
     jLabel4.setVisible(true); 
    } 
    else{ 
     jLabel4.setVisible(false); 
    } 
} 

我選擇的索引號爲0

+0

RTFM:http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html – keuleJ

回答

3

在構造不會反映JComboBox選擇的項目所做的更改任何代碼。你需要使用一個ListenerActionListener來檢測這些變化:

jComboBox1.addActionListener(new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     jLabel4.setVisible(jComboBox1.getSelectedIndex() == 1); 
    } 
}); 

旁白:略有改善可以通過使本聲明setVisible聲明中直接使用的比較式如圖所示進行。

Handling Events on a Combo Box

0

您應該使用ActionListener做到這一點:

jComboBox1.addActionListener(this); 
... 
jLabel4.setVisible(jComboBox1.getSelectedIndex() == 1); 
相關問題