清爽的java数组成的jList [英] java refreshing an array into jList

查看:123
本文介绍了清爽的java数组成的jList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

行,所以我有一个JList和内容提供了一个数组。我知道如何将元素添加到一个数组,但我想知道如何刷新一个JList,......还是甚至可能吗?我尝试谷歌。 :\\

OK so I have a JList and the content is provided with an array. I know how to add elements to an array but I want to know how to refresh a JList... or is it even possible? I tried Google. :\

import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class bs extends JApplet implements MouseListener {

public static String newline;
public static JList list;

    public void init() {



             String[] data = {"one", "two", "three", "four"};
              list = new JList(data);



        this.getContentPane().add(list);

        list.addMouseListener(this);

        String newline = "\n";

        list.setVisible(true);

    }

    public void refresh(){
        Address found;
        this.listModel.clear();

        int numItems = this.getAddressBookSize();
        String[] a = new String[numItems];
        for (int i=0;i<numItems;i++){
            found = (Address)Addresses.get(i);
            a[i] = found.getName();
        }
        /* attempt to sort the array */
        Arrays.sort(a, String.CASE_INSENSITIVE_ORDER);
        for (int i=0;i<numItems;i++) {
            this.listModel.addElement(a[i]);
        }
    }



    public void mousePressed(MouseEvent e) { }

    public void mouseReleased(MouseEvent e) {
        Object index = list.getSelectedValue();
       System.out.println("You clicked on: " + index);
    }

    public void mouseEntered(MouseEvent e) { }

    public void mouseExited(MouseEvent e) { }

    public void mouseClicked(MouseEvent e) { }




    public void paint(Graphics g) {

    }
}

任何想法?

感谢您。

推荐答案

一个很好的方法是创建一个ListModel的管理为您的数据和处理更新。

One good approach is to create a ListModel to manage the data for you and handle updates.

是这样的:

DefaultListModel listModel=new DefaultListModel();
for (int i=0; i<data.length; i++) {
  listModel.addElement(data[i]);
}
list=new JList(listModel);

然后,你可以简单地通过列表模型的变化如

Then you can simply make changes via the list model e.g.

listModel.addElement("New item");
listModel.removeElementAt(1); // remove the element at position 1

这篇关于清爽的java数组成的jList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