Package totalcross.ui
Class MenuBar
- java.lang.Object
-
- totalcross.ui.gfx.GfxSurface
-
- totalcross.ui.Control
-
- totalcross.ui.Container
-
- totalcross.ui.Window
-
- totalcross.ui.MenuBar
-
public class MenuBar extends Window
Constructs a Menu with the given items. A menu can be opened by the user in a couple of ways:- By clicking in the Menu button
- By clicking in the title of a Window
MenuItem miBeamEvent,miNewEvent,miDeleteEvent; MenuItem col0[] = { new MenuItem("Record"), // caption for the MenuBar miNewEvent = new MenuItem("NewEvent",false), // checked item, starting unchecked miDeleteEvent = new MenuItem("Delete Event...",true), // checked item, starting checked new MenuItem("Attach Note"), new MenuItem("Delete Note..."), new MenuItem("Purge..."), beamEvent = new MenuItem("Beam Event"), }; MenuItem col1[] = { new MenuItem("Edit"), // caption for the MenuBar new MenuItem("Undo"), new MenuItem("Cut"), new MenuItem("Copy"), new MenuItem("Paste"), new MenuItem("Select All"), new MenuItem(), // a separator new MenuItem("Keyboard"), new MenuItem("Graffiti Help"), }; MenuItem col2[] = { new MenuItem("Options"), // caption for the MenuBar new MenuItem("Font..."), new MenuItem("Preferences..."), new MenuItem("Display Options..."), new MenuItem("Phone Lookup"), new MenuItem("About Date Book"), }; setMenuBar(new MenuBar(new MenuItem[][]{col0,col1,col2})); beamEvent.isEnabled = false; ... // at later time, disable the "new event" and enable the "delete event" miNewEvent.isChecked = true; miDeleteEvent.isChecked = false;The menu can be closed by a click on a valid item or clicking outside of its bounds. A PRESSED event will be thrown when the menu is closed and a menu item was selected. To discover which item was selected, see method getSelectedIndex, which returns -1 if none, or the matrix index otherwise.Note that the separator dotted line doesn't generate events and can't be selected.
To convert the old menu form (using a string matrix) into the new form using a MenuItem matrix, you can use this idea:
Old format:// the string arrays menuArq, menuUtil and menuSobre are initialized somewhere else setMenuBar(mbar = new MenuBar(new String[][]{menuArq,menuUtil,menuSobre})); mbar.setChecked(106,true); mbar.setEnabled(106,false); mbar.setChecked(4, true);New format:// declare these as global variables: MenuItem mi4, mi106; // at initUI setMenuBar(mbar = new MenuBar(MenuBar.strings2items(new String[][]{menuArq,menuUtil,menuSobre}))); MenuItem[][] mis = mbar.getMenuItems(); mi4 = mis[0][4]; mi106 = mis[1][6]; mi106.isChecked = true; mi106.isEnabled = false; mi4.isChecked = true;Note that, after changing the isChecked and isEnabled states, there's no need to call repaint, bacause they will show up only the next time the menu bar opens.
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class totalcross.ui.Control
Control.TranslucentShape
-
-
Field Summary
Fields Modifier and Type Field Description intgapNote: if you want to change the spacement between the menu items (maybe to make more items fit in the row), change this gap value.protected MenuItem[][]items-
Fields inherited from class totalcross.ui.Window
_controlEvent, _dragEvent, _focus, _keyEvent, _mouseEvent, _multiEvent, _penEvent, androidBorderThickness, beepIfOut, blocking, borderStyle, cancelPenUp, canDrag, dragThreshold, fadeOtherWindows, fadeValue, firstFocus, flickEnabled, focusOnPenUp, footerColor, footerH, gradientTitleEndColor, gradientTitleStartColor, headerColor, highlighted, highResPrepared, HORIZONTAL_GRADIENT, ignoreEventOfType, keyHook, lastShiftY, lastSwappedContainer, mainSwapContainer, menubar, multiTouching, needsPaint, NO_BORDER, ORIENTATION_INVERTED, ORIENTATION_LANDSCAPE, ORIENTATION_PORTRAIT, popped, RECT_BORDER, repaintOnSwap, robot, ROUND_BORDER, rTitle, sameBackgroundColor, shiftH, shiftY, SIP_BOTTOM, SIP_HIDE, SIP_SHOW, SIP_TOP, TAB_BORDER, TAB_ONLY_BORDER, tempTitle, title, titleAlign, titleColor, titleFont, titleGap, topMost, VERTICAL_GRADIENT, zStack
-
Fields inherited from class totalcross.ui.Container
alwaysEraseBackground, BACKGROUND_CYLINDRIC_SHADED, BACKGROUND_SHADED, BACKGROUND_SHADED_INV, BACKGROUND_SOLID, backgroundStyle, BORDER_LOWERED, BORDER_NONE, BORDER_RAISED, BORDER_ROUNDED, BORDER_SIMPLE, BORDER_TOP, borderColor, borderRadius, children, controlFound, finishedStart, ignoreOnAddAgain, ignoreOnRemove, insets, lastH, lastScreenWidth, lastW, npback, numChildren, started, tabOrder, tail, TRANSITION_TIME
-
Fields inherited from class totalcross.ui.Control
AFTER, alphaValue, appId, appObj, asContainer, asWindow, backColor, BEFORE, BOTTOM, BOTTOM_OF, BRIGHTER_BACKGROUND, callListenersOnAllTargets, CENTER, CENTER_OF, clearValueInt, clearValueStr, DARKER_BACKGROUND, DP, effect, enableUpdateScreen, esce, eventsEnabled, FILL, fillColor, FIT, floating, fm, fmH, focusHandler, focusLess, focusOnPenDown, focusTraversable, font, FONTSIZE, foreColor, height, ignoreInsets, isHighlighting, isTablet, KEEP, keepDisabled, keepEnabled, LEFT, next, nextTabControl, npParts, offscreen, offscreen0, onEventFirst, parent, PARENTSIZE, PARENTSIZEMAX, PARENTSIZEMIN, PREFERRED, prev, RANGE, repositionAllowed, RIGHT, RIGHT_OF, SAME, SCREENSIZE, SCREENSIZEMAX, SCREENSIZEMIN, setFont, setH, setRel, setW, setX, SETX_NOT_SET, setY, tempW, textShadowColor, TOP, translucentShape, transparentBackground, uiAdjustmentsBasedOnFontHeightIsSupported, uiAndroid, UICONST, uiFlat, uiHolo, uiMaterial, uiVista, visible, width, WILL_RESIZE, x, y
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description MenuItemgetMenuItem(int index)Returns the MenuItem at the given index.MenuItem[][]getMenuItems()Returns the matrix of Menuitems passed in the constructor.intgetSelectedIndex()Returns the current menu item selected.protected booleanhandleFocusChangeKeys(KeyEvent ke)Called by the main event handler to handle the focus change keys.voidmoveBy(int i)Moves to the MenuItem array at left or right depending on the passed value (-1 or +1).protected booleanonClickedOutside(PenEvent event)Close the popup list with a click outside its boundsprotected voidonColorsChanged(boolean colorsChanged)Called after a setEnabled, setForeColor and setBackColor and when a control has been added to a Container.voidonEvent(Event event)Called to process key, pen, control and other posted events.protected voidonFontChanged()Change the font and recompute some parametersvoidonPaint(Graphics g)Draws the border (if any).protected voidonPopup()Setup some important variablesprotected voidpostPopup()Placeholder called after the popup is done and after the repaint of this window.protected voidpostUnpop()Placeholder called after the unpop is done and after the repaint of the other window.voidsetAlternativeStyle(int back, int fore)Sets the style of this menubar to an alternative style (no borders, rectangular appearance).voidsetCursorColor(int c)Sets the cursor color.voidsetPopColors(int back, int fore, int cursor)Set the colors for the popup windows.voidsetVisible(boolean b)Called by the Window class to popup this MenuBarstatic MenuItem[][]strings2items(java.lang.String[][] items)Converts a String matrix into a MenuItem matrix.protected voidswitchTo(int index)-
Methods inherited from class totalcross.ui.Window
_doPaint, _postEvent, destroyZStack, drawHighlight, getBorderStyle, getClientRect, getClientRect, getDefaultDragThreshold, getFocus, getHighlighted, getPopupCount, getPreferredHeight, getPreferredWidth, getSafeAreaInsets, getTitleFont, getTopMost, isScreenShifted, isSipShown, isSipShown4D, isTopMost, isVisible, loadBehind, makeUnmovable, onRobotKey, onUnpop, paintTitle, paintWindowBackground, popup, popupMenuBar, popupNonBlocking, postPressedEvent, pumpEvents, removeFocus, repaintActiveWindows, resize, resizeHeight, resizeWidth, screenResized, setBorderStyle, setDeviceTitle, setFocus, setGrabPenEvents, setHighlighted, setMenuBar, setOrientation, setSIP, setTitle, setTitleFont, shiftScreen, swap, swapFocus, unpop, validate
-
Methods inherited from class totalcross.ui.Container
add, add, add, add, add, broadcastEvent, clear, fillBackground, fillBackground, findChild, findNearestChild, findNextFocusControl, getBorderRadius, getChildren, getChildrenCount, getFirstChild, getFocusableControls, getInsets, incLastX, incLastY, initUI, isPressed, moveFocusToNextControl, moveFocusToNextEditable, onAddAgain, onRemove, onSwapFinished, paintChildren, remove, removeAll, setBorderRadius, setEnabled, setFocusTraversable, setHighlighting, setInsets, setPressColor, setPressed, swapToTopmostWindow
-
Methods inherited from class totalcross.ui.Control
_onEvent, addEnabledStateListener, addFocusListener, addFontChangeHandler, addGridListener, addHandler, addHighlightListener, addKeyListener, addListContainerListener, addMouseListener, addMultiTouchListener, addPenListener, addPressListener, addPushNotificationListener, addSizeChangeHandler, addTimer, addTimer, addTimerListener, addValueChangeHandler, addWindowListener, bringToFront, changeHighlighted, contains, drawTranslucentBackground, getAbsoluteRect, getBackColor, getDoEffect, getEffectH, getEffectW, getEffectX, getEffectY, getEventListeners, getFont, getForeColor, getGap, getGraphics, getHeight, getNext, getParent, getParentWindow, getPos, getPressedEvent, getPrev, getRect, getSize, getTextShadowColor, getWidth, getX, getX2, getY, getY2, hadParentScrolled, handleGeographicalFocusChangeKeys, hasFocus, internalSetEnabled, intXYWH, isActionEvent, isChildOf, isDisplayed, isEnabled, isFloating, isInsideOrNear, isObscured, isVisibleAndInside, onBoundsChanged, onWindowPaintFinished, post, postEvent, releaseScreenShot, removeEnabledStateListener, removeFocusListener, removeGridListener, removeHandler, removeHighlightListener, removeKeyListener, removeListContainerListener, removeMouseListener, removeMultiTouchListener, removePenListener, removePressListener, removePushNotificationListener, removeTimer, removeTimerListener, removeWindowListener, repaint, repaintNow, reposition, reposition, repositionChildren, requestFocus, resetSetPositions, resetStyle, safeRepaintNow, safeUpdateScreen, sendToBack, setBackColor, setBackForeColors, setDoEffect, setFloating, setFocusLess, setFont, setForeColor, setNinePatch, setNinePatch, setRect, setRect, setRect, setRect, setSet, setTextShadowColor, setTranslucent, showTip, takeInitialScreenShot, takeScreenShot, translateFromOrigin, uiStyleChanged, updateScreen, updateTemporary, willOpenKeyboard
-
-
-
-
Field Detail
-
items
protected MenuItem[][] items
-
gap
public int gap
Note: if you want to change the spacement between the menu items (maybe to make more items fit in the row), change this gap value. Default is 3 (3 pixels at left and 3 at right).
-
-
Constructor Detail
-
MenuBar
public MenuBar(MenuItem[][] items)
Create a MenuBar with the given menu items.
-
-
Method Detail
-
strings2items
public static MenuItem[][] strings2items(java.lang.String[][] items)
Converts a String matrix into a MenuItem matrix.
-
getMenuItems
public MenuItem[][] getMenuItems()
Returns the matrix of Menuitems passed in the constructor.
-
getMenuItem
public MenuItem getMenuItem(int index)
Returns the MenuItem at the given index. E.g.:MenuItem file = mbar.getMenuItem(102);
-
setPopColors
public void setPopColors(int back, int fore, int cursor)Set the colors for the popup windows. You can pass-1to any parameter to keep the current settings.
-
setCursorColor
public void setCursorColor(int c)
Sets the cursor color. By default, it is based in the background color
-
setVisible
public void setVisible(boolean b)
Called by the Window class to popup this MenuBar- Overrides:
setVisiblein classControl
-
onFontChanged
protected void onFontChanged()
Change the font and recompute some parameters- Overrides:
onFontChangedin classControl
-
getSelectedIndex
public int getSelectedIndex()
Returns the current menu item selected.- Returns:
- -1 if no item was selected, or a number with format xyy, where x is the index of the item selected at the MenuBar and yy is the index+1 ( = the index of the String array that defines the items) of the item selected in the MenuBarDropDown. EG: suppose that the col1/"Cut" of the example at the top of this page was clicked, then 102 is returned.
-
onClickedOutside
protected boolean onClickedOutside(PenEvent event)
Close the popup list with a click outside its bounds- Overrides:
onClickedOutsidein classWindow
-
onEvent
public void onEvent(Event event)
Description copied from class:ControlCalled to process key, pen, control and other posted events.
-
postUnpop
protected void postUnpop()
Description copied from class:WindowPlaceholder called after the unpop is done and after the repaint of the other window. The default implementation does nothing.
-
postPopup
protected void postPopup()
Description copied from class:WindowPlaceholder called after the popup is done and after the repaint of this window. The default implementation does nothing.
-
switchTo
protected void switchTo(int index)
-
onColorsChanged
protected void onColorsChanged(boolean colorsChanged)
Description copied from class:ControlCalled after a setEnabled, setForeColor and setBackColor and when a control has been added to a Container. If colorsChanged is true, it was called from setForeColor/setBackColor/Container.add; otherwise, it was called from setEnabled- Overrides:
onColorsChangedin classContainer
-
onPaint
public void onPaint(Graphics g)
Description copied from class:ContainerDraws the border (if any). If you override this method, be sure to callsuper.onPaint(g);, or the border will not be drawn.
-
moveBy
public void moveBy(int i)
Moves to the MenuItem array at left or right depending on the passed value (-1 or +1).
-
handleFocusChangeKeys
protected boolean handleFocusChangeKeys(KeyEvent ke)
Description copied from class:WindowCalled by the main event handler to handle the focus change keys. Only called when Settings.keyboardFocusNavigation is true.- Overrides:
handleFocusChangeKeysin classWindow
-
setAlternativeStyle
public void setAlternativeStyle(int back, int fore)Sets the style of this menubar to an alternative style (no borders, rectangular appearance). Here's a sample, taken from the UIGadgets sample:mbar.setAlternativeStyle(Color.BLUE,Color.WHITE);
The colors are set using a combination of the given back and fore colors. You can have a more flexible color selection by using the code below, instead of calling this method. Under most situations, tho, this method is enough.mbar.setBackForeColors(Color.BLUE, Color.WHITE); mbar.setCursorColor(0x6464FF); mbar.setBorderStyle(NO_BORDER); mbar.setPopColors(0x0078FF, Color.CYAN, -1); // use the default cursor color for the popup menu (last -1 param)- Since:
- TotalCross 1.0 beta 4
-
-