user1122027
user1122027

Reputation: 41

JList wrap issue

When I add elements to it during run time, it seems to not update the wrap properly. When the frame is revalidated, it will continue to render new items on the last line (even keeping old wrapped lines), but it will not continue and wrap to a new line.

The list can only be re-wrapped when the frame is re-sized (invalidating, validating and repainting do not work).

    final JFrame frame = new JFrame();
    final Vector<String> strings = new Vector<String>();
    JList list = new JList(strings);

    list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    list.setVisibleRowCount(-1);

    strings.add(" ------------------ add ------------------");
    strings.add(" ------------------ add ------------------");

    JButton button = new JButton("add");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            strings.add(" ------------------ add ------------------");
            //frame.invalidate();
            //frame.validate();
            //frame.repaint();
        }
    });

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(list, BorderLayout.CENTER);
    panel.add(button,BorderLayout.SOUTH);

    frame.setSize(400,400);
    frame.add(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

Upvotes: 3

Views: 380

Answers (1)

dacwe
dacwe

Reputation: 43504

Use a ListModel, for example DefaultListModel. It will fire the "fire" the correct events to the JList so that it updates when objects are added to or removed from the model.

public static void main(String[] args) {

    JFrame frame = new JFrame("Test");

    final DefaultListModel model = new DefaultListModel();

    model.addElement("---added---");
    model.addElement("---added---");

    frame.add(new JList(model), BorderLayout.CENTER);
    frame.add(new JButton(new AbstractAction("Add") {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            model.addElement("---added again---");
        }
    }), BorderLayout.SOUTH);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 150);
    frame.setVisible(true);
}

For the "wrap problem" just use the JList(ListModel) constructor it will use the JList.VERTICAL property that renders the list like you want.

Upvotes: 3

Related Questions