Home  >  Article  >  类库下载  >  java graphical user interface list box

java graphical user interface list box

高洛峰
高洛峰Original
2016-10-20 10:54:352330browse

Java graphical user interface list box

The list box is generated through the Swing component JList, which always occupies a fixed number of rows of space on the screen. If you want to get the selected elements in the list box, just call getSelectedValuesList(), which can generate a string array containing the names of the selected elements. The JList component allows multiple selections; if you hold down the Ctrl key, all clicked elements can be selected; if an element is selected, hold down the Shift key and click another element, then all elements between the two elements are selected; to To remove an element from the selection, hold down the Ctrl key and click on the element.

After initializing the list box, the next step is to add and modify content to the list box. Divided into static operations and dynamic operations.

1. Static operation

Static operation is to add all elements to JList at the same time. After adding, they cannot be modified or deleted, that is, the list box cannot be operated during the execution of the program.

E.g.

package test;

import javax.swing.*;
import java.awt.*;
import static net.mindview.util.SwingConsole.*;

public class ListTest1 extends JFrame{
    private String[] str = {"Monday","Tuesday","Wednesday","Thursday","Friday","Staturday","Sunday"};
    private JList list;public ListTest1()
    {
        list = new JList(str);
        setLayout(new FlowLayout());
        add(list);
    }
    
    public static void main(String[] args)
    {
        run(new ListTest1(),200,100);
    }
}

As in the above example, just add all elements to the JList when initializing it.

Execution result: The list box cannot be operated.

java graphical user interface list box

2. Dynamic operation

By looking at the JList method, you can find that JList is not responsible for the dynamic operation of the list box. All the details of the dynamic operation can be completed in the "list model", that is, the DefaultListModel. Just add the list Just add the model to JList. T DefaultListModel Listmodel = New DefaultListModel ();

Listmodel.addelement (Element1); // Add element

Listmodel.clear (); t index); // Clear specification Position element

E.g.

package test;

import java.awt.*;import java.awt.event.*;import static net.mindview.util.SwingConsole.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ListTest extends JFrame{
    private String[] str = {"Monday","Tuesday","Wednesday","Thursday","Friday","Staturday","Sunday"};
    private JButton button1 = new JButton("Add Item"),
                    button2 = new JButton("Clear Item");
    private JTextArea text = new JTextArea(str.length,20);
    private DefaultListModel listmodel = new DefaultListModel();
    private JList list = new JList(listmodel);
    //将列表模型加入JList,列表模型负责完成动态操作,JList负责创建列表以及许多其它工作(如多重选择)。
    private int count = 0;
    private boolean flag = false;
    
    public ListTest()
    {
        text.setEditable(false);//只是用来显示,不能编辑
        for(int i = 0;i<4;i++)
        {
            listmodel.addElement(str[count++]);
        }
        
        button1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
               if(count<str.length)
               {
                   listmodel.addElement(str[count++]);
               }else
               {
                   button1.setEnabled(flag);
                   flag = true;
               }
            }
        });
        
        button2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                if(count<str.length)
                {
                    count = 0;//列表重新开始添加元素
                    listmodel.clear();//列表元素清除
                    text.setText(null);
                }else
                {
                    count = 0;
                    listmodel.clear();
                    text.setText(null);
                    button1.setEnabled(flag);//启动按钮
                }
            }
        });
        
        list.addListSelectionListener(new ListSelectionListener(){
            @SuppressWarnings("deprecation")
            public void valueChanged(ListSelectionEvent e)
            {
               if(e.getValueIsAdjusting())
                    return;
                //如果检测到事件在更改,则返回true,后面语句不执行;当更改结束后,则返回false,执行后面语句。                for(Object item : list.getSelectedValuesList())
                {
                    text.append(item + "\n");//List型对象转换为Object
                }
                //list调用getSelectedValuesList()方法,产生一个字符串数组,内容为被选中的元素名称
            }
        });
        
        setLayout(new FlowLayout());
        Border border = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.RED);//添加边框
        list.setBorder(border);//设置边框
        text.setBorder(border);
        add(button1);
        add(button2);
        add(new JScrollPane(text));
        add(list);
    }
    
    public static void main(String[] args) 
    {
        run(new ListTest(),250,375);
    }
}

Execution result:

In the above program, the getValueIsAdjusting() method of the event ListSelectionEvent supported by JList and the getSelectedValuesList() method of JList are used in the processing of JList. It is necessary to pay attention to the usage of these two methods.

java graphical user interface list box(1)Boolean javax.swing.event.ListSelectionEvent.getValueIsAdjusting()

Returns whether this event is one of multiple different events that are still changing. If this event is one of multiple different events that are still changing, then returns true.

For example, for an event where the selection is updated in response to a user drag, this property is set to true when the drag begins and to false when the drag ends. During dragging, the listener receives events with the valueIsAdjusting property set to true. At the end of the drag, when the change terminates, the listener receives an event with the value set to false .

If the JList object registration program removes the update detection statement:

if(e.getValueIsAdjusting())    return;

The output is:

It can be seen that there is no update detection, and there is repeated output after selecting the list box element.

java graphical user interface list box

(2)List javax.swing.JList.getSelectedValuesList()

The JList object calls the getSelectedValuesList() method to generate a string array whose content is the name of the selected element.

3. JList scroll bar

JList does not provide direct support for scrolling. We only need to wrap JList into JScrollPane and it will automatically help handle all the details.

Summary: If you want to add elements to JList, you can perform the static operation of adding all elements when JList is initialized, or you can use the "list model" DefaultListModel to handle the dynamic operation of all list modification details.

Note: Update detection may be used during the JList element selection process to ensure the stability of the program.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn