2013-03-11 21 views
0

我已經放在一起一個小的用戶界面小部件,但其上的刪除按鈕不起作用。每當我點擊它,什麼都不會發生。有任何想法嗎?刪除方法不適用於自定義用戶界面小部件

public class ComboBoxProblem extends JFrame { 
    static JLabel citiesLabel = new JLabel(); 
    static JList citiesList = new JList(); 
    static JScrollPane citiesScrollPane = new JScrollPane(); 
    static JButton remove = new JButton(); 

    public static void main(String[] args) { 
     new ComboBoxProblem().show(); 
    } 

    public ComboBoxProblem() { 
     // create frame 
     setTitle("Flight Planner"); 
     setResizable(false); 

     getContentPane().setLayout(new GridBagLayout()); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     GridBagConstraints gridConstraints; 
     citiesLabel.setText("Destination City"); 
     gridConstraints = new GridBagConstraints(); 
     gridConstraints.gridx = 0; 
     gridConstraints.gridy = 0; 
     gridConstraints.insets = new Insets(10, 0, 0, 0); 
     getContentPane().add(citiesLabel, gridConstraints); 
     citiesScrollPane.setPreferredSize(new Dimension(150, 100)); 
     citiesScrollPane.setViewportView(citiesList); 
     gridConstraints = new GridBagConstraints(); 
     gridConstraints.gridx = 0; 
     gridConstraints.gridy = 1; 
     gridConstraints.insets = new Insets(10, 10, 10, 10); 
     getContentPane().add(citiesScrollPane, gridConstraints); 

     // Here is my list with my elements, that I want to remove 

     final DefaultListModel Model = new DefaultListModel(); 
     Model.addElement("San Diego"); 
     Model.addElement("Los Angeles"); 
     Model.addElement("Orange County"); 
     Model.addElement("Ontario"); 
     Model.addElement("Bakersfield"); 
     Model.addElement("Oakland"); 
     Model.addElement("Sacramento"); 
     Model.addElement("San Jose"); 

     citiesList.setModel(Model); 

     final JList list = new JList(Model); 

     remove.setText("Remove"); 
     gridConstraints = new GridBagConstraints(); 
     gridConstraints.gridx = 0; 
     gridConstraints.gridy = 3; 
     getContentPane().add(remove, gridConstraints); 

     // Here is my removing method, I don't know, where the problem is 
     // and it is showing no error 

     remove.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       int sel = list.getSelectedIndex(); 
       if (sel >= 0) { 

        Model.removeElementAt(sel); 
       } 
      } 
     }); 

     pack(); 
    } 
} 
+1

您的活動是否正在開展? – Thihara 2013-03-11 15:30:24

+0

另外....是你的構造函數中的另外兩個片段?它看起來應該是,但這可能是一個重要的細節。 – 2013-03-11 15:35:25

+0

它沒有給我顯示任何東西.. – CRazyProgrammer 2013-03-11 15:48:38

回答

0

替換此行:

int sel = list.getSelectedIndex(); 

通過這一個:

int sel = citiesList.getSelectedIndex(); 

list.getSelectedIndex()總返回-1。

請在將來使用調試以獲取有關代碼中發生的更多信息。