2014-02-07 21 views
0

我已經使用Netbeans(使用GUI編輯器)向我的GUI添加了一個列表,並添加了三個值:紅色,綠色和藍色。 我想要改變用戶從列表中選擇的圖像的亮度,即如果用戶在列表中選擇綠色,然後按下增加亮度按鈕,則亮度將僅增加綠色圖像。 香港專業教育學院增加了一個列表選擇事件,這裏的操作說明:http://docs.oracle.com/javase/tutorial/uiswing/components/list.htmlGUI中的Java列表

我對事件的代碼如下:

private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {          
     // TODO add your handling code here: 
     jList1.getSelectedIndex(); 
     if (jList1.getSelectedIndex() == 0) { 
      int listInt = 1; 
     } 
     if (jList1.getSelectedIndex() == 1) { 
      int listInt = 2; 
     } 
     if (jList1.getSelectedIndex() == 2) { 
      int listInt = 3; 
     } 
    } 

而且我對亮度按鈕的代碼如下:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {           
     // TODO add your handling code here: 
     System.out.println(listInt); 
     if (listInt == 1) { 
      increaseContrast(redImage); 
      update(redImage, redIcon, redLabel); 
     } 
     if (listInt == 2) { 
      increaseContrast(greenImage); 
      update(greenImage, greenIcon, greenLabel); 
     } 
     if (listInt == 3) { 
      increaseContrast(blueImage); 
      update(blueImage, blueIcon, blueLabel); 
     } 

不管選擇是什麼,總是將0打印到終端,這意味着第一個代碼段不起作用。任何人都可以幫助解釋爲何發生這種情況

+0

不相關,但仍然有用:不要使用GUI構建器。 –

回答

2

因爲您正在聲明和修改jList1ValueChanged方法中的局部變量listInt,該方法在您退出該函數時超出了範圍。當然你想更改一個實例變量,該變量對於jButton2ActionPerformed(可能被稱爲listInt)也是可見的,但只需在那些if語句中設置它的值,而不是聲明具有相同名稱的局部變量。你得到0是因爲這是int的默認初始值(所以listInt)。

+1

你是對的,愚蠢的錯誤,但謝謝你! – user2517280