开发者

Adding and Removing a Button in JList

开发者 https://www.devze.com 2023-02-27 19:15 出处:网络
I want to add/remove buttons in JList. How can I do 开发者_高级运维so? Alternatively, consider a button-friendly JToolBar, as shown in How to Use Tool Bars.@rohit I wonder here, what would you need th

I want to add/remove buttons in JList. How can I do 开发者_高级运维so?


Alternatively, consider a button-friendly JToolBar, as shown in How to Use Tool Bars.


@rohit I wonder here, what would you need them in a JList? If you want to lay them out vertically you should use some layout manager, e.g. BoxLayout or (better) GridLayout.

There is really no reason why you should have buttons in a JList, where having them in a panel will have the same result.

Seriously try to reconsider your design and go with a more flexible and easier one which uses a layout manager.

All the best, Boro.


Take a look at the Oracle Swing tutorial about how to use lists:

http://download.oracle.com/javase/tutorial/uiswing/components/list.html


JList.addElement() and JList.removeElement can be used to add en remove elements to and from JLists.


I Used this code. try it

class PanelRenderer implements ListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        JButton renderer = (JButton) value;
        renderer.setBackground(isSelected ? Color.red : list.getBackground());
        return renderer;
    }
}

public void ShowItemList(List<JButton> buttonList, JPanel container) {


        DefaultListModel model = new DefaultListModel();

        for (JButton b:buttonList) {

                model.addElement(b);

        }
        final JList list = new JList(model);
        list.setFixedCellHeight(40);
        list.setSelectedIndex(-1);

        list.setCellRenderer(new JPanelToJList.PanelRenderer());
        JScrollPane scroll1 = new JScrollPane(list);
        final JScrollBar scrollBar = scroll1.getVerticalScrollBar();
        scrollBar.addAdjustmentListener(new AdjustmentListener() {
            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
                System.out.println("JScrollBar's current value = " + scrollBar.getValue());
            }
        });
        container.removeAll();
        container.add(scroll1);
}

If you want to add a JButton add it to the list. If want to remove, remove it from the list and run the method again.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号