2014-10-16 16 views
1

我正在從jpane的jlist中動態添加值。 當我雙擊jlist的一個元素時,我想改變該元素的值。如何在jpane對話框中更改jlist元素的值

如何做到這一點?

String bigList[] = new String[2]; 
bigList[0] = "first value"; 
bigList[1] = "second value"; 

final JList list = new JList(bigList); 

list.addMouseListener(new MouseAdapter() { 
    public void mouseClicked(MouseEvent e) { 
     if (e.getClickCount() == 2) { 
      int index = list.locationToIndex(e.getPoint()); 
      System.out.println("Double clicked on Item " + index); 

      ??????? CHANGEVALUE(index,"MY NEW VALUE); ???????? 
     } 
    } 
}); 
JOptionPane jpane = new JOptionPane(); 
jpane.showMessageDialog(null, list, "MYTITLE", JOptionPane.PLAIN_MESSAGE); 

回答

2

您可以使用DefaultListModel來實現此目的。 DefaultListModel有方法setElementAt("value " ,index)。使用這種方法你可以改變雙擊項目的值。

加入這一行

d.setElementAt("MY NEW VALUE", index); 

會給你期望的結果。

DefaultListModel d = new DefaultListModel(); 
d.addElement("first value"); 
d.addElement("second value"); 

final JList list = new JList(d); 

list.addMouseListener(new MouseAdapter() { 
    public void mouseClicked(MouseEvent e) { 
     if (e.getClickCount() == 2) { 
      int index = list.locationToIndex(e.getPoint()); 
      System.out.println("Double clicked on Item " + index); 

      //??????? CHANGEVALUE(index,"MY NEW VALUE); ???????? 
      d.setElementAt("MY NEW VALUE", index); 
     } 
    } 
}); 
JOptionPane jpane = new JOptionPane(); 
jpane.showMessageDialog(null, list, "MYTITLE", JOptionPane.PLAIN_MESSAGE); 
+1

太棒了!非常感謝你。完全是我搜索的。 – 2014-10-16 15:57:20

相關問題