public abstract class ButtonList

  1. Object
  2. Component
  3. Container
  4. ButtonList

ImplementsActionListener, ActionSource, Animation, DataChangedListener, Editable, Iterable<Component>, SelectionListener, StyleListener

Known subtypesCheckBoxList, RadioButtonList, SwitchList

An abstract base class for a list of buttons. Most useful for grids of toggle widgets such as Radio Buttons, CheckBoxes, and Switches. There are concrete implementations for Switch (SwitchList), RadioButton (RadioButtonList, and CheckBox (CheckBoxList).

This abstraction allows you to work with a set of toggle buttons as a single unit. It uses a ListModel to store the toggle options, and will automatically stay in sync with its model when options are added or removed, or the selection is changed.

package com.codename1.testproj;

import com.codename1.components.CheckBoxList;
import com.codename1.components.RadioButtonList;
import com.codename1.components.SwitchList;
import static com.codename1.ui.CN.*;
import com.codename1.io.Log;
import com.codename1.ui.Button;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.FlowLayout;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.ui.Toolbar;
import com.codename1.ui.Command;
import com.codename1.ui.TextField;
import com.codename1.ui.layouts.GridLayout;
import com.codename1.ui.list.DefaultListModel;
import com.codename1.ui.table.TableLayout;
import java.util.Arrays;

/**
 * This file was generated by [Codename One](https://www.codenameone.com/) for the purpose
 * of building native mobile applications using Java.
 */
public class TestProject {

    private Form current;
    private Resources theme;

    public void init(Object context) {
        // use two network threads instead of one
        updateNetworkThreadCount(2);

        theme = UIManager.initFirstTheme("/theme");

        // Enable Toolbar on all Forms by default
        Toolbar.setGlobalToolbar(true);

        // Pro only feature
        Log.bindCrashProtection(true);

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if(err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });
    }

    public void start() {
        if(current != null){
            current.show();
            return;
        }

        testButtonLists();
    }

    public void testButtonLists() {
        Form hi = new Form("Hi", new BorderLayout());

        SwitchList switchList = new SwitchList(new DefaultListModel("Red", "Green", "Blue", "Indigo"));
        switchList.addActionListener(e->{
            Log.p("Action event received from "+e.getSource());
            Log.p("Selected indices: "+Arrays.toString(switchList.getMultiListModel().getSelectedIndices()));
        });

        Button clearSelections = new Button("Clear");
        clearSelections.addActionListener(e -> {
            switchList.getMultiListModel().setSelectedIndices();
        });

        Button addOption = new Button("Add Option");
        addOption.addActionListener(e -> {
            callSerially(()->{
                TextField val = new TextField();
                Command res = Dialog.show("Enter label", val, new Command("OK"));
                switchList.getMultiListModel().addItem(val.getText());

            });
        });

        RadioButtonList layoutSelector = new RadioButtonList(new DefaultListModel("Flow", "X", "Y", "2-Col Table", "3-Col Table", "2 Col Grid", "3 Col Grid"));
        layoutSelector.addActionListener(e->{
            switch (layoutSelector.getModel().getSelectedIndex()) {
                case 0: switchList.setLayout(new FlowLayout());
                break;
                case 1: switchList.setLayout(BoxLayout.x());
                break;
                case 2: switchList.setLayout(BoxLayout.y());
                break;
                case 3: switchList.setLayout(new TableLayout(switchList.getComponentCount()/2+1, 2));
                break;
                case 4: switchList.setLayout(new TableLayout(switchList.getComponentCount()/3+1, 3));
                break;
                case 5: switchList.setLayout(new GridLayout(2));
                break;
                case 6: switchList.setLayout(new GridLayout(3));
            }
            switchList.animateLayout(300);
        });

        CheckBoxList checkBoxList = new CheckBoxList(switchList.getMultiListModel());
        checkBoxList.addActionListener(e-> {
            System.out.println("CheckBox actionEvent.  "+Arrays.toString(checkBoxList.getMultiListModel().getSelectedIndices()));
        });
        hi.add(BorderLayout.NORTH, layoutSelector);
        hi.add(BorderLayout.CENTER, BoxLayout.encloseY(checkBoxList, switchList));
        hi.add(BorderLayout.SOUTH, GridLayout.encloseIn(2, addOption, clearSelections));
        hi.show();

    }

    public void stop() {
        current = getCurrentForm();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = getCurrentForm();
        }
    }

    public void destroy() {
    }

}

