简体   繁体   English

在JList中添加和删除按钮

[英]Adding and Removing a Button in JList

I want to add/remove buttons in JList . 我想在JList添加/删除按钮。 How can I do so? 我该怎么办?

另外,考虑如何使用按钮友好的JToolBar ,如如何使用工具栏所示

@rohit I wonder here, what would you need them in a JList? @rohit我想知道,您在JList中需要什么? If you want to lay them out vertically you should use some layout manager, eg BoxLayout or (better) GridLayout. 如果要垂直放置它们,则应使用一些布局管理器,例如BoxLayout或(更好的)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. 确实没有理由在JList中具有按钮,而将它们放在面板中将具有相同的结果。

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: 查看有关如何使用列表的Oracle Swing教程:

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

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. 如果要添加JButton,请将其添加到列表中。 If want to remove, remove it from the list and run the method again. 如果要删除,请从列表中将其删除,然后再次运行该方法。

JList.addElement()和JList.removeElement可用于在JList中添加和删除元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM