public abstract class 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.Decorator | An 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
Inherited fields
From Component
DEFAULT_CURSOR, CROSSHAIR_CURSOR, TEXT_CURSOR, WAIT_CURSOR, SW_RESIZE_CURSOR, SE_RESIZE_CURSOR, NW_RESIZE_CURSOR, NE_RESIZE_CURSOR, N_RESIZE_CURSOR, S_RESIZE_CURSOR, W_RESIZE_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, MOVE_CURSOR, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_Y, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_IMMEDIATELY_DRAG_XY, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_CENTER_OFFSET, BRB_OTHER, CENTER, TOP, LEFT, BOTTOM, RIGHT, BASELINE
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 readyConstructor details
ButtonList
protected ButtonList(ListModel model, boolean allowMultipleSelection)Parameters
modelListModel- The options. Each will be represented by a button.
allowMultipleSelectionboolean- indicates that multiple selection is allowed or not
Method details
onReady
protected void onReady(Runnable r)Parameters
rRunnable- Will be run when buttons are ready to be generated.
fireReady
protected final void fireReady()getMultiListModel
public MultipleSelectionListModel getMultiListModel()MultiSelectionListModel. Otherwise it will return null.Returns
getModel
public ListModel getModel()Returns
setModel
public final void setModel(ListModel model)createButton
protected abstract Component createButton(Object model)setSelected
protected abstract void setSelected(Component button, boolean selected)Parameters
buttonComponent- The button (in the form produced by
#createButton. selectedboolean- Whether the button is selected or not.
setLayout
public void setLayout(Layout layout)Parameters
layoutLayout- The layout to use. Only layouts that don’t require constraints in
com.codename1.ui.Component)may be used. E.g.FlowLayout,BoxLyout,TableLayout,GridLayoutare all fine.
refresh
public void refresh()decorateComponent
protected Component decorateComponent(Object modelItem, Component b)Parameters
modelItemObject- Not documented.
bComponent- The button in the form returned by
#createButton(java.lang.Object)
Returns
undecorateComponent
protected Component undecorateComponent(Component b)Parameters
bComponent- The button in the form returned by
#createButton(java.lang.Object)
Returns
dataChanged
public void dataChanged(int status, int index)Parameters
statusint- the type data change; REMOVED, ADDED or CHANGED
indexint- item index in a list model
selectionChanged
public void selectionChanged(int oldSelected, int newSelected)Parameters
oldSelectedint- old selected index in list model
newSelectedint- new selected index in list model
actionPerformed
public void actionPerformed(ActionEvent evt)Parameters
evtActionEvent- event object describing the source of the action as well as its trigger
addActionListener
public void addActionListener(ActionListener l)removeActionListener
public void removeActionListener(ActionListener l)setCellUIID
public void setCellUIID(String uiid)#createButton(java.lang.Object) method.addDecorator
public void addDecorator(ButtonList.Decorator decorator)Parameters
decoratorButtonList.Decorator- A decorator.
removeDecorator
public void removeDecorator(ButtonList.Decorator decorator)