2016-10-23 39 views
1

我想讓用戶從列表中選擇,並且用戶選擇的任何選項應顯示在文本區域中,但我在實現該選項時遇到困難!我不斷收到錯誤:無與倫比的類型:int和字符串

我也不斷收到一個錯誤,說不能容忍的類型:intstring

import java.awt.*; 
    import java.awt.event.*; 
    import javax.swing.*; 
    import javax.swing.event.*; 
    import javax.swing.event.ListSelectionListener; 

    public class Lab4Part3 extends JFrame implements ListSelectionListener { 

    JList<String> list; 

     public Lab4Part3() { 

      JPanel panel = new JPanel(); 

      Container c = getContentPane(); 

      JPanel panel1 = new JPanel(); 

      JLabel new1Label = new JLabel ("Choose your fav subject"); 
    //create a list with 10 choices 
      String choices [] = {"GUI", "Maths", "Database", "Object Oriented", "Web Dev", "Networks", "Switching", "Routing", "accounting", "finance",}; 

      list = new JList<String>(choices); 
      list.addListSelectionListener(this); 
      JScrollPane pane = new JScrollPane(list); 
      panel1.add(new1Label); 
      panel1.add(list); 

      JPanel panel2 = new JPanel(); 
      JTextArea ta = new JTextArea(); 
      ta.setText("Response will appear here"); 
      panel2.add(ta); 

      c.add(panel1, BorderLayout.NORTH); 
      c.add(panel2, BorderLayout.SOUTH); 

      setSize(400,300); 
      setVisible(true); 


     } 

      public static void main (String args []) { 


      Lab4Part3 myFrame = new Lab4Part3(); 
     myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


     } 


    public void valueChanged(ListSelectionEvent e) { 


    if (list.getSelectedIndex()==("GUI")) { 


      ta.setText("GUI"); 
    } 

    } 
    } 

回答

0
if (list.getSelectedIndex()==("GUI")) { 

應由

if (list.getSelectedIndex()==0) { 

"GUI"以來被替換是在你的choices陣列的第一個值。

更清晰的方法是使用Map<Integer,String>,您可以將選擇的索引與String值相關聯。
通過這種方式,如果選擇順序在您的UI中發生變化,那麼偵聽器在其處理中保持有效。

+0

謝謝你的工作! –

+0

大:)隨時接受答案:) – davidxxx

相關問題