Examples

Switch List in a FlowLayout:

`SwitchList switchList = new SwitchList(new DefaultListModel("Red", "Green", "Blue", "Indigo"));
switchList.setLayout(new FlowLayout());`

Switch List in a BoxLayout.Y:

`SwitchList switchList = new SwitchList(new DefaultListModel("Red", "Green", "Blue", "Indigo"));
switchList.setLayout(BoxLayout.y());`

Switch List in a Grid Layout:

Switch List in a Table Layout:

2 Columns:

`SwitchList switchList = new SwitchList(new DefaultListModel("Red", "Green", "Blue", "Indigo"));
switchList.setLayout(new TableLayout(switchList.getComponentCount()/2+1, 2));`

3 Columns:

`SwitchList switchList = new SwitchList(new DefaultListModel("Red", "Green", "Blue", "Indigo"));
switchList.setLayout(new TableLayout(switchList.getComponentCount()/3+1, 3));`

Nested types

interface ButtonList.DecoratorAn interface that can be implemented to provide custom decoration/undecoration of the buttons as they are created/removed.

Fields

protected boolean ready

Constructors

protected ButtonList(ListModel model, boolean allowMultipleSelection)Creates a new ButtonList.

Methods

protected void onReady(Runnable r)Wrap any calls that requires that the infrastructure is ready inside this.
protected final void fireReady()This should be called by the concrete implementation once it is ready to generate the buttons.
public MultipleSelectionListModel getMultiListModel()For multi-selection models (e.g. for checkbox or switch lists), this will return the model as a MultiSelectionListModel.
public ListModel getModel()Returns the model.
public final void setModel(ListModel model)
protected abstract Component createButton(Object model)Creates a new button for this list.
protected abstract void setSelected(Component button, boolean selected)Sets the given button’s selected state.
public void setLayout(Layout layout)Sets the layout for the list.
public void refresh()Refreshes the container - regenerating all of the buttons in the list from the model.
protected Component decorateComponent(Object modelItem, Component b)Decorates buttons.
protected Component undecorateComponent(Component b)Undecorates buttons.
public void dataChanged(int status, int index)Invoked when there was a change in the underlying model
public void selectionChanged(int oldSelected, int newSelected)Indicates the selection changed in the underlying list model
public void actionPerformed(ActionEvent evt)Invoked when an action occurred on a component
public void addActionListener(ActionListener l)Add a listener to be notified when any of the buttons in the list are pressed.
public void removeActionListener(ActionListener l)Remove a listener so that it no longer is notified when buttons in the list are pressed.
public void setCellUIID(String uiid)Sets the UIID for cells of the list.
public void addDecorator(ButtonList.Decorator decorator)Adds a decorator that can be used to customize a button when it is created
public void removeDecorator(ButtonList.Decorator decorator)Removes a decorator.

Inherited fields

Inherited methods

From Container

encloseIn, encloseIn, initLaf, getUIManager, setUIManager, isSurface, add, addAll, add, add, add, add, add, getLeadComponent, setLeadComponent, getLeadParent, keyPressed, keyReleased, getLayout, invalidate, setShouldLayout, setShouldCalcPreferredSize, getLayoutWidth, getLayoutHeight, applyRTL, constrainWidthWhenScrollable, constrainHeightWhenScrollable, addComponent, addComponent, addComponent, addComponent, replaceAndWait, replaceAndWait, replace, replaceAndWait, replace, createReplaceTransition, isEnabled, setEnabled, removeComponent, cancelRepaints, flushReplace, removeAll, revalidateWithAnimationSafety, revalidate, revalidateLater, forceRevalidate, clearClientProperties, paint, paintGlass, layoutContainer, isSafeArea, setSafeArea, isSafeAreaRoot, getSafeAreaRoot, setSafeAreaRoot, getComponentCount, getComponentAt, getComponentIndex, contains, scrollComponentToVisible, getClosestComponentTo, getResponderAt, getComponentAt, findDropTargetAt, pointerPressed, calcPreferredSize, paramString, refreshTheme, isScrollableX, setScrollableX, isScrollableY, setScrollableY, getSideGap, getBottomGap, setScrollable, setCellRenderer, getScrollIncrement, setScrollIncrement, findFirstFocusable, dragInitiated, fireClicked, isSelectableInteraction, getGridPosY, paintComponentBackground, getGridPosX, animateHierarchyAndWait, createAnimateHierarchy, animateHierarchy, animateHierarchyFadeAndWait, createAnimateHierarchyFade, animateHierarchyFade, animateLayoutFadeAndWait, createAnimateLayoutFadeAndWait, animateLayoutFade, createAnimateLayoutFade, animateLayoutAndWait, animateLayout, updateTabIndices, createAnimateLayout, drop, createAnimateMotion, morph, morphAndWait, animateUnlayout, animateUnlayoutAndWait, createAnimateUnlayout, getChildrenAsList, iterator, iterator

