Problem with reusing the JScrollPane again for different custom Lists

前端 未结 2 1949
你的背包
你的背包 2020-12-22 02:03

I am trying to create a JScrollPane component which can be reused depending upon the string parameter that is being passed.. I have created the following code, it works if I

相关标签:
2条回答
  • 2020-12-22 03:04

    @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();
                }
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-22 03:06

    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.

    0 讨论(0)
提交回复
热议问题