Problem with reusing the JScrollPane again for different custom Lists

﹥>﹥吖頭↗ 提交于 2019-11-29 16:40:26

@camickr is correct; JPanel is a better "general-purpose container for lightweight components." You can add additional components to the other areas of the BorderLayout used in the example below. It's also a good habit to build your GUI on the event dispatch thread.

import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.event.*;

/** @see http://stackoverflow.com/questions/4176343 */
public class ListPanel extends JPanel {

    private JList list;

    public ListPanel(String[] data) {
        super(new BorderLayout());
        list = new JList(data);
        list.addListSelectionListener(new SelectionHandler());
        JScrollPane jsp = new JScrollPane(list);
        this.add(jsp, BorderLayout.CENTER);
    }

    private class SelectionHandler implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                System.out.println(Arrays.toString(list.getSelectedValues()));
            }
        }
    }

    private void display() {
        JFrame f = new JFrame("ListPanel");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                String[] data = {"Math", "Computer", "Physics", "Chemistry"};
                new ListPanel(data).display();
            }
        });
    }
}

public class ListComponent extends JScrollPane

What? You should not be extending a JScrollPane. You are not adding new functionality to the scroll pane.

If you are trying to add a JList to a JScrollPane, then I suggest you read the JList API and follow the link to the Swing tutorial on "How to Use Lists" for a working example.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!