From Component

setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, putClientProperty, getDirtyRegion, setDirtyRegion, isOpaque, setOpaque, getWidth, setWidth, getOuterWidth, getInnerWidth, getHeight, setHeight, getOuterHeight, getInnerHeight, isDragRegion, getDragRegionStatus, getBaseline, getBaselineResizeBehavior, getPreferredSizeStr, setPreferredSizeStr, getPreferredSize, setPreferredSize, getScrollDimension, calcScrollSize, setScrollSize, getPreferredW, setPreferredW, getPreferredH, setPreferredH, getOuterPreferredH, getInnerPreferredH, getOuterPreferredW, getInnerPreferredW, setSize, getUIID, setUIID, setUIIDFinal, setUIID, getInlineAllStyles, setInlineAllStyles, getInlineSelectedStyles, setInlineSelectedStyles, getInlineUnselectedStyles, setInlineUnselectedStyles, getInlineDisabledStyles, setInlineDisabledStyles, getInlinePressedStyles, setInlinePressedStyles, remove, getParent, getOwner, setOwner, isOwnedBy, containsOrOwns, addFocusListener, removeFocusListener, addScrollListener, removeScrollListener, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, resetFocusable, getTabIndex, setTabIndex, getPreferredTabIndex, setPreferredTabIndex, isTraversable, setTraversable, handlesInput, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, longKeyPress, keyRepeated, registerForAnimation, deregisterFromAnimation, getAnimationManager, getScrollAnimationSpeed, setScrollAnimationSpeed, isBlockLead, setBlockLead, isIgnorePointerEvents, setIgnorePointerEvents, isRippleEffect, setRippleEffect, getInlineStylesTheme, setInlineStylesTheme, shouldRenderComponentSelection, isHideInLandscape, setHideInLandscape, createStyleAnimation, isSmoothScrolling, setSmoothScrolling, pointerHover, stopScrollMomentum, pointerHoverReleased, pointerHoverPressed, pinch, pinchReleased, pinch, rotation, isPinchBlocksDragAndDrop, setPinchBlocksDragAndDrop, pointerDragged, getDragImage, getDragTransparency, setDragTransparency, toImage, drawDraggedImage, draggingOver, dragEnter, dragExit, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, isStickyDrag, pointerPressed, isDragAndDropOperation, pointerReleased, longPointerPress, pointerReleased, setVerticalScrollBounds, setHorizontalScrollBounds, isVScrollThumbGrabbed, isHScrollThumbGrabbed, isVScrollThumbHover, isHScrollThumbHover, isTensileDragEnabled, setTensileDragEnabled, getTextSelectionSupport, addDropListener, removeDropListener, addDragOverListener, removeDragOverListener, isNativeDragSource, setNativeDragSource, getNativeDragOperation, setNativeDragOperation, createNativeDragOperation, isNativeDropTarget, setNativeDropTarget, getAcceptedDropMimeTypes, setAcceptedDropMimeTypes, getAcceptedDropActions, setAcceptedDropActions, canAcceptNativeDrop, nativeDragEnter, nativeDragOver, nativeDragExit, nativeDrop, addNativeDropListener, removeNativeDropListener, addNativeDragOverListener, removeNativeDragOverListener, dragFinished, addDragFinishedListener, addStateChangeListener, removeStateChangeListener, addPointerPressedListener, addLongPressListener, addContextMenuListener, removeContextMenuListener, addMouseWheelListener, removeMouseWheelListener, addStylusListener, removeStylusListener, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getStyle, getPressedStyle, setPressedStyle, initUnselectedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, refreshTheme, refreshTheme, isDragActivated, animate, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, isEditable, laidOut, deinitialize, initComponent, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, getPropertyNames, getPropertyTypes, getPropertyTypeNames, getPropertyValue, setPropertyValue, paintLockRelease, paintLock, isSnapToGrid, setSnapToGrid, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, blocksSideSwipe, isFlatten, setFlatten, getTensileLength, setTensileLength, isGrabsPointerEvents, setGrabsPointerEvents, getScrollOpacityChangeSpeed, setScrollOpacityChangeSpeed, growShrink, isAlwaysTensile, setAlwaysTensile, isDraggable, setDraggable, isDropTarget, setDropTarget, isChildOf, isHideInPortrait, setHideInPortrait, getBindablePropertyNames, getBindablePropertyTypes, bindProperty, unbindProperty, getBoundPropertyValue, setBoundPropertyValue, getCloudBoundProperty, setCloudBoundProperty, getCloudDestinationProperty, setCloudDestinationProperty, getComponentState, setComponentState, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip

