2012-04-27 54 views
1

我有一个包含JList的面板。 当我将这个面板添加到西部BorderLayout与一个元素一切都OK,我看到它的一个元素,但如果我添加新元素或清除所有元素,我看不到任何效果。为什么JList不显示新添加的元素?

任何机构能提出任何解决方案吗?

到FtpPanel将被添加含有的JList

public class FtpPanel extends JPanel{ 
public JList ftpJList; 
public DefaultListModel ftpListModel; 

public FtpPanel(String[] list) { 
    this.setLayout(new BorderLayout()); 
    this.setBorder(new EmptyBorder(20, 20, 20, 20)); 
    this.ftpListModel = new DefaultListModel(); 
    for(String s : list){ 
     this.ftpListModel.addElement(s); 
    } 
    this.ftpJList = new JList(ftpListModel); 
    final JScrollPane wsp = new JScrollPane(this.ftpJList); 
    wsp.setBorder(new TitledBorder(new WebBorder(),"ftpsrv.itra.de")); 
    this.add(wsp, BorderLayout.CENTER); 
} 

}

FtpTabPanel JPanel类

public class FtpTabPanel extends JPanel{ 
public FtpPanel ftpPanel; 
public FtpTabPanel() { 
    createComponents(); 
    layoutComponents(); 
    initializeComponents(); 
} 

private void createComponents() { 
    ftpPanel = new FtpPanel(new String[]{"You aren't Connected"}); 
} 
private void layoutComponents() { 
    setLayout(new BorderLayout()); 
    add(ftpPanel, BorderLayout.WEST); 
} 

}

中添加和删除的jList

addFileToJlist(listOfFtpFile){ 
    SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       if(listOfFtpFile !=null) 
        ftpTabPanel.ftpPanel.ftpListModel.clear(); 
        ftpTabPanel.ftpPanel.updateUI(); 
        for(String s : listOfFtpFile){ 
         ftpTabPanel.ftpPanel.ftpListModel.addElement(s); 
         ftpTabPanel.ftpPanel.ftpWebList.validate(); 
         ftpTabPanel.ftpPanel.updateUI(); 
        } 
       ftpTabPanel.ftpPanel.ftpWebList.revalidate(); 
       panel.updateUI(); 
      } 
     }); 
} 

回答

3

下面是一个简单的工作示例(即是你的基本相同,但没有不必要的更新):

public static void main (String[] args) 
{ 
    JFrame frame = new JFrame(); 

    final DefaultListModel model = new DefaultListModel(); 

    JList list = new JList (model); 
    frame.add (new JScrollPane (list)); 

    list.addMouseListener (new MouseAdapter() 
    { 
     public void mousePressed (MouseEvent e) 
     { 
      model.clear(); 
      Random random = new Random(); 
      int max = random.nextInt (10); 
      for (int i = 0; i <= max; i++) 
      { 
       model.addElement ("" + random.nextInt (100)); 
      } 
     } 
    }); 

    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
    frame.setSize (200, 400); 
    frame.setLocationRelativeTo (null); 
    frame.setVisible (true); 
} 

而且我实在看不出任何问题在你的例子中(除了不必要的验证和updateUI调用)。似乎这个问题是在别的地方...

+0

*“似乎问题在别的地方”* OP - 为了更好地帮助您,请发布[SSCCE](http://sscce.org/)。 – 2012-04-27 11:30:45

-2

我最近有类似的问题。解决它就像这样:

(添加元素到Jlist) Jlist.setVisible(false); Jlist.setVisible(true);

只有它的方式,我不知道为什么。

+1

-1如果这似乎是一种解决方案,那么您在其他地方正在做一些非常错误的事情(很可能该模型不符合其变更通知合同,或者您正在更改其脚下的基础数据结构) – kleopatra 2013-06-27 09:54:57