Field details

ready

protected boolean ready

Constructor details

ButtonList

protected ButtonList(ListModel model, boolean allowMultipleSelection)
Creates a new ButtonList.

Parameters

model ListModel
The options. Each will be represented by a button.
allowMultipleSelection boolean
indicates that multiple selection is allowed or not

Method details

onReady

protected void onReady(Runnable r)
Wrap any calls that requires that the infrastructure is ready inside this.

Parameters

r Runnable
Will be run when buttons are ready to be generated.

fireReady

protected final void fireReady()
This should be called by the concrete implementation once it is ready to generate the buttons.

getMultiListModel

public MultipleSelectionListModel getMultiListModel()
For multi-selection models (e.g. for checkbox or switch lists), this will return the model as a MultiSelectionListModel. Otherwise it will return null.

Returns

The model.

getModel

public ListModel getModel()
Returns the model.

Returns

The model

setModel

public final void setModel(ListModel model)

createButton

protected abstract Component createButton(Object model)
Creates a new button for this list. Should be implemented by subclasses to create the correct kind of button.

setSelected

protected abstract void setSelected(Component button, boolean selected)
Sets the given button’s selected state.

Parameters

button Component
The button (in the form produced by #createButton.
selected boolean
Whether the button is selected or not.

setLayout

public void setLayout(Layout layout)
Sets the layout for the list. This refresh the list to match the new layout.

Parameters

layout Layout
The layout to use. Only layouts that don’t require constraints in com.codename1.ui.Component) may be used. E.g. FlowLayout, BoxLyout, TableLayout, GridLayout are all fine.

refresh

public void refresh()
Refreshes the container - regenerating all of the buttons in the list from the model. This usually doesn’t ever need to be called explicitly as it will be called automatically when the model changes, or the layout changes.

decorateComponent

protected Component decorateComponent(Object modelItem, Component b)
Decorates buttons. This allows subclasses to add event listeners to buttons.

Parameters

modelItem Object
Not documented.
b Component
The button in the form returned by #createButton(java.lang.Object)

Returns

Should pass back the same component it receives.

undecorateComponent

protected Component undecorateComponent(Component b)
Undecorates buttons. This allows subclasses to remove event listeners from buttons.

Parameters

b Component
The button in the form returned by #createButton(java.lang.Object)

Returns

Should pass back the same component it receives.

dataChanged

public void dataChanged(int status, int index)
Invoked when there was a change in the underlying model

Parameters

status int
the type data change; REMOVED, ADDED or CHANGED
index int
item index in a list model

selectionChanged

public void selectionChanged(int oldSelected, int newSelected)
Indicates the selection changed in the underlying list model

Parameters

oldSelected int
old selected index in list model
newSelected int
new selected index in list model

actionPerformed

public void actionPerformed(ActionEvent evt)
Invoked when an action occurred on a component

Parameters

evt ActionEvent
event object describing the source of the action as well as its trigger

addActionListener

public void addActionListener(ActionListener l)
Add a listener to be notified when any of the buttons in the list are pressed.

removeActionListener

public void removeActionListener(ActionListener l)
Remove a listener so that it no longer is notified when buttons in the list are pressed.

setCellUIID

public void setCellUIID(String uiid)
Sets the UIID for cells of the list. Each cell will be a component as returned by the concrete implementation’s #createButton(java.lang.Object) method.

addDecorator

public void addDecorator(ButtonList.Decorator decorator)
Adds a decorator that can be used to customize a button when it is created

Parameters

decorator ButtonList.Decorator
A decorator.

removeDecorator

public void removeDecorator(ButtonList.Decorator decorator)
Removes a decorator.