Codename One Reference Guide
Codename One Reference Guide
Package
Description
com.codename1.ads
com.codename1.analytics
The analytics API allows tracking your mobile application usage in the
field to give you real-time data on how your application is used.
com.codename1.capture
com.codename1.charts
com.codename1.charts.models
Provides the classes that handle the data values (data model) to be used
by displaying the charts.
com.codename1.charts.renderers Provides renderer classes that keep the chart rendering / drawing styles.
com.codename1.charts.transitions
com.codename1.charts.util
Utility classes that provide helper methods used by most of the other
packages.
com.codename1.charts.views
Provides the classes that handle the actual rendering / drawing of the
charts, based on the provided model and renderer.
com.codename1.cloud
com.codename1.codescan
com.codename1.components
com.codename1.contacts
com.codename1.db
SQLite support.
com.codename1.facebook
com.codename1.facebook.ui
com.codename1.io
com.codename1.io.gzip
com.codename1.io.services
com.codename1.io.tar
com.codename1.javascript
com.codename1.l10n
com.codename1.location
com.codename1.maps
com.codename1.maps.layers
com.codename1.maps.providers
com.codename1.media
Video and audio playback support are handled within this package using
the Media/Media manager APIs.
com.codename1.messaging
com.codename1.processing
com.codename1.push
com.codename1.share
com.codename1.social
com.codename1.system
Low level calls into the Codename One system, including support for
making platform native API calls.
com.codename1.testing
com.codename1.ui
com.codename1.ui.animations
com.codename1.ui.events
com.codename1.ui.geom
com.codename1.ui.html
This package is deprecated and used only for legacy support, use the
WebBrowser component from the components package.
com.codename1.ui.layouts
com.codename1.ui.layouts.mig
com.codename1.ui.list
Lists are highly customizable and serve as the basis for ComboBox and
other components (such as carousels etc) they employ a similar MVC
approach to Swing including the renderer pattern.
com.codename1.ui.painter
com.codename1.ui.plaf
com.codename1.ui.spinner
com.codename1.ui.table
Table component for editing and viewing tabular data and arranging
Codename One components in a tabular form
com.codename1.ui.tree
com.codename1.ui.util
Utility features that are either too domain specific or don't "fit" into any
other packages including the Resource file format loading API.
com.codename1.ui.validation
com.codename1.util
com.codename1.util.regex
com.codename1.xml
The XML package allows parsing XML documents into DOM objects.
Painter
java.io
java.lang
java.lang.annotation
Codename One - Write Once Run Anywhere Native Mobile Apps Using
Java
Codename One allows Java developers to write their app once and have it work on all mobile devices (iOS,
Android etc.). It features a simulator, designer (visual theme/builder) and ports to multiple OS's.
Codename One is a mature open source project and its roots go back to Sun Microsystems (2006) where one
of its core underlying components was developed and open sourced.
Codename One is open source. This includes the libraries, native OS ports, resource editor & native VM
code. It also includes themes and separate related projects containing demos, skins etc.
You can understand more about how Codename One works and how the API fits into everything in this
stackoverflow answer.
Other Resources
Developer Guide
How Do I? - Get quick video answers and short tutorials for common questions
The Codename One Blog
cn1libs are extensions to Codename One that allow using device native functionality
Stack Overflow's Codename One Tag
Community Discussion Forum
The Open Source project on github
Build Codename One from source code
Codename One - Write Once Run Anywhere Native Mobile Apps Using Java
Package java.util
Interface
Description
Collection<E>
Collection
Comparator<T>
Deque<E>
Enumeration<T>
EventListener
Iterator<E>
List<E>
ListIterator<E>
Map<K,V>
A Map is a data structure consisting of a set of keys and values in which each
key is mapped to a single value.
Map.Entry<K,V>
Map.Entry
NavigableMap<K,V>
NavigableSet<E>
Observer
Queue<E>
RandomAccess
Set<E>
SortedMap<K,V>
SortedSet<E>
Class
AbstractCollection<E>
Description
Class AbstractCollection is an abstract implementation
of the Collection interface.
AbstractList<E>
AbstractMap<K,V>
AbstractMap.SimpleEntry<K,V>
A key-value mapping.
AbstractList
AbstractSequentialList<E>
AbstractSet<E>
ArrayDeque<E>
ArrayList<E>
Package java.util
Arrays
BitSet
Calendar
Collections
Collections contains
Collection classes.
Date
Dictionary<K,V>
EventListenerProxy
HashMap<K,V>
HashSet<E>
Hashtable<K,V>
IdentityHashMap<K,V>
LinkedHashMap<K,V>
LinkedHashSet<E>
LinkedList<E>
Observable
PriorityQueue<E>
Random
Stack<E>
StringTokenizer
Timer
TimerTask
TimeZone
TreeMap<K,V>
TreeSet<E>
Vector<E>
Exception
Description
NoSuchElementException
Package java.util
Package java.text
Class
DateFormat
Description
Deprecated
this class has many issues in iOS and other platforms, please use the
L10NManager
SimpleDateFormat
Deprecated
this class has many issues in iOS and other platforms, please use the
L10NManager
Exception
Description
Package java.text
Package java.net
Class
URI
Description
An implementation of a Univeral Resource Identifier (URI).
Exception
Description
URISyntaxException
Package java.net
Package java.lang.ref
Class
Reference
Description
Abstract base class for reference objects.
Package java.lang.ref
Package java.lang
Interface
Appendable
Description
Declares methods to append characters or character sequences.
AutoCloseable
CharSequence
This interface represents an ordered set of characters and defines the methods to
probe them.
Cloneable
This (empty) interface must be implemented by all classes that wish to support
cloning.
Comparable<T>
This interface should be implemented by all classes that wish to define a natural
order of their instances.
Iterable<T>
Objects of classes that implement this interface can be used within a foreach
statement.
Runnable
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread.
Class
Description
Boolean
The Boolean class wraps a value of the primitive type boolean in an object.
Byte
Character
The Character class wraps a value of the primitive type char in an object.
Class<T>
Instances of the class Class represent classes and interfaces in a running Java
application.
Double
The Double class wraps a value of the primitive type double in an object.
Enum<E extends
Enum<E>>
Float
Integer
The Integer class wraps a value of the primitive type int in an object.
Long
The Long class wraps a value of the primitive type long in an object.
Math
The class Math contains methods for performing basic numeric operations.
Object
Runtime
Every Java application has a single instance of class Runtime that allows the
application to interface with the environment in which the application is
running.
Short
String
StringBuffer
StringBuilder
System
The System class contains several useful class fields and methods.
Thread
Throwable
The Throwable class is the superclass of all errors and exceptions in the Java
language.
Void
Exception
Description
ArithmeticException
ArrayIndexOutOfBoundsException
ArrayStoreException
Package java.lang
10
ClassNotFoundException
CloneNotSupportedException
Exception
IllegalAccessException
IllegalArgumentException
IllegalMonitorStateException
IllegalStateException
IllegalThreadStateException
IndexOutOfBoundsException
InstantiationException
InterruptedException
NegativeArraySizeException
NullPointerException
NumberFormatException
RuntimeException
SecurityException
Error
Description
AssertionError
Error
LinkageError
NoClassDefFoundError
Package java.lang
11
OutOfMemoryError
VirtualMachineError
Annotation Type
Description
Deprecated
Override
SuppressWarnings
Package java.lang
12
Package java.lang.invoke
Class
Description
CallSite
Deprecated
these classes are used internally for Lambda compatibility
LambdaMetafactory
Deprecated
these classes are used internally for Lambda compatibility
MethodHandle
Deprecated
these classes are used internally for Lambda compatibility
MethodHandles
Deprecated
these classes are used internally for Lambda compatibility
MethodHandles.Lookup
MethodType
Package java.lang.invoke
Deprecated
these classes are used internally for Lambda compatibility
13
Package java.lang.annotation
Interface
Description
Enum
ElementType
Description
A mirror of java.lang.annotation.ElementType.
Exception
Description
Error
Description
Package java.lang.annotation
14
Package java.io
Interface
Description
DataInput
The DataInput interface provides for reading bytes from a binary stream and
reconstructing from them data in any of the Java primitive types.
DataOutput
The DataOutput interface provides for converting data from any of the Java primitive
types to a series of bytes and writing these bytes to a binary stream.
Flushable
Class
Description
ByteArrayInputStream
ByteArrayOutputStream
This class implements an output stream in which the data is written into a
byte array.
DataInputStream
A data input stream lets an application read primitive Java data types from
an underlying input stream in a machine-independent way.
DataOutputStream
A data output stream lets an application write primitive Java data types to
an output stream in a portable way.
InputStream
InputStreamReader
OutputStream
OutputStreamWriter
PrintStream
Reader
Writer
Exception
Description
EOFException
InterruptedIOException
IOException
Package java.io
15
Package com.codename1.xml
The XML package allows parsing XML documents into DOM objects.
See: Description
Interface
ParserCallback
Description
A callback used to dispatch errors encountered while parsing XML
resources
Class
Element
Description
The Element class defines a single XML element with its attributes and children.
XMLParser Parser class used to parse an XML document into a DOM object (Element).
XMLWriter
Package com.codename1.xml
16
Package com.codename1.util.regex
A simple regular expression API that is portable across all platforms
See: Description
Interface
Description
Class
Description
ReaderCharacterIterator
RECharacter
RECompiler
REDebugCompiler
REProgram
REUtil
This is a class that contains utility helper methods for this package.
StreamCharacterIterator
StringCharacterIterator
StringReader
Exception
Description
Package com.codename1.util.regex
17
Package com.codename1.util
General utilities classes
See: Description
Interface
Callback<T>
Description
Simple interface that allows asynchronous code to perform a parameterized callback
or failure in a similar way to GWT's callback interface
LazyValue<T> Useful when passing a value that might not exist to a function, e.g.
Class
Description
Base64
BigDecimal
BigInteger
CaseInsensitiveOrder
CStringBuilder
Deprecated
we will be moving to the proper string builder very soon
MathUtil
StringUtil
Package com.codename1.util
18
Package com.codename1.ui.validation
The validation framework allows us to mark invalid input in text components and disable components in the
case of invalid input
See: Description
Interface
Constraint
Description
To perform validation we add a constraint to a validator, a constraint defines whether a
value if valid for a given object
Class
Description
Validator
Enum
Description
Package com.codename1.ui.validation
19
Package com.codename1.ui.util
Utility features that are either too domain specific or don't "fit" into any other packages including the Resource
file format loading API.
See: Description
Class
Description
Effects
Static utility class useful for simple visual effects that don't quite fit anywhere
else in the core API.
EmbeddedContainer
This class is mostly used internally by the GUI builder and isn't very useful for
general purpose.
EventDispatcher
Handles event dispatching while guaranteeing that all events would be fired
properly on the EDT regardless of their source.
GlassTutorial
ImageIO
Enable simple operations on image file & image objects such as dynamic
scaling and storage to binary formats such as JPEG.
Resources
Loads resources from the binary resource file generated by the Codename
One Designer.
SwipeBackSupport
Allows binding a swipe listener to the form that enables the user to swipe
back to the previous form.
UIBuilder
The UI builder can create a user interface based on the UI designed in the
resource editor and allows us to bind to said UI.
UITimer
Package com.codename1.ui.util
20
Package com.codename1.ui.tree
Tree component for displaying hierarchy based information and its related classes
See: Description
Interface
Description
TreeModel
Arranges tree node objects, a node can essentially be anything and it will be displayed in
a hierarchy using the Tree
Class
Tree
Description
The Tree component allows constructing simple tree component hierarchies that can be
expanded seamlessly with no limit.
Package com.codename1.ui.tree
21
Package com.codename1.ui.table
Table component for editing and viewing tabular data and arranging Codename One components in a tabular
form
See: Description
Interface
TableModel
Description
The table and table model class are complimentry classes allowing the quick
construction of tabular data controls.
Class
Description
DefaultTableModel
Table
The Table class represents a grid of data that can be used for rendering a
grid of components/labels.
TableLayout
TableLayout.Constraint
Represents the layout constraint for an entry within the table indicating the
desired position/behavior of the component.
Package com.codename1.ui.table
22
Package com.codename1.ui.spinner
Spinners allows picking of simple sequential values similarly to combo boxes but of a much wider value set.
See: Description
Class
Description
BaseSpinner
DateSpinner
A date spinner allows selecting a date value within the given date range
DateTimeSpinner
The date and time spinner extends the time spinner by allowing to pick a specific
day as well
GenericSpinner
A spinner class that allows arbitrary values, this is effectively a combo box
replacement for platforms where a combo box is not available
NumericSpinner
Picker
Picker
TimeSpinner
Package com.codename1.ui.spinner
23
Package com.codename1.ui.plaf
Look of the application can be fully customized via this package, it represents a rendering layer that can be
plugged in separately in runtime and themed to provide any custom look.
See: Description
Class
Description
Border
DefaultLookAndFeel
Deprecated
this class is still crucial for some features in Codename One.
LookAndFeel
Deprecated
this class is still crucial for some features in Codename One.
Style
UIManager
Central point singleton managing the look of the application, this class allows
us to customize the styles (themes) as well as the look instance.
Package com.codename1.ui.plaf
24
Package com.codename1.ui.painter
allows us to draw arbitrary elements of graphics from plain/scaled/tiled images to gradients and pretty
much any form of graphic drawing we can imagine.
See: Description
Painter
Class
Description
BackgroundPainter A painter that draws the background of a component based on its style
PainterChain
Package com.codename1.ui.painter
25
Package com.codename1.ui
See: Description
Interface
Description
Painter
URLImage.ImageAdapter
Allows applying resize logic to downloaded images you can use constant
resize behaviors defined in this class.
Class
Description
AnimationManager
Animation manager concentrates all of the animations for a given form into
a single place that allows us to manage all mutations to a Form in a way the
prevents collisions between mutations.
AutoCompleteTextField
BrowserComponent
Button
ButtonGroup
Calendar
CheckBox
ComboBox<T>
A ComboBox is a list that allows only one selection at a time, when a user
clicks the ComboBox a popup button with the full list of elements allows the
selection of a single element.
Command
Component
ComponentGroup
Container
Dialog
Display
Central class for the API that manages rendering/events and is used to
place top level components (Form) on the "display".
EncodedImage
An image that only keeps the binary data of the source file used to load it in
permanent memory.
Font
Package com.codename1.ui
26
Form
Top level component that serves as the root for the UI, this Container
handles the menus and title while placing content between them.
Graphics
Image
InfiniteContainer
This abstract Container can scroll indefinitely (or at least until we run out of
data).
Label
Allows displaying a single line of text and icon (both optional) with different
alignment options.
List<T>
MenuBar
NavigationCommand
PeerComponent
RadioButton
RGBImage
An image that stores its data as an integer RGB array internally, this image
cannot be manipulated via Graphics primitives however its array is
accessible and modifiable programmatically.
SideMenuBar
This is Menu Bar that displays it's commands on a side bar navigation
similar to Google+/Facbook apps navigation
Slider
The slider component serves both as a slider widget to allow users to select
a value on a scale via touch/arrows and also to indicate progress.
Stroke
SwipeableContainer
SwipeableContainer
Tabs
TextArea
An optionally multi-line editable region that can display text and allow a user
to edit it.
TextField
Toolbar
Toolbar replaces the default title area with a powerful abstraction that
allows functionality ranging from side menus (hamburger) to title animations
and any arbitrary component type.
Transform
URLImage
URLImage
VirtualKeyboard
This class represent the Codename One Light Weight Virtual Keyboard
27
Component/Container Relationship
Containers can be nested one within the other to form elaborate UI's. Containers use
com.codename1.ui.layouts to arrange the components within. This is important as it allows a container can
adapt to changing resolution, DPI, orientation, font size etc.
A container doesn't implicitly reflow its elements and in that regard follows the direction of AWT/Swing. As a
result the layout can be animated to create a flowing effect for UI changes. This also provides improved
performance as a bonus. See this sample of Container animation:
You can learn more about layout managers here and about event handling here.
Component Gallery
The component gallery below isn't complete or exhaustive but it should give you a sense of the types of
widgets available within Codename One in a glance.
AutoCompleteTextField
AutoCompleteTextField
BrowserComponent
Component/Container Relationship
28
allows us to embed an OS native browser into the app and connect to its JavaScript
runtime!
Button
Button
Link Button
Button
Calendar
presents a visual date picker. Notice that we recommend using the Picker class which is superior
when running on the device for most use cases.
Calendar
CheckBox
provides a check flag to tick on/off. RadioButton provides an exclusive check marking that only
applies to one radio within the group. Both can also appear as toggle buttons
CheckBox
BrowserComponent
29
ComboBox
a single visible entry that can popup the full list. Notice that we recommend using the
superior when running on the device for most use cases
Command
& Toolbar provide deep customization of the title area and allow us to place elements in the side
menu (hamburger), overflow menu etc.
Command
ComponentGroup
ComponentGroup
Dialog
Dialog
ComboBox
30
InfiniteContainer
InfiniteContainer
& InfiniteScrollAdapter implement a Container that can dynamically fetch more data
Label
Label
List
MultiList
a list that is a bit simpler to work with than List List although our recommendation to use
something else still applies
MultiList
InfiniteContainer
31
Slider
Slider
allows us to indicate progress or allows the user to drag a bar to indicate volume (as in quantity)
SwipeableContainer
SwipeableContainer
Tabs
Tabs
places components/containers into tabbable entries, allows swiping between choices thru touch
Carousel
Tabs
TextArea/Field
Slider
32
TextArea
& TextField allow for user input via the keyboard (virtual or otherwise)
Table
Table
Tree
Tree
ChartComponent
ChartComponent
can embed a wide range of visualization aids and animations into your app
ImageViewer
TextArea/Field
33
ImageViewer
InfiniteProgress
InfiniteProgress
InteractionDialog
InteractionDialog
MediaPlayer
MediaPlayer
MultiButton
ImageViewer
34
MultiButton
OnOffSwitch
OnOffSwitch
allows us to toggle a state similar to the CheckBox but with a more modern look
ShareButton
ShareButton
ShareButton
SpanLabel
MultiButton
35
SpanLabel
SpanButton
SpanButton
Picker (Date)
Picker
Picker (Time)
Picker
ToastBar
SpanLabel
36
ToastBar
ToastBar
37
Package com.codename1.ui.list
Lists are highly customizable and serve as the basis for ComboBox and other components (such as carousels
etc) they employ a similar MVC approach to Swing including the renderer pattern.
See: Description
Interface
CellRenderer<T>
Description
Deprecated
this interface was added for ContainerList which is now deprecated.
A "rubber stamp" tool that allows us to extract a component (often the same
component instance for all invocations) that is initialized to the value of the
ListCellRenderer<T>
current item extracted from the model, this component is drawn on the list and
discarded.
ListModel<T>
Represents the data structure of the list, thus allowing a list to represent any
potential data source by referencing different implementations of this interface.
Class
Description
ContainerList
Deprecated
the performance of ContainerList is worse than the performance of
List or Container.
DefaultListCellRenderer<T>
DefaultListModel<T>
FilterProxyListModel<T>
GenericListCellRenderer<T>
MultiList
Package com.codename1.ui.list
38
Package com.codename1.ui.layouts
Layout managers allow a Container to arrange its components by a set of rules that adapt to specific
densities (ppi - pixels per inch).
See: Description
Class
Description
BorderLayout
A border layout lays out a container, arranging and resizing its components to
fit in five regions: north, south, east, west, and center.
BoxLayout
CoordinateLayout
Deprecated
the usage of this layout is strongly discouraged as elements will not adapt to
the right position/size
FlowLayout
FlowLayout is the default layout manager for Codename One Containers and
Forms.
GridLayout
The components are arranged in a grid based on available space, all cells in
the grid are given exactly the same size which matches the largest preferred
size or available space.
GroupLayout
Insets
Port of Insets from Harmony for the use of the GridBag code
LayeredLayout
The LayeredLayout places the components in order one on top of the other and
sizes them all to the size of the largest component.
Layout
LayoutStyle
Package com.codename1.ui.layouts
39
BorderLayout
BorderLayout
40
BoxLayout
BoxLayout
X axis is a simpler replacement to flow layout and has grow/no grow variants.
41
GridLayout
arranges elements in a grid where all elements have an equal size. It can auto adapt the column
count.
42
is similar in many regards to HTML tables. Notice that its in the com.codename1.ui.table
package and not in this package.
TableLayout
43
GridBagLayout
MigLayout
is a popular 3rd party layout manager its Codename One port is experimental.
44
45
Package com.codename1.ui.layouts.mig
Interface
Description
InCellGapProvider
An interface to implement if you want to decide the gaps between two types of
components within the same cell.
Class
Description
AC
A constraint that holds the column or row constraints for the grid.
BoundSize
A size that contains minimum, preferred and maximum size of type UnitValue.
CC
Grid
LayoutCallback
A class to extend if you want to provide more control over where a component is
placed or the size of it.
LayoutUtil
LC
LinkHandler
MigLayout
Deprecated
this is currently an experimental integration and has known bugs do not rely on
this layout for production
Package com.codename1.ui.layouts.mig
46
Package com.codename1.ui.html
This package is deprecated and used only for legacy support, use the WebBrowser component from the
components package.
See: Description
Interface
Description
DocumentRequestHandler
HTMLCallback
IOCallback
Class
Description
AsyncDocumentRequestHandlerImpl
DefaultDocumentRequestHandler
DefaultHTMLCallback
DocumentInfo
HTMLComponent
Deprecated
this component includes some customizability advantages but
its probably better for 99% of the use cases to use the
WebBrowser Component from the Components package.
HTMLElement
HTMLParser
HTMLUtils
Package com.codename1.ui.html
47
Package com.codename1.ui.geom
Contains classes related to geometry locations and calculations such as rectangle and size
See: Description
Interface
Description
PathIterator This interface provides a directed path over the boundary of a shape.
Shape
Class
Description
Dimension
Utility class that holds a width and height that represents a dimension of a component
or element
Dimension2D
Utility class that holds a width and height that represents a dimension of a component
or element
GeneralPath
Point
Point2D
Rectangle
Represents a Rectangle position (x, y) and Dimension (width, height), this is useful for
measuring coordinates within the application.
Rectangle2D
Represents a Rectangle position (x, y) and Dimension (width, height), this is useful for
measuring coordinates within the application.
Package com.codename1.ui.geom
48
Package com.codename1.ui.events
Observable pattern event listeners in the spirit of AWT 1.1's event dispatching architecture, all events are
dispatched on the EDT (Event Dispatch Thread).
See: Description
Interface
ActionListener
Description
Event callback interface invoked when a component action occurs
FocusListener
Observes focus change events for a given form and invokes the
callbacks to enable us to assign functionality based on current focused
component.
ScrollListener
SelectionListener
StyleListener
Class
Description
Enum
Description
Package com.codename1.ui.events
49
Package com.codename1.ui.animations
All components are animatable by potential and additional animations (unrelated to a specific component) can
be installed on the fly, transitions between forms are also handled as part of this package.
See: Description
Interface
Description
Animation Allows any object to react to events and draw an animation at a fixed interval.
Class
Description
AnimationObject
An animation object is an element within the timeline that has a visibility state
for rendering at a given point in time.
CommonTransitions
ComponentAnimation
FlipTransition
MorphTransition
Motion
Abstracts the notion of physical motion over time from a numeric location to
another.
Timeline
Transition
Package com.codename1.ui.animations
50
Package com.codename1.testing
This package contains everything necessary for unit tests, automation of tests and everything in between.
See: Description
Interface
UnitTest
Description
A Codename One unit test interface, you would normally like to derive from AbstractTest
which is less verbose and contains many helper methods.
Class
Description
AbstractTest
A unit test class that simplifies the process of writing test cases for Codename
One.
DeviceRunner
Runs the test cases from the test build of the app, notice that this class is
abstract since device/app specific code can exist in the implementation
Produces test reporting in the format of JUnit XML for compatibility with tools
JUnitXMLReporting that consume JUnit test case results see
http://code.google.com/p/codenameone/issues/detail?id=446 for more details.
TestReporting
Test reports can be overriden to provide custom test reporting options you can
replace the test reporter on the device by sending the build argument
build.testReporter='com.x.MyTestReporterClass'.
TestUtils
Package com.codename1.testing
51
Package com.codename1.system
Low level calls into the Codename One system, including support for making platform native API calls.
See: Description
Interface
Description
CrashReport
NativeInterface
URLCallback
In platforms that support opening an application via URL this interface can be
implemented by the main class to support such functionality.
Class
Description
DefaultCrashReporter
A default implementation of the crash reporter that instantly sends the crash
data to the server.
NativeLookup
Creates an instance of the native interface which will call the underlying
platform using the convention documented in the package docs.
Package com.codename1.system
52
Notice that this code will only be compiled on the server build and is not compiled on the client. These sources
should be placed under the appropriate folder in the native directory and are sent to the server for compilation.
For Objective-C, one would need to define a class matching the name of the package and the class name
combined where the "." elements are replaced by underscores. One would need to provide both a header and
an "m" file following this convention e.g.:
53
Package com.codename1.social
Connectors for native social network SDK's
See: Description
Class
Description
Invokes the native bundled facebook SDK to login/logout of facebook, notice that
in order for this to work server build arguments must indicate that you are using
FacebookConnect
the facebook sdk! To accomplish this just define: facebook.appId=YourAppId in
your build arguments.
GoogleConnect
The GoogleConnect Login class allows the sign in with google functionality.
Login
LoginCallback
Package com.codename1.social
54
Package com.codename1.share
Sharing services, that can be registered on the ShareButton
See: Description
Class
EmailShare
Description
Email sharing service.
SMSShare
Package com.codename1.share
55
Package com.codename1.push
Push notification support using either device specific protocols when available
See: Description
Interface
PushCallback
Description
This callback interface is invoked when a push notification is received by the
application.
Class
Push
Description
Utility class for sending a push message to a different device through the Codename One
push servers.
Package com.codename1.push
56
Package com.codename1.processing
IO Related tools and utilities, e.g.
See: Description
Class
Result
Description
An evaluator for a very small expression language to extract primitive types from structured
information.
Package com.codename1.processing
57
Package com.codename1.payment
In-App Billing/Purchase API's are abstracted by this package.
See: Description
Interface
Description
PurchaseCallback
Callback interface that the main class must implement in order for
in-app-purchasing to work.
RestoreCallback
Callback interface that the main class must implement in order for the restore
option of in-app-purchasing to work.
Class
Description
Product
Purchase
Represents the status of in-app-purchase goods, this class provides information about
products purchased by a user as well as the ability to purchase additional products.
Package com.codename1.payment
58
Package com.codename1.notifications
Interface
Description
LocalNotificationCallback An interface that can be implemented by the application's main class (i.e.
Class
Description
LocalNotification Local notifications are user notifications that are scheduled by the app itself.
Package com.codename1.notifications
59
Package com.codename1.messaging
This API allows to send e-mail messages through underlying platforms e-mail clients.
See: Description
Class
Description
Package com.codename1.messaging
60
Package com.codename1.media
Video and audio playback support are handled within this package using the Media/Media manager APIs.
See: Description
Interface
Media
Description
Media control interface allows for media playback, recording.
Class
Description
Allow us to create objects using String URI's or with a stream to the media data.
Notice that the underlying platforms contains the actual codecs, therefore you need
MediaManager
to play common media file types such as mp3, mp4 to successfully play them across
devices on all target platforms.
Package com.codename1.media
61
Package com.codename1.maps.providers
These are the map providers, currently http://www.openstreetmap.org/ is supported.
See: Description
Class
Description
GoogleMapsProvider
MapProvider
Package com.codename1.maps.providers
62
Package com.codename1.maps
The mapping API allows developers to use maps in their applications, add layers on top of the map and to
enhance the API with additional Layers, Providers and functionality.
See: Description
Interface
Description
Class
Description
BoundingBox
Coord
MapComponent
All communication with the map and layers should be done in WGS84, it takes care
of coordinates transformation.
Mercator
Projection
ProxyHttpTile
This Tile brings the tile image from a given http url.
Tile
Package com.codename1.maps
63
Package com.codename1.maps.layers
The Layers are elements that are displayed on the map.
See: Description
Interface
Layer
Description
a Layer interface.
Class
Description
AbstractLayer
ArrowLinesLayer
This class is responsible for painting arrows that indicates direction of walk on
map.
LinesLayer
PointLayer
Do not use this layer directly, you need to add this layer into a PointsLayer class
instance in order for it to work as expected!
PointsLayer
Package com.codename1.maps.layers
64
Package com.codename1.maker
This package is deprecated and will be removed in a coming revision
See: Description
Class
MakerPlugin
Description
Deprecated
this class is no longer supported and will be removed in an upcoming revision
Package com.codename1.maker
65
Package com.codename1.location
Simple abstraction of location services (GPS/Triangulation) providing user global positioning and monitoring
over such changes.
See: Description
Interface
Description
Class
Description
Geofence
Metadata for geofencing support that allows tracking user location in the
background while the app is inactive.
Location
Package com.codename1.location
66
Package com.codename1.l10n
The Localization API allows developers to adapt their applications to different geographic locales and
conventions.
See: Description
Class
DateFormat
Description
A class for parsing and formatting localisation sensitive dates, compatible with
Jave 6 SDK.
L10NManager
The localization manager allows adapting values for display in different locales
SimpleDateFormat
A class for parsing and formatting dates with a given pattern, compatible with
the Java 6 API.
Exception
Description
Package com.codename1.l10n
67
Package com.codename1.javascript
The Codename One JS Bridge package includes classes that facilitate the interaction between Java and
Javascript in a Codename One application.
See: Description
Interface
JSFunction
Description
The JSFunction interface allows you to implement functions in Java that can be called
from Javascript.
Class
Description
Requirements
The bridge will only run on platforms that include a native browser component. This includes iOS, Android,
Windows, Desktop & JavaScript at this time.
Usage
The JavascriptContext class lays the foundation by enabling you to call Javascript code directly from Java. It
provides automatic type conversion between Java and Javascript types as follows:
Java to Javascript
Java Type
Javascript Type
String
String
Double/Integer/Float/Long Number
Boolean
Boolean
JSObject
Object
null
null
Other
Not Allowed
Javascript to Java
Javascript Type Java Type
Number
Double
String
String
Boolean
Boolean
Object
JSObject
Function
JSObject
Array
JSObject
null
null
undefined
null
Note that this conversion table is more verbose than necessary, since Javascript functions and arrays are, in
fact Objects themselves, so those rows are redundant. All Javascript objects are converted to JSObjects.
Package com.codename1.javascript
68
Getting Started
In order to start interacting with a Javascript environment, you need to create a WebBrowser and load a page.
Then inside the WebBrowser's onLoad() handler, you can create a JavascriptContext on the internal
BrowserComponent object:
Getting Values
The JavascriptContext.get(String) method is used to get values from Javascript. It takes an arbitrary
Javascript expression, executes it, and returns the result, after converting it to the corresponding Java type.
E.g. if the result is a String, it will return a String and if it is a Number it will return a java Double object. If the
result is an Object, it will return a JSObject.
The following is a simple example that retrieves the document content, which is a string:
If you run this example in the simulator, you'll see something like the following:
Note: You don't see the WebBrowser in the background here due to a bug in the simulator. If you run this
example on a device, you will see the WebBrowser component in the background.
Returning Numeric Values
As mentioned in the conversion table above, numeric values are automatically converted to java.lang.Double
objects. The following example, returns the width and height properties of the window for use in Java.
Getting Started
69
Returning Objects
The previous examples involved only primitive return values. The JavascriptContext abstraction, in these
cases, doesn't offer a whole lot of added-value over just using the
BrowserComponent.executeJavascriptAndReturnString() method. The real value is when we are dealing with
objects.
The following example obtains a reference to the window object and wraps it in a proxy JSObject class so that
we can work directly with the window object:
This code produces the exact same result as the previous example. The difference is the intermediary step of
wrapping the window object in a JSObject, and obtaining the outerHeight and outerWidth properties directly
via that proxy object.
You can obtain a JSObject proxy for any Javascript object, even ones that you create on the fly. The following
example creates an anonymous object with some keys and values and uses a JSObject proxy to interact with
this object from Java.
The result is as follows:
Getting Values
70
See Working With Objects for more information about working with the JSObject class.
Returning Functions and Arrays
In Javascript, functions and arrays are just objects, so these are also encapsulated as JSObject proxies. See
Working with Arrays and Workin with Functions for more details on how to work with these values via the
JSObject interface.
Setting Values
Just as you can get values from Javascript using JavascriptContext's get() method, you can also set values
via JavascriptContext.set(String,Object).
The following is a simple example that sets the location, and causes it to redirect to a different page:
If you run this example, you should see your browser display the Codename One website after a redirect.
Getting Values
71
Setting Values
72
Assuming that the obj variable in Java is a proxy for the same obj variable in the javascript example.
In this case you may want to obtain the x coordinate of the nested position object. JSObject allows you to use
the dot '.' notation for referencing sub-properties like this. E.g.
Double x = (Double)obj.get("position.x")
This feature raises the issue of how, then, to access properties that contain a '.' in its name. E.g.
var obj = {
name : 'Steve',
position : {
x : 100,
y : 105,
z : -25
},
'position.x' : 200
}
In this example there is a top-level property named 'position.x' as well as a property at the component address
position.x. This is a contrived example that is meant to be somewhat confusing in order to demonstrate how to
73
74
Jays',
'George Bell', age : 31},
'Tony Fernandez', age : 34},
'Lloyd Moseby', age : 29}
Then assuming we have a JSObject proxy for this object, we could loop through the players array and output
the name and age of each player as follows:
JObject players = (JObject)obj.get("players");
int len = ((Double)players.get("length")).intValue();
for ( int i=0; i<len; i++){
JSObject player = (JSObject)players.get(i);
Log.p("Name : "+player.get("name")+" age : "+player.get("age"));
}
If you execute this code in the simulator, you'll see the following output in the console:
75
Running it on a device will yield similar output in the device log file.
Let's step through this code to see what is happening. First we create a new, empty javascript object and
wrap it in a JSObject proxy. Then we use the JSObject's JSObject.set(String,Object) method to add an
anonymous JSFunction object to it with the propery of "log". This step registers a method proxy on the
Javascript side that acts just like a normal javascript method, but which actually triggers the JSFunction's
JSFunction.apply(JSObject,Object[]) method.
We then set this logger object to the global javascript scope by making it a direct child of the window object.
Finally we issue a Javascript method call to logger.log(). This is what effectively calls the apply() method on
our JSFunction object.
Caveats
JSFunction callbacks are executed asynchronously so as to prevent deadlocks. This means that you
cannot return a value from this method using a return statement (hence the reason why the interface definition
for JSFunction.apply(JSObject,Object[]) is void.
If you want to return a value back to Javascript, then you'll need to do it by providing a callback
function as one of the parameters, and call this callback method from inside the
JSFunction.apply(JSObject,Object[]) method upon completion.
In this snippet, we start by obtaining a reference to the "window" object. We then add a method to this object
named "addAsync". This method is a JSFunction object that we implement inline. The apply() method of the
JSFunction object is the Java method that will be executed when the addAsync method is called from
Javascript. In this case the addAsync method expects three parameters:
1. The two numbers that are being added together.
2. A Javascript callback method that will be executed when completed and passed the result of the
addition as a parameter.
Notice that all numerical arguments are converted to Java Double objects, and the callback function is
converted to a JSObject object. Also notice the use of callback.call(), which just calls the callback as a
function itself. With this variant of the call() method, the window object is used as this. Notice also that we
76
Our HTML simply includes two text fields (to input the values to be added together), a button to initiate the
calculation, and a <span> tag where the result will be placed when the calculation is complete.
Finally it includes the AddAsync.js Javascript file (which is placed in the same directory as the AddAsync.html
file. Its contents are as follows:
document
.getElementById('calculate')
.addEventListener('click', function(){
var aField = document.getElementById('input1');
var bField = document.getElementById('input2');
var a = parseFloat(aField.value);
var b = parseFloat(bField.value);
window.addAsync(a, b, function(result){
document.getElementById('result').innerHTML = result;
});
}, true);
This script attaches an event handler to the calculate button that gets the values from the two input fields and
passes it to the window.addAsync() method for calculation. The addAsync() method is actually our java
JSFunction that we implemented earlier.
One small word about the placement of these files: This example is taken from a class
ca.weblite.codename1.tests.CodenameOneTests. The AddAsync.html and AddAsync.js files are included in
the same directory as the CodenameOneTests.java file ( i.e. /ca/weblite/codename1/tests). We used the
WebBrowser's setURL() method to load the AddAsync.html file from an absolute path using jar: protocol.
Currently this is the best way of loading local HTML files into a WebBrowser object (i.e. use the jar: protocol
and provide an absolute path).
The result of running this app is as follows:
77
78
79
Package com.codename1.io.tar
Tar support allowing us to package multiple separate files into a single package which is useful in supporting
hierarchies in a portable way.
See: Description
Class
Description
Octal
TarConstants
TarEntry
TarHeader
Header
TarInputStream
TarOutputStream
TarUtils
Package com.codename1.io.tar
80
Package com.codename1.io.services
Default WebService implementations
See: Description
Class
Description
CachedData
Cached data class for use with the cached data service
CachedDataService
Deprecated
this class uses an unconventional storage mechanism and has many
ImageDownloadService
issues, we recommend replacing it with the simpler and more powerful
URLImage or Util.dowloadFileTo* calls.
RSSService
Simple RSS read and parse request, to handle errors just subclass this and
override parsingError.
TwitterRESTService
Calls to the Twitter REST API can be performed via this class although
currently support for authentication isn't implemented due to the transition
to oAuth instead of basic authentication.
Package com.codename1.io.services
81
Package com.codename1.io
Codename One IO is intended as a componentized solution for IO operations that allows us to centralize IO
logic while maintaining a more portable approach for threads.
See: Description
Interface
Description
Externalizable
IOProgressListener
JSONParseCallback
The event based parser allows parsing without creating an object tree by
receiving callbacks to this class.
Class
Description
AccessToken
BufferedInputStream
Based on the buffered input stream from the JDK with some
minor tweaks to allow external classes to monitor stream status
and progress.
BufferedOutputStream
Based on the buffered output stream from the JDK with some
minor tweaks to allow external classes to monitor stream status
and progress.
CacheMap
CharArrayReader
ConnectionRequest
Cookie
CSVParser
FileSystemStorage
JSONParser
Fast and dirty parser for JSON content on the web, it essentially
returns a Map object containing the object fields mapped to their
values.
Log
MultipartRequest
NetworkEvent
Event containing more meta data for network events which may
be error events or an update for progress indication code.
NetworkManager
Oauth2
Preferences
Package com.codename1.io
82
Socket
SocketConnection
Storage
Util
WebServiceProxyCall
WebServiceProxyCall.WSDefinition
83
Package com.codename1.io.gzip
gzip support based on https://github.com/ymnk/jzlib
See: Description
Class
Description
Adler32
CRC32
Deflate
Deflater
DeflaterOutputStream
FilterInputStream
FilterOutputStream
GZConnectionRequest A connection request that can detect a GZipped response and parse it
GZIPHeader
GZIPInputStream
GZIPOutputStream
Inflater
InflaterInputStream
JZlib
ZStream
Deprecated
Not for public use in the future.
Exception
Description
GZIPException
Package com.codename1.io.gzip
84
Package com.codename1.facebook.ui
User interface for integrating with basic Facebook features currently mostly the Like button
See: Description
Class
Description
Generic "Like" button that enables us to submit a like to facebook, to get the post id
required for the like functionality you will need to use a tool such as:
LikeButton
https://developers.facebook.com/tools/explorer/?method=GET&path=me%2Fposts You
can ask it to list your posts and then seek the correct id within the returned JSON
Package com.codename1.facebook.ui
85
Package com.codename1.facebook
Legacy generic implementation of the Facebook API with simplified OAuth integration to allow social sharing.
See: Description
Class
Album
Description
This class represents a Facebook Photo Object
http://developers.facebook.com/docs/reference/api/album
Page
Photo
Post
User
Package com.codename1.facebook
86
Package com.codename1.db
SQLite support.
See: Description
Interface
Description
Cursor
Row
Class
Database
Description
This is a Database SQLite class, this class allows developers to connect to a database
and preform sql queries on the data.
Package com.codename1.db
87
Package com.codename1.contacts
Provides access to the contacts list from the device
See: Description
Class
Description
Address
Contact
This class represents a Contact information from the device Address Book
ContactsManager
This class uses as the Contacts manager of the device, it enables the possibility
To get the Contacts that are available on the device.
ContactsModel
This Contacts model is responsible for querying Contacts from the device and to
cache the data for faster usage
Package com.codename1.contacts
88
Package com.codename1.components
Generic elaborate components that make use of both UI elements and storage.
See: Description
Class
Description
Ads
FileEncodedImage
An encoded image that stores the actual data of the encoded image in a
disk file or resource and loads it only when necessary.
FileTreeModel
A tree model representing the file system as a whole, notice that this class
returns absolute file names which would result in an unreadable tree.
FloatingHint
ImageViewer
InfiniteProgress
InfiniteScrollAdapter
InteractionDialog
Unlike a regular dialog the interaction dialog only looks like a dialog, it
resides in the layered pane and can be used to implement features where
interaction with the background form is still required.
Since this code is designed for interaction all "dialogs" created thru here
are modless and never block.
MasterDetail
MediaPlayer
Video playback component with control buttons for back, play/pause and
forward buttons.
MultiButton
OnOffSwitch
Progress
ReplaceableImage
RSSReader
ScaleImageButton
ScaleImageLabel
ShareButton
The share button allows sharing a String or an image either thru the
defined sharing services or thru the native OS sharing support.
SliderBridge
SpanButton
SpanLabel
Package com.codename1.components
89
An encoded image that stores the actual data of the encoded image in
storage.
StorageImageAsync
Asynchronous storage image that loads in the background and not during
the paint cycle effectively not blocking the EDT drawing speed.
ToastBar
WebBrowser
90
Package com.codename1.codescan
Deprecated!!: Please use the cn1-codescan library instead.
See: Description
Interface
Description
ScanResult
Deprecated
Use the cn1-codescanner cn1lib.
Class
Description
CodeScanner
Deprecated
Use the cn1-codescanner cn1lib.
Package com.codename1.codescan
91
Package com.codename1.cloud
Provides cloud related services such as storage, binding widgets to the cloud seamlessly so they can be
persisted easily.
See: Description
Interface
BindTarget
Description
Allows binding arbitrary components to data storage
Deprecated
CloudResponse<T> the cloud storage API is no longer supported, we recommend switching to a
solution such as parse4cn1
CustomProperty
Deprecated
the cloud storage API is no longer supported, we recommend switching to a
solution such as parse4cn1
Class
Description
Deprecated
CloudImageProperty the cloud storage API is no longer supported, we recommend switching to a
solution such as parse4cn1
CloudListModel
Deprecated
the cloud storage API is no longer supported, we recommend switching to a
solution such as parse4cn1
CloudObject
Deprecated
the cloud storage API is no longer supported, we recommend switching to a
solution such as parse4cn1
CloudPersona
Deprecated
the cloud storage API is no longer supported, we recommend switching to a
solution such as parse4cn1
CloudStorage
Deprecated
this API is targeted for removal due to changes in Google App Engine API
support
Exception
Description
Deprecated
CloudException the cloud storage API is no longer supported, we recommend switching to a
solution such as parse4cn1
Package com.codename1.cloud
92
Package com.codename1.charts.views
Provides the classes that handle the actual rendering / drawing of the charts, based on the provided model
and renderer.
See: Description
Class
Description
AbstractChart
BarChart
BubbleChart
ClickableArea
CombinedXYChart
DialChart
DoughnutChart
LineChart
PieChart
PieMapper
PieSegment
RangeBarChart
RangeStackedBarChart
RoundChart
ScatterChart
TimeChart
XYChart
Enum
Description
Package com.codename1.charts.views
93
Package com.codename1.charts.util
Utility classes that provide helper methods used by most of the other packages.
See: Description
Class
Description
ColorUtil
MathHelper
NumberFormat
Package com.codename1.charts.util
94
Package com.codename1.charts.transitions
Class
Description
SeriesTransition
XYMultiSeriesTransition
XYSeriesTransition
XYValueSeriesTransition
Package com.codename1.charts.transitions
95
Package com.codename1.charts.renderers
Provides renderer classes that keep the chart rendering / drawing styles.
See: Description
Class
Description
BasicStroke
DefaultRenderer
DialRenderer
SimpleSeriesRenderer
XYMultipleSeriesRenderer
XYSeriesRenderer
Enum
Description
DialRenderer.Type
XYMultipleSeriesRenderer.Orientation
XYSeriesRenderer.FillOutsideLine.Type
Package com.codename1.charts.renderers
96
Package com.codename1.charts
The main ChartComponent Package
See: Description
Class
Description
97
The above screenshots were taken from the ChartsDemo app. Y ou can start playing with this app by
checking it out from our git repository.
How to Create A Chart
Adding a chart to your app involves four steps:
1. Build the model. You can construct a model (aka data set) for the chart using one of the existing
model classes in the com.codename1.charts.models package. Essentially, this is just where you add
the data that you want to display.
2. Set up a renderer. You can create a renderer for your chart using one of the existing renderer
classes in the com.codename1.charts.renderers package. The renderer allows you to specify how the
chart should look. E.g. the colors, fonts, styles, to use.
3. Create the Chart View. Use one of the existing view classes in the com.codename1.charts.views
package.
4. Create a com.codename1.charts,ChartComponent . In order to add your chart to the UI, you need to
wrap it in a com.codename1.charts,ChartComponent object.
You can check out the ChartsDemo app for specific examples, but here is a high level view of some code that
creates a Pie Chart.
The charts package is derived work from the excellent open source aChartEngine API.
98
Package com.codename1.charts.models
Provides the classes that handle the data values (data model) to be used by displaying the charts.
See: Description
Class
Description
CategorySeries
MultipleCategorySeries
Point
RangeCategorySeries
A series for the range category charts like the range bar.
SeriesSelection
TimeSeries
XYValueSeries
Package com.codename1.charts.models
99
Package com.codename1.charts.compat
Class
Canvas
Description
Deprecated
GradientDrawable
Paint
Deprecated
Paint.Align
Paint.Cap
Paint.Join
PathMeasure
Deprecated
Enum
Description
GradientDrawable.Orientation
Paint.Style
Package com.codename1.charts.compat
100
Package com.codename1.capture
Package for capturing photos, audio or video from the camera/microphone.
See: Description
Class
Description
Capture This is the main class for capturing media files from the device.
Package com.codename1.capture
101
Package com.codename1.analytics
The analytics API allows tracking your mobile application usage in the field to give you real-time data on how
your application is used.
See: Description
Class
Description
Package com.codename1.analytics
102
Package com.codename1.ads
A legacy banner Ads API.
See: Description
Class
Description
Package com.codename1.ads
103
Package
Description
com.codename1.ads
com.codename1.analytics
The analytics API allows tracking your mobile application usage in the
field to give you real-time data on how your application is used.
com.codename1.capture
com.codename1.charts
com.codename1.charts.models
Provides the classes that handle the data values (data model) to be used
by displaying the charts.
com.codename1.charts.renderers Provides renderer classes that keep the chart rendering / drawing styles.
com.codename1.charts.transitions
com.codename1.charts.util
Utility classes that provide helper methods used by most of the other
packages.
com.codename1.charts.views
Provides the classes that handle the actual rendering / drawing of the
charts, based on the provided model and renderer.
com.codename1.cloud
com.codename1.codescan
com.codename1.components
com.codename1.contacts
com.codename1.db
SQLite support.
com.codename1.facebook
com.codename1.facebook.ui
com.codename1.io
com.codename1.io.gzip
com.codename1.io.services
com.codename1.io.tar
com.codename1.javascript
com.codename1.l10n
com.codename1.location
com.codename1.maps
com.codename1.maps.layers
com.codename1.maps.providers
com.codename1.media
Video and audio playback support are handled within this package using
the Media/Media manager APIs.
com.codename1.messaging
104
com.codename1.processing
com.codename1.push
com.codename1.share
com.codename1.social
com.codename1.system
Low level calls into the Codename One system, including support for
making platform native API calls.
com.codename1.testing
com.codename1.ui
com.codename1.ui.animations
com.codename1.ui.events
com.codename1.ui.geom
com.codename1.ui.html
This package is deprecated and used only for legacy support, use the
WebBrowser component from the components package.
com.codename1.ui.layouts
com.codename1.ui.layouts.mig
com.codename1.ui.list
Lists are highly customizable and serve as the basis for ComboBox and
other components (such as carousels etc) they employ a similar MVC
approach to Swing including the renderer pattern.
com.codename1.ui.painter
com.codename1.ui.plaf
com.codename1.ui.spinner
com.codename1.ui.table
Table component for editing and viewing tabular data and arranging
Codename One components in a tabular form
com.codename1.ui.tree
com.codename1.ui.util
Utility features that are either too domain specific or don't "fit" into any
other packages including the Resource file format loading API.
com.codename1.ui.validation
com.codename1.util
com.codename1.util.regex
com.codename1.xml
The XML package allows parsing XML documents into DOM objects.
Painter
java.io
java.lang
java.lang.annotation
105
Codename One - Write Once Run Anywhere Native Mobile Apps Using
Java
Codename One allows Java developers to write their app once and have it work on all mobile devices (iOS,
Android etc.). It features a simulator, designer (visual theme/builder) and ports to multiple OS's.
Codename One is a mature open source project and its roots go back to Sun Microsystems (2006) where one
of its core underlying components was developed and open sourced.
Codename One is open source. This includes the libraries, native OS ports, resource editor & native VM
code. It also includes themes and separate related projects containing demos, skins etc.
You can understand more about how Codename One works and how the API fits into everything in this
stackoverflow answer.
Other Resources
Developer Guide
How Do I? - Get quick video answers and short tutorials for common questions
The Codename One Blog
cn1libs are extensions to Codename One that allow using device native functionality
Stack Overflow's Codename One Tag
Community Discussion Forum
The Open Source project on github
Build Codename One from source code
Codename One - Write Once Run Anywhere Native Mobile Apps Using Java
106
Class Vector<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.Vector<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, List<E>, RandomAccess
Direct Known Subclasses:
Stack
public class
extends AbstractList<E>
implements List<E>, RandomAccess
Vector is a variable size contiguous indexable array of objects. The size of the vector is the number of
objects it contains. The capacity of the vector is the number of objects it can hold.
Objects may be inserted at any position up to the size of the vector, thus increasing the size of the
vector. Objects at any position in the vector may be removed, thus shrinking the size of the Vector.
Objects at any position in the Vector may be replaced, which does not affect the vector's size.
The capacity of a vector may be specified when the vector is created. If the capacity of the vector is
exceeded, the capacity is increased (doubled by default).
See Also:
StringBuffer
Field Summary
Modifier and
Type
protected int
protected int
protected
Object[]
How many elements should be added to the vector when it is detected that
it needs to grow to accommodate extra entries.
elementCount
Constructor Summary
Constructor and Description
Vector()
Vector(int capacity)
Constructs a new vector using the specified capacity and capacity increment.
Class Vector<E>
107
Method Summary
Modifier and
Type
boolean
void
boolean
Adds the specified object into this vector at the specified location.
addAll(Collection<? extends E> collection)
Adds the objects in the specified collection to the end of this vector.
addAll(int location, Collection<? extends E> collection)
boolean
void
int
void
boolean
boolean
Returns the number of elements this vector can hold without growing.
clear()
void
E
Enumeration<E>
void
boolean
E
E
int
int
int
void
boolean
E
int
int
E
Method Summary
Ensures that this vector can hold the specified number of elements
without growing.
equals(Object object)
Compares the specified object to this vector and returns if they are equal.
firstElement()
Inserts the specified object into this vector at the specified location.
isEmpty()
108
remove(Object object)
boolean
boolean
Removes all elements from this vector, leaving the size zero and the
capacity unchanged.
void
removeElement(Object object)
boolean
void
Removes the element found at index position location from this Vector.
removeRange(int start, int end)
protected void
Removes the objects in the specified range from the start to the, but not
including, end index.
retainAll(Collection<?> collection)
boolean
Removes all objects from this vector that are not contained in the
specified collection.
set(int location, E object)
Replaces the element at the specified location in this vector with the
specified object.
Replaces the element at the specified location in this vector with the
specified object.
void
setSize(int length)
void
int
List<E>
Object[]
<T> T[]
Returns a List of the specified portion of this vector from the start index to
one less than the end index.
toArray()
String
void
Field Detail
109
How many elements should be added to the vector when it is detected that it needs
to grow to accommodate extra entries. If this value is zero or negative the size will be
doubled if an increase is needed.
Constructor Detail
Vector
public Vector()
Constructs a new vector using the specified capacity and capacity increment.
Parameters:
capacity - the initial capacity of the new vector.
capacityIncrement - the amount to increase the capacity when this vector is
full.
Throws:
IllegalArgumentException - if capacity is negative.
Vector
public Vector(Collection<? extends E> collection)
Method Detail
add
public void add(int location,
E object)
Field Detail
110
addAll
public boolean addAll(int location,
Collection<? extends E> collection)
Inserts the objects in the specified collection at the specified location in this vector.
The objects are inserted in the order in which they are returned from the Collection
iterator. The elements with an index equal or higher than location have their index
increased by the size of the added collection.
Specified by:
addAll in interface List<E>
Overrides:
addAll in class AbstractList<E>
Parameters:
location - the location to insert the objects.
collection - the collection of objects.
Returns:
true if this vector is modified, false otherwise.
Throws:
ArrayIndexOutOfBoundsException - if location < 0 or location > size().
addAll
public boolean addAll(Collection<? extends E> collection)
Adds the objects in the specified collection to the end of this vector.
Specified by:
addAll in interface Collection<E>
Specified by:
addAll in interface List<E>
Overrides:
addAll in class AbstractCollection<E>
Parameters:
collection - the collection of objects.
Returns:
true if this vector is modified, false otherwise.
Method Detail
111
Returns the number of elements this vector can hold without growing.
Returns:
the capacity of this vector.
See Also:
ensureCapacity(int), size()
clear
public void clear()
Method Detail
112
Attempts to copy elements contained by this Vector into the corresponding elements
of the supplied Object array.
Parameters:
elements - the Object array into which the elements of this vector are copied.
Throws:
IndexOutOfBoundsException - if elements is not big enough.
See Also:
#clone
elementAt
public E elementAt(int location)
elements
public Enumeration<E> elements()
Ensures that this vector can hold the specified number of elements without growing.
Parameters:
minimumCapacity - the minimum number of elements that this vector will hold
before growing.
See Also:
capacity()
equals
public boolean equals(Object object)
Compares the specified object to this vector and returns if they are equal. The object
must be a List which contains the same objects in the same order.
Specified by:
equals in interface Collection<E>
Specified by:
equals in interface List<E>
Overrides:
equals in class AbstractList<E>
Parameters:
object - the object to compare with this object
Returns:
true if the specified object is equal to this vector, false otherwise.
See Also:
hashCode()
Method Detail
113
hashCode
public int hashCode()
Returns an integer hash code for the receiver. Objects which are equal return the
same value for this method.
Specified by:
hashCode in interface Collection<E>
Specified by:
hashCode in interface List<E>
Overrides:
hashCode in class AbstractList<E>
Returns:
the receiver's hash.
See Also:
equals(java.lang.Object)
indexOf
public int indexOf(Object object)
Searches in this vector for the index of the specified object. The search for the object
starts at the beginning and moves towards the end of this vector.
Specified by:
indexOf in interface List<E>
Overrides:
indexOf in class AbstractList<E>
Parameters:
object - the object to find in this vector.
Returns:
the index in this vector of the specified element, -1 if the element isn't found.
See Also:
contains(java.lang.Object), lastIndexOf(Object), lastIndexOf(Object,
int)
indexOf
public int indexOf(Object object,
int location)
Method Detail
114
insertElementAt
public void insertElementAt(E object,
int location)
Inserts the specified object into this vector at the specified location. This object is
inserted before any previous element at the specified location. All elements with an
index equal or greater than location have their index increased by 1. If the location is
equal to the size of this vector, the object is added at the end.
Parameters:
object - the object to insert in this vector.
location - the index at which to insert the element.
Throws:
ArrayIndexOutOfBoundsException - if location < 0 || location > size().
See Also:
addElement(E), size()
isEmpty
public boolean isEmpty()
lastElement
public E lastElement()
Searches in this vector for the index of the specified object. The search for the object
starts at the end and moves towards the start of this vector.
Specified by:
lastIndexOf in interface List<E>
Overrides:
lastIndexOf in class AbstractList<E>
Parameters:
object - the object to find in this vector.
Method Detail
115
Searches in this vector for the index of the specified object. The search for the object
starts at the specified location and moves towards the start of this vector.
Parameters:
object - the object to find in this vector.
location - the index at which to start searching.
Returns:
the index in this vector of the specified element, -1 if the element isn't found.
Throws:
ArrayIndexOutOfBoundsException - if location >= size().
See Also:
contains(java.lang.Object), indexOf(Object), indexOf(Object, int)
remove
public E remove(int location)
Removes the object at the specified location from this vector. All elements with an
index bigger than location have their index decreased by 1.
Specified by:
remove in interface List<E>
Overrides:
remove in class AbstractList<E>
Parameters:
location - the index of the object to remove.
Returns:
the removed object.
Throws:
IndexOutOfBoundsException - if location < 0 || location >= size().
remove
public boolean remove(Object object)
Removes the first occurrence, starting at the beginning and moving towards the end,
of the specified object from this vector. All elements with an index bigger than the
element that gets removed have their index decreased by 1.
Specified by:
remove in interface Collection<E>
Specified by:
remove in interface List<E>
Overrides:
remove in class AbstractCollection<E>
Parameters:
object - the object to remove from this vector.
Returns:
true if the specified object was found, false otherwise.
See Also:
removeAllElements(), removeElementAt(int), size()
removeAll
public boolean removeAll(Collection<?> collection)
Removes all occurrences in this vector of each object in the specified Collection.
Specified by:
removeAll in interface Collection<E>
Specified by:
removeAll in interface List<E>
Overrides:
removeAll in class AbstractCollection<E>
Method Detail
116
Returns:
true
See Also:
remove(Object), contains(Object)
removeAllElements
public void removeAllElements()
Removes all elements from this vector, leaving the size zero and the capacity
unchanged.
See Also:
isEmpty(), size()
removeElement
public boolean removeElement(Object object)
Removes the first occurrence, starting at the beginning and moving towards the end,
of the specified object from this vector. All elements with an index bigger than the
element that gets removed have their index decreased by 1.
Parameters:
object - the object to remove from this vector.
Returns:
true if the specified object was found, false otherwise.
See Also:
removeAllElements(), removeElementAt(int), size()
removeElementAt
public void removeElementAt(int location)
Removes the element found at index position location from this Vector. All elements
with an index bigger than location have their index decreased by 1.
Parameters:
location - the index of the element to remove.
Throws:
ArrayIndexOutOfBoundsException - if location < 0 || location >= size().
See Also:
removeElement(java.lang.Object), removeAllElements(), size()
removeRange
protected void removeRange(int start,
int end)
Removes the objects in the specified range from the start to the, but not including,
end index. All elements with an index bigger than or equal to end have their index
decreased by end - start.
Overrides:
removeRange in class AbstractList<E>
Parameters:
start - the index at which to start removing.
end - the index one past the end of the range to remove.
Throws:
IndexOutOfBoundsException - if start < 0, start > end or end > size().
retainAll
public boolean retainAll(Collection<?> collection)
Removes all objects from this vector that are not contained in the specified collection.
Specified by:
retainAll in interface Collection<E>
Specified by:
retainAll in interface List<E>
Overrides:
retainAll in class AbstractCollection<E>
Parameters:
collection - the collection of objects to retain.
Method Detail
117
See Also:
remove(Object)
set
public E set(int location,
E object)
Replaces the element at the specified location in this vector with the specified object.
Specified by:
set in interface List<E>
Overrides:
set in class AbstractList<E>
Parameters:
location - the index at which to put the specified object.
object - the object to add to this vector.
Returns:
the previous element at the location.
Throws:
ArrayIndexOutOfBoundsException - if location < 0 || location >= size().
See Also:
size()
setElementAt
public void setElementAt(E object,
int location)
Replaces the element at the specified location in this vector with the specified object.
Parameters:
object - the object to add to this vector.
location - the index at which to put the specified object.
Throws:
ArrayIndexOutOfBoundsException - if location < 0 || location >= size().
See Also:
size()
setSize
public void setSize(int length)
Sets the size of this vector to the specified size. If there are more than length
elements in this vector, the elements at end are lost. If there are less than length
elements in the vector, the additional elements contain null.
Parameters:
length - the new size of this vector.
See Also:
size()
size
public int size()
Method Detail
118
Returns a List of the specified portion of this vector from the start index to one less
than the end index. The returned List is backed by this vector so changes to one are
reflected by the other.
Specified by:
subList in interface List<E>
Overrides:
subList in class AbstractList<E>
Parameters:
start - the index at which to start the sublist.
end - the index one past the end of the sublist.
Returns:
a List of a portion of this vector.
Throws:
IndexOutOfBoundsException - if start < 0 or end > size().
IllegalArgumentException - if start > end.
toArray
public Object[] toArray()
Returns an array containing all elements contained in this vector. If the specified
array is large enough to hold the elements, the specified array is used, otherwise an
array of the same type is created. If the specified array is used and is larger than this
vector, the array element following the collection elements is set to null.
Specified by:
toArray in interface Collection<E>
Specified by:
toArray in interface List<E>
Overrides:
toArray in class AbstractList<E>
Parameters:
contents - the array to fill.
Returns:
an array of the elements from this vector.
Throws:
ArrayStoreException - if the type of an element in this vector cannot be
stored in the type of the specified array.
toString
public String toString()
Method Detail
119
Method Detail
120
Class TreeSet<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractSet<E>
java.util.TreeSet<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, NavigableSet<E>, Set<E>, SortedSet<E>
public class
extends AbstractSet<E>
implements NavigableSet<E>
TreeSet is an implementation of SortedSet. All optional operations (adding and removing) are
supported. The elements can be any objects which are comparable to each other either using their
natural order or a specified Comparator.
Since:
1.2
Constructor Summary
Constructor and Description
TreeSet()
TreeSet(SortedSet<E> set)
Constructs a new instance of TreeSet containing the elements of the specified SortedSet
and using the same Comparator.
Method Summary
Modifier and Type
boolean
boolean
void
Comparator<?
super E>
boolean
Iterator<E>
NavigableSet<E>
Class TreeSet<E>
Answers the smallest element bigger than or equal to the specified one,
or null if no such element.
clear()
specified object.
descendingIterator()
121
Answers the biggest element less than or equal to the specified one, or
null if no such element.
headSet(E end)
SortedSet<E>
NavigableSet<E>
Answers the smallest element bigger than the specified one, or null if no
such element.
boolean
Iterator<E>
isEmpty()
Answers the biggest element less than the specified one, or null if no
such element.
pollFirst()
Deletes and answers the smallest element, or null if the set is empty.
pollLast()
Deletes and answers the biggest element, or null if the set is empty.
boolean
remove(Object object)
int
NavigableSet<E>
SortedSet<E>
SortedSet<E>
NavigableSet<E>
Method Summary
122
Constructor Detail
TreeSet
public TreeSet()
Constructs a new instance of TreeSet which uses natural ordering and containing the
unique elements in the specified collection.
Parameters:
collection - the collection of elements to add.
Throws:
ClassCastException - when an element in the collection does not implement
the Comparable interface, or the elements in the collection cannot be
compared.
TreeSet
public TreeSet(Comparator<? super E> comparator)
Constructs a new empty instance of TreeSet which uses the specified comparator.
Parameters:
comparator - the comparator to use.
TreeSet
public TreeSet(SortedSet<E> set)
Method Detail
add
public boolean add(E object)
123
handle null.
addAll
public boolean addAll(Collection<? extends E> collection)
Method Detail
124
iterator
public Iterator<E> iterator()
descendingIterator
public Iterator<E> descendingIterator()
remove
public boolean remove(Object object)
Method Detail
125
Deletes and answers the smallest element, or null if the set is empty.
Specified by:
pollFirst in interface NavigableSet<E>
Returns:
the smallest element, or null if the set is empty
Since:
1.6
See Also:
NavigableSet.pollFirst()
pollLast
public E pollLast()
Deletes and answers the biggest element, or null if the set is empty.
Specified by:
pollLast in interface NavigableSet<E>
Returns:
the biggest element, or null if the set is empty
Since:
1.6
See Also:
NavigableSet.pollLast()
higher
public E higher(E e)
Method Detail
126
lower
public E lower(E e)
Answers the biggest element less than the specified one, or null if no such element.
Specified by:
lower in interface NavigableSet<E>
Parameters:
e - the specified element
Returns:
the biggest element less than the specified one, or null if no such element
Since:
1.6
See Also:
NavigableSet.lower(java.lang.Object)
ceiling
public E ceiling(E e)
Answers the smallest element bigger than or equal to the specified one, or null if no
such element.
Specified by:
ceiling in interface NavigableSet<E>
Parameters:
e - the specified element
Returns:
the smallest element bigger than or equal to the specified one, or null if no
such element
Since:
1.6
See Also:
NavigableSet.ceiling(java.lang.Object)
floor
public E floor(E e)
Answers the biggest element less than or equal to the specified one, or null if no such
element.
Specified by:
floor in interface NavigableSet<E>
Parameters:
e - the specified element
Returns:
the biggest element less than or equal to the specified one, or null if no such
element
Since:
1.6
See Also:
NavigableSet.floor(java.lang.Object)
Method Detail
127
subSet
public NavigableSet<E> subSet(E start,
boolean startInclusive,
E end,
boolean endInclusive)
Answers a NavigableSet of the specified portion of this set which contains elements
greater (or equal to, depends on startInclusive) the start element but less than (or
equal to, depends on endInclusive) the end element. The returned NavigableSet is
backed by this set so changes to one are reflected by the other.
Specified by:
subSet in interface NavigableSet<E>
Parameters:
start - the start element
startInclusive - true if the start element is in the returned set
end - the end element
endInclusive - true if the end element is in the returned set
Returns:
the subset
Since:
1.6
See Also:
NavigableSet.subSet(Object, boolean, Object, boolean)
headSet
public NavigableSet<E> headSet(E end,
boolean endInclusive)
Answers a NavigableSet of the specified portion of this set which contains elements
less than (or equal to, depends on endInclusive) the end element. The returned
NavigableSet is backed by this set so changes to one are reflected by the other.
Specified by:
headSet in interface NavigableSet<E>
Parameters:
end - the end element
endInclusive - true if the end element is in the returned set
Returns:
the subset
Since:
1.6
See Also:
NavigableSet.headSet(Object, boolean)
tailSet
public NavigableSet<E> tailSet(E start,
boolean startInclusive)
Answers a NavigableSet of the specified portion of this set which contains elements
greater (or equal to, depends on startInclusive) the start element. The returned
NavigableSet is backed by this set so changes to one are reflected by the other.
Specified by:
Method Detail
128
in interface NavigableSet<E>
Parameters:
start - the start
startInclusive
element
- true if the start element is in the returned set
Returns:
the subset
Since:
1.6
See Also:
NavigableSet.tailSet(Object, boolean)
subSet
public SortedSet<E> subSet(E start,
E end)
Answers a SortedSet of the specified portion of this TreeSet which contains elements
greater or equal to the start element but less than the end element. The returned
SortedSet is backed by this TreeSet so changes to one are reflected by the other.
Specified by:
subSet in interface SortedSet<E>
Parameters:
start - the start element
end - the end element
Returns:
a subset where the elements are greater or equal to start and less than end
Throws:
ClassCastException - when the start or end object cannot be compared with
the elements in this TreeSet
NullPointerException - when the start or end object is null and the
comparator cannot handle null
headSet
public SortedSet<E> headSet(E end)
Answers a SortedSet of the specified portion of this TreeSet which contains elements
less than the end element. The returned SortedSet is backed by this TreeSet so
changes to one are reflected by the other.
Specified by:
headSet in interface SortedSet<E>
Parameters:
end - the end element
Returns:
a subset where the elements are less than end
Throws:
ClassCastException - when the end object cannot be compared with the
elements in this TreeSet
NullPointerException - when the end object is null and the comparator
cannot handle null
tailSet
public SortedSet<E> tailSet(E start)
Answers a SortedSet of the specified portion of this TreeSet which contains elements
greater or equal to the start element. The returned SortedSet is backed by this
TreeSet so changes to one are reflected by the other.
Specified by:
tailSet in interface SortedSet<E>
Parameters:
start - the start element
Returns:
a subset where the elements are greater or equal to start
Throws:
Method Detail
129
Method Detail
130
Class TreeMap<K,V>
java.lang.Object
java.util.AbstractMap<K,V>
java.util.TreeMap<K,V>
Type Parameters:
K - type of key
V - type of value
All Implemented Interfaces:
Map<K,V>, NavigableMap<K,V>, SortedMap<K,V>
public class
extends AbstractMap<K,V>
implements NavigableMap<K,V>
TreeMap is an implementation of SortedMap. All optional operations (adding and removing) are
supported. The values can be any objects. The keys can be any objects which are comparable to
each other either using their natural
Since:
1.2
Constructor Summary
Constructor and Description
TreeMap()
Method Summary
Modifier and Type
Map.Entry<K,V>
void
Class TreeMap<K,V>
Answers the smallest key greater than or equal to the specified key,
or null if no such key.
clear()
131
comparator()
Answers the entry with the smallest key, or null if the map is empty.
firstKey()
Map.Entry<K,V>
Answers an entry related with the biggest key less than or equal to
the specified key, or null if no such key.
floorKey(K key)
Answers the biggest key less than or equal to the specified key, or
null if no such key.
get(Object key)
SortedMap<K,V>
Returns a sorted map over a range of this sorted map with all keys
that are less than the specified endKey.
headMap(K end, boolean inclusive)
NavigableMap<K,V>
Answers a view of the head of the map whose keys are smaller
than (or equal to, depends on inclusive argument) endKey.
higherEntry(K key)
Map.Entry<K,V>
Answers an entry related with the smallest key greater than the
specified key, or null if no such key.
higherKey(K key)
Set<K>
Map.Entry<K,V>
K
Answers the smallest key greater than the specified key, or null if
no such key.
keySet()
Answers the entry with the biggest key, or null if the map is empty.
lastKey()
Map.Entry<K,V>
Answers an entry related with the biggest key less than the
specified key, or null if no such key.
lowerKey(K key)
NavigableSet<K>
Answers the biggest key less than the specified key, or null if no
such key.
navigableKeySet()
Map.Entry<K,V>
Deletes and answers the entry with the smallest key, or null if the
map is empty.
pollLastEntry()
Map.Entry<K,V>
V
void
Method Summary
Deletes and answers the entry with the biggest key, or null if the
map is empty.
put(K key, V value)
132
Removes the mapping with the specified key from this map.
size()
int
NavigableMap<K,V>
SortedMap<K,V>
Returns a sorted map over a range of this sorted map with all keys
greater than or equal to the specified startKey and less than the
specified endKey.
tailMap(K startKey)
SortedMap<K,V>
Returns a sorted map over a range of this sorted map with all keys
that are greater than or equal to the specified startKey.
tailMap(K start, boolean inclusive)
NavigableMap<K,V>
Collection<V>
Answers a view of the tail of the map whose keys are bigger than
(or equal to, depends on inclusive argument) startKey.
values()
Constructor Detail
TreeMap
public TreeMap()
Constructs a new TreeMap instance containing the mappings from the specified map
and using natural ordering.
Parameters:
map - the mappings to add.
Throws:
ClassCastException - if a key in the specified map does not implement the
Comparable interface, or if the keys in the map cannot be compared.
133
Constructs a new TreeMap instance containing the mappings from the specified
SortedMap and using the same comparator.
Parameters:
map - the mappings to add.
Method Detail
clear
public void clear()
Constructor Detail
134
Returns a set of the keys contained in this map. The set is backed by this map so
changes to one are reflected by the other. The set does not support adding.
Specified by:
keySet in interface Map<K,V>
Overrides:
keySet in class AbstractMap<K,V>
Returns:
a set of the keys.
lastKey
public K lastKey()
Method Detail
135
in this map.
NullPointerException - if
cannot handle null keys.
putAll
public void putAll(Map<? extends K,? extends V> map)
Copies all the mappings in the given map to this map. These mappings will replace
all mappings that this map had for any of the keys currently in the given map.
Specified by:
putAll in interface Map<K,V>
Overrides:
putAll in class AbstractMap<K,V>
Parameters:
map - the map to copy mappings from.
Throws:
ClassCastException - if a key in the specified map cannot be compared with
the keys in this map.
NullPointerException - if a key in the specified map is null and the
comparator cannot handle null keys.
remove
public V remove(Object key)
Removes the mapping with the specified key from this map.
Specified by:
remove in interface Map<K,V>
Overrides:
remove in class AbstractMap<K,V>
Parameters:
key - the key of the mapping to remove.
Returns:
the value of the removed mapping or null if no mapping for the specified key
was found.
Throws:
ClassCastException - if the specified key cannot be compared with the keys
in this map.
NullPointerException - if the specified key is null and the comparator
cannot handle null keys.
size
public int size()
Returns a collection of the values contained in this map. The collection is backed by
this map so changes to one are reflected by the other. The collection supports
remove, removeAll, retainAll and clear operations, and it does not support add or
addAll operations.
This method returns a collection which is the subclass of AbstractCollection. The
iterator method of this subclass returns a "wrapper object" over the iterator of map's
entrySet(). The size method wraps the map's size method and the contains method
Method Detail
136
in interface Map<K,V>
Overrides:
values in class AbstractMap<K,V>
Returns:
a collection of the values contained in this map.
firstEntry
public Map.Entry<K,V> firstEntry()
Answers the entry with the smallest key, or null if the map is empty.
Specified by:
firstEntry in interface NavigableMap<K,V>
Returns:
the entry with the smallest key, or null if the map is empty
Since:
1.6
See Also:
NavigableMap.firstEntry()
lastEntry
public Map.Entry<K,V> lastEntry()
Answers the entry with the biggest key, or null if the map is empty.
Specified by:
lastEntry in interface NavigableMap<K,V>
Returns:
the entry with the biggest key, or null if the map is empty
Since:
1.6
See Also:
NavigableMap.lastEntry()
pollFirstEntry
public Map.Entry<K,V> pollFirstEntry()
Deletes and answers the entry with the smallest key, or null if the map is empty.
Specified by:
pollFirstEntry in interface NavigableMap<K,V>
Returns:
the entry with the smallest key, or null if the map is empty
Since:
1.6
See Also:
NavigableMap.pollFirstEntry()
pollLastEntry
public Map.Entry<K,V> pollLastEntry()
Deletes and answers the entry with the biggest key, or null if the map is empty.
Specified by:
pollLastEntry in interface NavigableMap<K,V>
Returns:
the entry with the biggest key, or null if the map is empty
Since:
1.6
See Also:
NavigableMap.pollLastEntry()
Method Detail
137
Answers an entry related with the smallest key greater than the specified key, or null
if no such key.
Specified by:
higherEntry in interface NavigableMap<K,V>
Parameters:
key - the key
Returns:
the entry, or null if no such key
Since:
1.6
See Also:
NavigableMap.higherEntry(Object)
higherKey
public K higherKey(K key)
Answers the smallest key greater than the specified key, or null if no such key.
Specified by:
higherKey in interface NavigableMap<K,V>
Parameters:
key - the key
Returns:
the smallest key greater than key, or null if no such key
Since:
1.6
See Also:
NavigableMap.higherKey(Object)
lowerEntry
public Map.Entry<K,V> lowerEntry(K key)
Answers an entry related with the biggest key less than the specified key, or null if no
such key.
Specified by:
lowerEntry in interface NavigableMap<K,V>
Parameters:
key - the key
Returns:
the entry, or null if no such key
Since:
1.6
See Also:
NavigableMap.lowerEntry(Object)
lowerKey
public K lowerKey(K key)
Answers the biggest key less than the specified key, or null if no such key.
Specified by:
lowerKey in interface NavigableMap<K,V>
Parameters:
key - the key
Returns:
the biggest key less than key, or null if no such key
Since:
1.6
See Also:
NavigableMap.lowerKey(Object)
Method Detail
138
Answers an entry related with the smallest key greater than or equal to the specified
key, or null if no such key.
Specified by:
ceilingEntry in interface NavigableMap<K,V>
Parameters:
key - the key
Returns:
the entry, or null if no such key
Since:
1.6
See Also:
NavigableMap.ceilingEntry(java.lang.Object)
ceilingKey
public K ceilingKey(K key)
Answers the smallest key greater than or equal to the specified key, or null if no such
key.
Specified by:
ceilingKey in interface NavigableMap<K,V>
Parameters:
key - the key
Returns:
the smallest key greater than or equal to key, or null if no such key
Since:
1.6
See Also:
NavigableMap.ceilingKey(java.lang.Object)
floorEntry
public Map.Entry<K,V> floorEntry(K key)
Answers an entry related with the biggest key less than or equal to the specified key,
or null if no such key.
Specified by:
floorEntry in interface NavigableMap<K,V>
Parameters:
key - the key
Returns:
the entry, or null if no such key
Since:
1.6
See Also:
NavigableMap.floorEntry(Object)
floorKey
public K floorKey(K key)
Answers the biggest key less than or equal to the specified key, or null if no such key.
Specified by:
floorKey in interface NavigableMap<K,V>
Parameters:
key - the key
Returns:
the biggest key less than or equal to key, or null if no such key
Since:
1.6
See Also:
NavigableMap.floorKey(Object)
Method Detail
139
Returns a set containing all of the mappings in this map. Each mapping is an
instance of Map.Entry. As the set is backed by this map, changes in one will be
reflected in the other. It does not support adding operations.
Specified by:
entrySet in interface Map<K,V>
Specified by:
entrySet in class AbstractMap<K,V>
Returns:
a set of the mappings.
navigableKeySet
public NavigableSet<K> navigableKeySet()
descendingKeySet
public NavigableSet<K> descendingKeySet()
descendingMap
public NavigableMap<K,V> descendingMap()
subMap
public NavigableMap<K,V> subMap(K start,
boolean startInclusive,
K end,
boolean endInclusive)
Answers a view of part of the map whose keys is from startKey to endKey.
Specified by:
subMap in interface NavigableMap<K,V>
Parameters:
start - the start key
startInclusive - true if the start key is in the returned map
end - the end key
Method Detail
140
headMap
public NavigableMap<K,V> headMap(K end,
boolean inclusive)
Answers a view of the head of the map whose keys are smaller than (or equal to,
depends on inclusive argument) endKey.
Specified by:
headMap in interface NavigableMap<K,V>
Parameters:
end - the end key
inclusive - true if the end key is in the returned map
Returns:
the head-map view
Since:
1.6
See Also:
NavigableMap.headMap(Object, boolean)
tailMap
public NavigableMap<K,V> tailMap(K start,
boolean inclusive)
Answers a view of the tail of the map whose keys are bigger than (or equal to,
depends on inclusive argument) startKey.
Specified by:
tailMap in interface NavigableMap<K,V>
Parameters:
start - the start key
inclusive - true if the start key is in the returned map
Returns:
the tail-map view
Since:
1.6
See Also:
NavigableMap.tailMap(Object, boolean)
subMap
public SortedMap<K,V> subMap(K startKey,
K endKey)
Returns a sorted map over a range of this sorted map with all keys greater than or
equal to the specified startKey and less than the specified endKey. Changes to the
returned sorted map are reflected in this sorted map and vice versa.
Note: The returned map will not allow an insertion of a key outside the specified
range.
Specified by:
subMap
in interface SortedMap<K,V>
Parameters:
startKey - the low boundary of the range (inclusive).
endKey - the high boundary of the range (exclusive),
Returns:
a sorted map with the key from the specified range.
Throws:
Method Detail
141
if
this map is itself a sorted map over a range of another sorted map and the
specified range is outside of its range.
headMap
public SortedMap<K,V> headMap(K endKey)
Returns a sorted map over a range of this sorted map with all keys that are less than
the specified endKey. Changes to the returned sorted map are reflected in this sorted
map and vice versa.
Note: The returned map will not allow an insertion of a key outside the specified
range.
Specified by:
headMap
in interface SortedMap<K,V>
Parameters:
endKey - the high boundary of the range specified.
Returns:
a sorted map where the keys are less than endKey.
Throws:
ClassCastException - if the specified key cannot be compared with the keys
in this map.
NullPointerException - if the specified key is null and the comparator
cannot handle null keys.
IllegalArgumentException - if this map is itself a sorted map over a range of
another map and the specified key is outside of its range.
tailMap
public SortedMap<K,V> tailMap(K startKey)
Returns a sorted map over a range of this sorted map with all keys that are greater
than or equal to the specified startKey. Changes to the returned sorted map are
reflected in this sorted map and vice versa.
Note: The returned map will not allow an insertion of a key outside the specified
range.
Specified by:
tailMap
in interface SortedMap<K,V>
Parameters:
startKey - the low boundary of the range specified.
Returns:
a sorted map where the keys are greater or equal to startKey.
Throws:
ClassCastException - if the specified key cannot be compared with the keys
in this map.
NullPointerException - if the specified key is null and the comparator
cannot handle null keys.
IllegalArgumentException - if this map itself a sorted map over a range of
another map and the specified key is outside of its range.
Method Detail
142
Class TimerTask
java.lang.Object
java.util.TimerTask
All Implemented Interfaces:
Runnable
Constructor Summary
Modifier Constructor and Description
protected TimerTask()
Method Summary
Modifier and Type
boolean
cancel()
long
scheduledExecutionTime()
Constructor Detail
TimerTask
protected TimerTask()
Method Detail
cancel
public boolean cancel()
scheduledExecutionTime
public long scheduledExecutionTime()
Class TimerTask
143
Class Timer
java.lang.Object
java.util.Timer
public class
extends Object
Constructor Summary
Constructor and Description
Timer()
Method Summary
Modifier and Type
void
cancel()
void
void
void
void
void
void
Constructor Detail
Timer
public Timer()
Method Detail
cancel
public void cancel()
schedule
public void schedule(TimerTask task,
Date time)
schedule
public void schedule(TimerTask task,
Date firstTime,
long period)
Method Detail
144
schedule
public void schedule(TimerTask task,
long delay,
long period)
scheduleAtFixedRate
public void scheduleAtFixedRate(TimerTask task,
Date firstTime,
long period)
scheduleAtFixedRate
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Method Detail
145
Class TimeZone
java.lang.Object
java.util.TimeZone
TimeZone represents a time zone offset, and also figures out daylight savings. Typically, you get a
TimeZone using getDefault which creates a TimeZone based on the time zone where the program is
running. For example, for a program running in Japan, getDefault creates a TimeZone object based
on Japanese Standard Time. You can also get a TimeZone using getTimeZone along with a time
zone ID. For instance, the time zone ID for the Pacific Standard Time zone is "PST". So, you can get
a PST TimeZone object with: This class is a pure subset of the java.util.TimeZone class in JDK 1.3.
The only time zone ID that is required to be supported is "GMT". Apart from the methods and
variables being subset, the semantics of the getTimeZone() method may also be subset: custom IDs
such as "GMT-8:00" are not required to be supported. Version: CLDC 1.1 02/01/2002 (Based on JDK
1.3) See Also:Calendar, Date
Constructor Summary
Constructor and Description
TimeZone()
Method Summary
Modifier and
Type
static String[]
static TimeZone
String
abstract int
getOffset(int era, int year, int month, int day, int dayOfWeek,
int millis)
getRawOffset()
Constructor Detail
Class TimeZone
146
Method Detail
getAvailableIDs
public static String[] getAvailableIDs()
Gets the default TimeZone for this host. The source of the default TimeZone may
vary with implementation.
getID
public String getID()
era,
year,
month,
day,
dayOfWeek,
millis)
Gets offset, for current date, modified in case of daylight savings. This is the offset to
add *to* GMT to get local time. Gets the time zone offset, for current date, modified in
case of daylight savings. This is the offset to add *to* GMT to get local time. Assume
that the start and end month are distinct. This method may return incorrect results for
rules that start at the end of February (e.g., last Sunday in February) or the beginning
of March (e.g., March 1).
getRawOffset
public abstract int getRawOffset()
Constructor Detail
147
Class StringTokenizer
java.lang.Object
java.util.StringTokenizer
All Implemented Interfaces:
Enumeration<Object>
public class
extends Object
implements Enumeration<Object>
The StringTokenizer class allows an application to break a string into tokens by performing code
point comparison. The StringTokenizer methods do not distinguish among identifiers, numbers, and
quoted strings, nor do they recognize and skip comments.
The set of delimiters (the codepoints that separate tokens) may be specified either at creation time or
on a per-token basis.
An instance of StringTokenizer behaves in one of three ways, depending on whether it was created
with the returnDelimiters flag having the value true or false:
If returnDelims is false, delimiter code points serve to separate tokens. A token is a maximal
sequence of consecutive code points that are not delimiters.
If returnDelims is true, delimiter code points are themselves considered to be tokens. In this
case a token will be received for each delimiter code point.
A token is thus either one delimiter code point, or a maximal sequence of consecutive code points
that are not delimiters.
A StringTokenizer object internally maintains a current position within the string to be tokenized.
Some operations advance this current position past the code point processed.
A token is returned by taking a substring of the string that was used to create the StringTokenizer
object.
Here's an example of the use of the default delimiter StringTokenizer :
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
println(st.nextToken());
}
?",
Method Detail
148
Constructor Summary
Constructor and Description
StringTokenizer(String string)
Constructs a new StringTokenizer
delimiter.
StringTokenizer(String string, String delimiters)
Constructs a new StringTokenizer for the parameter string
Method Summary
Modifier and Type
int
boolean
hasMoreElements()
Returns true if unprocessed
tokens remain.
boolean
hasMoreTokens()
Returns true if unprocessed
tokens remain.
Object
String
String
nextElement()
Constructor Detail
StringTokenizer
public StringTokenizer(String string)
Constructs a new StringTokenizer for the parameter string using whitespace as the
delimiter. The returnDelimiters flag is set to false.
Parameters:
string - the string to be tokenized.
StringTokenizer
public StringTokenizer(String string,
String delimiters)
Constructs a new StringTokenizer for the parameter string using the specified
delimiters. The returnDelimiters flag is set to false. If delimiters is null, this
constructor doesn't throw an Exception, but later calls to some methods might throw
Class StringTokenizer
149
Constructs a new StringTokenizer for the parameter string using the specified
delimiters, returning the delimiters as tokens if the parameter returnDelimiters is
true. If delimiters is null this constructor doesn't throw an Exception, but later calls
to some methods might throw a NullPointerException.
Parameters:
string - the string to be tokenized.
delimiters - the delimiters to use.
returnDelimiters - true to return each delimiter as a token.
Method Detail
countTokens
public int countTokens()
Returns the next token in the string as an Object. This method is implemented in
order to satisfy the Enumeration interface.
Specified by:
nextElement in interface Enumeration<Object>
Returns:
next token in the string as an Object
Throws:
NoSuchElementException - if no tokens remain.
nextToken
public String nextToken()
Constructor Detail
150
- if no tokens remain.
nextToken
public String nextToken(String delims)
Returns the next token in the string as a String. The delimiters used are changed to
the specified delimiters.
Parameters:
delims - the new delimiters to use.
Returns:
next token in the string as a String.
Throws:
NoSuchElementException - if no tokens remain.
Method Detail
151
Class Stack<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.Vector<E>
java.util.Stack<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, List<E>, RandomAccess
public class
extends Vector<E>
Field Summary
Constructor Summary
Constructor and Description
Stack()
Method Summary
Modifier and
Type
boolean
Returns the element at the top of the stack without removing it.
pop()
Returns the element at the top of the stack and removes it.
push(E object)
Returns the index of the first occurrence of the object, starting from the
top of the stack.
int
Class Stack<E>
152
Constructor Detail
Stack
public Stack()
Method Detail
empty
public boolean empty()
Returns the element at the top of the stack without removing it.
Returns:
the element at the top of the stack.
Throws:
EmptyStackException - if the stack is empty.
See Also:
pop()
pop
public E pop()
Returns the element at the top of the stack and removes it.
Returns:
the element at the top of the stack.
Throws:
EmptyStackException - if the stack is empty.
See Also:
peek(), push(E)
push
public E push(E object)
153
Returns the index of the first occurrence of the object, starting from the top of the
stack.
Parameters:
o - the object to be searched.
Returns:
the index of the first occurrence of the object, assuming that the topmost
object on the stack has a distance of one.
Method Detail
154
Interface SortedSet<E>
All Superinterfaces:
Collection<E>, Iterable<E>, Set<E>
All Known Subinterfaces:
NavigableSet<E>
All Known Implementing Classes:
TreeSet
public interface
extends Set<E>
SortedSet is a Set which iterates over its elements in a sorted order. The order is determined either
by the elements natural ordering, or by a Comparator which is passed into a concrete implementation
at construction time. All elements in this set must be mutually comparable. The ordering in this set
must be consistent with equals of its elements.
See Also:
Comparator, Comparable
Method Summary
Modifier and
Type
Comparator<?
super E>
SortedSet<E>
headSet(E end)
Returns a SortedSet
SortedSet<E>
SortedSet<E>
Method Detail
comparator
Comparator<? super E> comparator()
Interface SortedSet<E>
155
Returns the first element in this SortedSet. The first element is the lowest element.
Returns:
the first element.
Throws:
NoSuchElementException - when this SortedSet is empty.
headSet
SortedSet<E> headSet(E end)
Returns the last element in this SortedSet. The last element is the highest element.
Returns:
the last element.
Throws:
NoSuchElementException - when this SortedSet is empty.
subSet
SortedSet<E> subSet(E start,
E end)
Method Detail
156
Method Detail
157
Interface SortedMap<K,V>
All Superinterfaces:
Map<K,V>
All Known Subinterfaces:
NavigableMap<K,V>
All Known Implementing Classes:
TreeMap
public interface
extends Map<K,V>
A map that has its keys ordered. The sorting is according to either the natural ordering of its keys or
the ordering given by a specified comparator.
Method Summary
Modifier and Type
Comparator<?
super K>
SortedMap<K,V>
Returns a sorted map over a range of this sorted map with all keys that
are less than the specified endKey.
lastKey()
SortedMap<K,V>
Returns a sorted map over a range of this sorted map with all keys
greater than or equal to the specified startKey and less than the
specified endKey.
tailMap(K startKey)
SortedMap<K,V>
Returns a sorted map over a range of this sorted map with all keys that
are greater than or equal to the specified startKey.
Method Detail
comparator
Comparator<? super K> comparator()
Interface SortedMap<K,V>
158
Returns a sorted map over a range of this sorted map with all keys that are less than
the specified endKey. Changes to the returned sorted map are reflected in this sorted
map and vice versa.
Note: The returned map will not allow an insertion of a key outside the specified
range.
Parameters:
endKey - the high boundary of the range specified.
Returns:
a sorted map where the keys are less than endKey.
Throws:
ClassCastException - if the class of the end key is inappropriate for this
sorted map.
NullPointerException - if the end key is null and this sorted map does not
support null keys.
IllegalArgumentException - if this map is itself a sorted map over a range of
another map and the specified key is outside of its range.
lastKey
K lastKey()
Returns a sorted map over a range of this sorted map with all keys greater than or
equal to the specified startKey and less than the specified endKey. Changes to the
returned sorted map are reflected in this sorted map and vice versa.
Note: The returned map will not allow an insertion of a key outside the specified
range.
Parameters:
startKey - the low boundary of the range (inclusive).
endKey - the high boundary of the range (exclusive),
Returns:
a sorted map with the key from the specified range.
Throws:
ClassCastException - if the class of the start or end key is inappropriate for
this sorted map.
NullPointerException - if the start or end key is null and this sorted map
does not support null keys.
IllegalArgumentException - if the start key is greater than the end key, or if
this map is itself a sorted map over a range of another sorted map and the
Method Detail
159
Returns a sorted map over a range of this sorted map with all keys that are greater
than or equal to the specified startKey. Changes to the returned sorted map are
reflected in this sorted map and vice versa.
Note: The returned map will not allow an insertion of a key outside the specified
range.
Parameters:
startKey - the low boundary of the range specified.
Returns:
a sorted map where the keys are greater or equal to startKey.
Throws:
ClassCastException - if the class of the start key is inappropriate for this
sorted map.
NullPointerException - if the start key is null and this sorted map does not
support null keys.
IllegalArgumentException - if this map itself a sorted map over a range of
another map and the specified key is outside of its range.
Method Detail
160
Interface Set<E>
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Subinterfaces:
NavigableSet<E>, SortedSet<E>
All Known Implementing Classes:
AbstractSet, HashSet, LinkedHashSet, TreeSet
public interface
extends Collection<E>
Method Summary
Modifier and
Type
boolean
boolean
void
boolean
boolean
Adds the objects in the specified collection which do not exist yet in this set.
clear()
boolean
int
boolean
Iterator<E>
boolean
boolean
Compares the specified object to this set, and returns true if they represent
the same object using a class specific comparison.
hashCode()
boolean
int
Object[]
<T> T[]
Interface Set<E>
Removes all objects from this set that are not contained in the specified
collection.
size()
161
Method Detail
add
boolean add(E object)
Adds the specified object to this set. The set is not modified if it already contains the
object.
Specified by:
add in interface Collection<E>
Parameters:
object - the object to add.
Returns:
true if this set is modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - when adding to this set is not
supported.
ClassCastException - when the class of the object is inappropriate for this
set.
IllegalArgumentException - when the object cannot be added to this set.
addAll
boolean addAll(Collection<? extends E> collection)
Adds the objects in the specified collection which do not exist yet in this set.
Specified by:
addAll in interface Collection<E>
Parameters:
collection - the collection of objects.
Returns:
true if this set is modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - when adding to this set is not
supported.
ClassCastException - when the class of an object is inappropriate for this set.
IllegalArgumentException - when an object cannot be added to this set.
clear
void clear()
Method Detail
162
in interface Collection<E>
Parameters:
collection
Returns:
if all objects in the specified collection are elements of this set, false
otherwise.
true
equals
boolean equals(Object object)
Compares the specified object to this set, and returns true if they represent the same
object using a class specific comparison. Equality for a set means that both sets have
the same size and the same elements.
Specified by:
equals in interface Collection<E>
Overrides:
equals in class Object
Parameters:
object - the object to compare with this object.
Returns:
boolean true if the object is the same as this object, and false if it is different
from this object.
See Also:
hashCode()
hashCode
int hashCode()
Returns the hash code for this set. Two set which are equal must return the same
value.
Specified by:
hashCode in interface Collection<E>
Overrides:
hashCode in class Object
Returns:
the hash code of this set.
See Also:
equals(java.lang.Object)
isEmpty
boolean isEmpty()
iterator
Iterator<E> iterator()
Returns an iterator on the elements of this set. The elements are unordered.
Specified by:
iterator in interface Collection<E>
Specified by:
iterator in interface Iterable<E>
Returns:
an iterator on the elements of this set.
See Also:
Iterator
Method Detail
163
Removes all objects from this set that are not contained in the specified collection.
Specified by:
retainAll in interface Collection<E>
Parameters:
collection - the collection of objects to retain.
Returns:
true if this set was modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - when removing from this set is
not supported.
size
int size()
Returns an array containing all elements contained in this set. If the specified array is
large enough to hold the elements, the specified array is used, otherwise an array of
Method Detail
164
the same type is created. If the specified array is used and is larger than this set, the
array element following the collection elements is set to null.
Specified by:
toArray in interface Collection<E>
Parameters:
array - the array.
Returns:
an array of the elements from this set.
Throws:
ArrayStoreException - when the type of an element in this set cannot be
stored in the type of the specified array.
See Also:
Collection.toArray(Object[])
Method Detail
165
Interface RandomAccess
All Known Implementing Classes:
ArrayList, Stack, Vector
public interface
RandomAccess is implemented by List implementations that support fast (usually constant time)
random access.
Interface RandomAccess
166
Class Random
java.lang.Object
java.util.Random
public class
extends Object
An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a
48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of
Computer Programming, Volume 2, Section 3.2.1.) If two instances of Random are created with the
same seed, and the same sequence of method calls is made for each, they will generate and return
identical sequences of numbers. In order to guarantee this property, particular algorithms are
specified for the class Random. Java implementations must use all the algorithms shown here for the
class Random, for the sake of absolute portability of Java code. However, subclasses of class
Random are permitted to use other algorithms, so long as they adhere to the general contracts for all
the methods. The algorithms implemented by class Random use a protected utility method that on
each invocation can supply up to 32 pseudorandomly generated bits. Since: JDK1.0, CLDC 1.0
Version: 12/17/01 (CLDC 1.1)
Constructor Summary
Constructor and Description
Random()
Creates a new random number generator using a single long seed: public Random(long
seed) { setSeed(seed); } Used by method next to hold the state of the pseudorandom
number generator.
Method Summary
Modifier and
Type
protected
int
double
float
Returns the next pseudorandom, uniformly distributed float value between 0.0
and 1.0 from this random number generator's sequence.
nextInt()
int
Returns the next pseudorandom, uniformly distributed int value from this
random number generator's sequence.
nextInt(int n)
int
long
void
Class Random
Returns the next pseudorandom, uniformly distributed long value from this
random number generator's sequence.
setSeed(long seed)
Sets the seed of this random number generator using a single long seed.
167
Constructor Detail
Random
public Random()
Creates a new random number generator. Its seed is initialized to a value based on
the current time: public Random() { this(System.currentTimeMillis()); } See
Also:System.currentTimeMillis()
Random
public Random(long seed)
Creates a new random number generator using a single long seed: public
Random(long seed) { setSeed(seed); } Used by method next to hold the state of the
pseudorandom number generator. Parameters:seed - the initial seed.See
Also:setSeed(long)
Method Detail
next
protected int next(int bits)
Generates the next pseudorandom number. Subclass should override this, as this is
used by all other methods. The general contract of next is that it returns an int value
and if the argument bits is between 1 and 32 (inclusive), then that many low-order
bits of the returned value will be (approximately) independently chosen bit values,
each of which is (approximately) equally likely to be 0 or 1. The method next is
implemented by class Random as follows: synchronized protected int next(int bits) {
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); return (int)(seed >>> (48
- bits)); } This is a linear congruential pseudorandom number generator, as defined by
D. H. Lehmer and described by Donald E. Knuth in Volume 2: , section 3.2.1.
nextDouble
public double nextDouble()
Returns the next pseudorandom, uniformly distributed double value between 0.0 and
1.0 from this random number generator's sequence. The general contract of
nextDouble is that one double value, chosen (approximately) uniformly from the
range 0.0d (inclusive) to 1.0d (exclusive), is pseudorandomly generated and
returned. All 253 possible float values of the form mx2-53 , where m is a positive
integer less than 253, are produced with (approximately) equal probability. The
method nextDouble is implemented by class Random as follows: public double
nextDouble() { return (((long)next(26) << 27) + next(27)) / (double)(1L << 53); } The
hedge "approximately" is used in the foregoing description only because the next
method is only approximately an unbiased source of independently chosen bits. If it
were a perfect source or randomly chosen bits, then the algorithm shown would
choose double values from the stated range with perfect uniformity. [In early versions
of Java, the result was incorrectly calculated as: return (((long)next(27) << 27) +
next(27)) / (double)(1L << 54); This might seem to be equivalent, if not better, but in
fact it introduced a large nonuniformity because of the bias in the rounding of
floating-point numbers: it was three times as likely that the low-order bit of the
significand would be 0 than that it would be 1! This nonuniformity probably doesn't
matter much in practice, but we strive for perfection.]
168
Returns the next pseudorandom, uniformly distributed float value between 0.0 and
1.0 from this random number generator's sequence. The general contract of
nextFloat is that one float value, chosen (approximately) uniformly from the range 0.0f
(inclusive) to 1.0f (exclusive), is pseudorandomly generated and returned. All 224
possible float values of the form mx 2-24, where m is a positive integer less
than 224 , are produced with (approximately) equal probability. The method nextFloat
is implemented by class Random as follows: public float nextFloat() { return next(24) /
((float)(1 << 24)); } The hedge "approximately" is used in the foregoing description
only because the next method is only approximately an unbiased source of
independently chosen bits. If it were a perfect source or randomly chosen bits, then
the algorithm shown would choose float values from the stated range with perfect
uniformity. [In early versions of Java, the result was incorrectly calculated as: return
next(30) / ((float)(1 << 30)); This might seem to be equivalent, if not better, but in fact
it introduced a slight nonuniformity because of the bias in the rounding of
floating-point numbers: it was slightly more likely that the low-order bit of the
significand would be 0 than that it would be 1.]
nextInt
public int nextInt()
Returns the next pseudorandom, uniformly distributed int value from this random
number generator's sequence. The general contract of nextInt is that one int value is
pseudorandomly generated and returned. All 232 possible int values are produced
with (approximately) equal probability. The method nextInt is implemented by class
Random as follows: public int nextInt() { return next(32); }
nextInt
public int nextInt(int n)
Returns the next pseudorandom, uniformly distributed long value from this random
number generator's sequence. The general contract of nextLong is that one long
value is pseudorandomly generated and returned. All 264 possible long values are
produced with (approximately) equal probability. The method nextLong is
implemented by class Random as follows: public long nextLong() { return
Method Detail
169
Sets the seed of this random number generator using a single long seed. The general
contract of setSeed is that it alters the state of this random number generator object
so as to be in exactly the same state as if it had just been created with the argument
seed as a seed. The method setSeed is implemented by class Random as follows:
synchronized public void setSeed(long seed) { this.seed = (seed ^ 0x5DEECE66DL)
& ((1L << 48) - 1); } The implementation of setSeed by class Random happens to use
only 48 bits of the given seed. In general, however, an overriding method may use all
64 bits of the long argument as a seed value.
Method Detail
170
Interface Queue<E>
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Subinterfaces:
Deque<E>
All Known Implementing Classes:
AbstractQueue, ArrayDeque, LinkedList, PriorityQueue
public interface
extends Collection<E>
This kind of collection provides advanced operations compared to basic collections, such as insertion,
extraction, and inspection.
Generally, a queue orders its elements by means of first-in-first-out. However, a priority queue orders
its elements according to a comparator specified or the elements' natural order. Furthermore, a stack
orders its elements last-in-first out.
A typical queue does not allow null to be inserted as its element, while some implementations such
as LinkedList allow it. But null should not be inserted even in these implementations, since the
method poll returns null to indicate that there is no element left in the queue.
does not provide blocking queue methods, which would block until the operation of the method
is allowed. See the BlockingQueue interface for information about blocking queue methods.
Queue
Method Summary
Modifier and
Type
Gets but does not remove the element at the head of the queue.
offer(E o)
boolean
Inserts the specified element into the queue provided that the condition
allows such an operation.
peek()
Gets but does not remove the element at the head of the queue.
poll()
Gets and removes the element at the head of the queue, or returns null if
there is no element in the queue.
remove()
Method Detail
offer
boolean offer(E o)
Interface Queue<E>
171
Gets and removes the element at the head of the queue, or returns null if there is no
element in the queue.
Returns:
the element at the head of the queue or null if there is no element in the
queue.
remove
E remove()
Gets and removes the element at the head of the queue. Throws a
NoSuchElementException if there is no element in the queue.
Returns:
the element at the head of the queue.
Throws:
NoSuchElementException - if there is no element in the queue.
peek
E peek()
Gets but does not remove the element at the head of the queue.
Returns:
the element at the head of the queue or null if there is no element in the
queue.
element
E element()
Gets but does not remove the element at the head of the queue. Throws a
NoSuchElementException if there is no element in the queue.
Returns:
the element at the head of the queue.
Throws:
NoSuchElementException - if there is no element in the queue.
Method Detail
172
Class PriorityQueue<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractQueue<E>
java.util.PriorityQueue<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, Queue<E>
public class
extends AbstractQueue<E>
A PriorityQueue holds elements on a priority heap, which orders the elements according to their
natural order or according to the comparator specified at construction time. If the queue uses natural
ordering, only elements that are comparable are permitted to be inserted into the queue.
The least element of the specified ordering is stored at the head of the queue and the greatest
element is stored at the tail of the queue.
A PriorityQueue is not synchronized. If multiple threads will have to access it concurrently, use the
PriorityBlockingQueue.
Constructor Summary
Constructor and Description
PriorityQueue()
Constructs a priority queue with the specified capacity and natural ordering.
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
Constructs a priority queue that contains the elements of another priority queue.
PriorityQueue(SortedSet<? extends E> c)
Method Summary
Modifier and Type
boolean
void
Comparator<?
super E>
boolean
Iterator<E>
boolean
Class PriorityQueue<E>
Gets the iterator of the priority queue, which will not return elements in
any specified ordering.
offer(E o)
173
boolean
remove(Object o)
int
Object[]
toArray()
<T> T[]
Returns all the elements in an array, and the type of the result array is
the type of the argument array.
Constructor Detail
PriorityQueue
public PriorityQueue()
Constructs a priority queue with the specified capacity and natural ordering.
Parameters:
initialCapacity - the specified capacity.
Throws:
IllegalArgumentException - if the initialCapacity is less than 1.
PriorityQueue
public PriorityQueue(int initialCapacity,
Comparator<? super E> comparator)
Method Summary
174
Constructs a priority queue that contains the elements of another priority queue. The
constructed priority queue has the initial capacity of 110% of the specified one. Both
priority queues have the same comparator.
Parameters:
c - the priority queue whose elements will be added to the priority queue to
be constructed.
PriorityQueue
public PriorityQueue(SortedSet<? extends E> c)
Constructs a priority queue that contains the elements of a sorted set. The
constructed priority queue has the initial capacity of 110% of the size of the sorted
set. The priority queue will have the same comparator as the sorted set.
Parameters:
c - the sorted set whose elements will be added to the priority queue to be
constructed.
Method Detail
iterator
public Iterator<E> iterator()
Gets the iterator of the priority queue, which will not return elements in any specified
ordering.
Specified by:
iterator in interface Iterable<E>
Specified by:
iterator in interface Collection<E>
Specified by:
iterator in class AbstractCollection<E>
Returns:
the iterator of the priority queue.
size
public int size()
Gets the size of the priority queue. If the size of the queue is greater than the
Integer.MAX, then it returns Integer.MAX.
Specified by:
size in interface Collection<E>
Specified by:
size in class AbstractCollection<E>
Returns:
the size of the priority queue.
Constructor Detail
175
offer
public boolean offer(E o)
Method Detail
176
toArray
public Object[] toArray()
Returns all the elements in an array. The result is a copy of all the elements.
Specified by:
toArray in interface Collection<E>
Overrides:
toArray in class AbstractCollection<E>
Returns:
the Array of all the elements
See Also:
AbstractCollection.toArray()
toArray
public <T> T[] toArray(T[] array)
Returns all the elements in an array, and the type of the result array is the type of the
argument array. If the argument array is big enough, the elements from the queue will
be stored in it(element immediately following the end of the queue is set to null, if
any); otherwise, it will return a new array with the size of the argument array and size
of the queue.
Specified by:
toArray in interface Collection<E>
Overrides:
toArray in class AbstractCollection<E>
Type Parameters:
T - the type of elements in the array
Parameters:
array - the array stores all the elements from the queue, if it has enough
space; otherwise, a new array of the same type and the size of the queue will
be used
Returns:
the Array of all the elements
Throws:
ArrayStoreException - if the type of the argument array is not compatible
with every element in the queue
NullPointerException - if the argument array is null
Method Detail
177
Method Detail
178
Interface Observer
public interface
Observer is
Observable
See Also:
Observable
Method Summary
Modifier and
Type
void
Method Detail
update
void update(Observable observable,
Object data)
Interface Observer
179
Class Observable
java.lang.Object
java.util.Observable
public class
extends Object
Observable is used to notify a group of Observer objects when a change occurs. On creation, the set
of observers is empty. After a change occurred, the application can call the notifyObservers()
method. This will cause the invocation of the update() method of all registered Observers. The order
of invocation is not specified. This implementation will call the Observers in the order they registered.
Subclasses are completely free in what order they call the update methods.
See Also:
Observer
Constructor Summary
Constructor and Description
Observable()
Method Summary
Modifier and
Type
void
protected
void
clearChanged()
int
void
void
boolean
hasChanged()
void
notifyObservers()
If hasChanged() returns true,
void
notifyObservers(Object data)
If hasChanged() returns true, calls
protected
void
setChanged()
Method Detail
180
Detail
Observable
public Observable()
Method Detail
addObserver
public void addObserver(Observer observer)
Adds the specified observer to the list of observers. If it is already registered, it is not
added a second time.
Parameters:
observer - the Observer to add.
clearChanged
protected void clearChanged()
Clears the changed flag for this Observable. After calling clearChanged(),
hasChanged() will return false.
countObservers
public int countObservers()
Removes the specified observer from the list of observers. Passing null won't do
anything.
Parameters:
observer - the observer to remove.
deleteObservers
public void deleteObservers()
If hasChanged() returns true, calls the update() method for every observer in the list
of observers using null as the argument. Afterwards, calls clearChanged().
Equivalent to calling notifyObservers(null).
notifyObservers
public void notifyObservers(Object data)
If hasChanged() returns true, calls the update() method for every Observer in the list
of observers using the specified argument. Afterwards calls clearChanged().
Constructor Detail
181
Parameters:
data
setChanged
protected void setChanged()
Sets the changed flag for this Observable. After calling setChanged(), hasChanged()
will return true.
Method Detail
182
Class NoSuchElementException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.util.NoSuchElementException
public class
extends RuntimeException
Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in
the enumeration. Since: JDK1.0, CLDC 1.0 Version: 12/17/01 (CLDC 1.1) See Also:Enumeration,
Enumeration.nextElement()
Constructor Summary
Constructor and Description
NoSuchElementException()
Method Summary
Constructor Detail
NoSuchElementException
public NoSuchElementException()
Class NoSuchElementException
183
Interface NavigableSet<E>
Type Parameters:
E - the type of element
All Superinterfaces:
Collection<E>, Iterable<E>, Set<E>, SortedSet<E>
All Known Implementing Classes:
TreeSet
public interface
extends SortedSet<E>
NavigableSet is a SortedSet with navigation methods answering the closest matches for specified
item.
Since:
1.6
Method Summary
Modifier and
Type
Iterator<E>
NavigableSet<E>
Answers the smallest element bigger than or equal to the specified one,
or null if no such element.
descendingIterator()
Answers the biggest element less than or equal to the specified one, or
null if no such element.
headSet(E end, boolean endInclusive)
NavigableSet<E>
Answers the smallest element bigger than the specified one, or null if no
such element.
lower(E e)
E
E
Answers the biggest element less than the specified one, or null if no
such element.
pollFirst()
Deletes and answers the smallest element, or null if the set is empty.
pollLast()
Deletes and answers the biggest element, or null if the set is empty.
subSet(E start, boolean startInclusive, E end,
boolean endInclusive)
NavigableSet<E>
NavigableSet<E>
Constructor Detail
184
Method Detail
pollFirst
E pollFirst()
Deletes and answers the smallest element, or null if the set is empty.
Returns:
the smallest element, or null if the set is empty
pollLast
E pollLast()
Deletes and answers the biggest element, or null if the set is empty.
Returns:
the biggest element, or null if the set is empty
higher
E higher(E e)
Answers the smallest element bigger than the specified one, or null if no such
element.
Parameters:
e - the specified element
Returns:
the smallest element bigger than the specified one, or null if no such element
Throws:
ClassCastException - if the element cannot be compared with the ones in the
set
NullPointerException - if the element is null and the set can not contain null
ceiling
E ceiling(E e)
Answers the smallest element bigger than or equal to the specified one, or null if no
such element.
Parameters:
e - the specified element
Returns:
the smallest element bigger than or equal to the specified one, or null if no
such element
Throws:
ClassCastException - if the element cannot be compared with the ones in the
set
NullPointerException - if the element is null and the set can not contain null
lower
E lower(E e)
Answers the biggest element less than the specified one, or null if no such element.
Parameters:
e - the specified element
185
Answers the biggest element less than or equal to the specified one, or null if no such
element.
Parameters:
e - the specified element
Returns:
the biggest element less than or equal to the specified one, or null if no such
element
Throws:
ClassCastException - if the element cannot be compared with the ones in the
set
NullPointerException - if the element is null and the set can not contain null
descendingIterator
Iterator<E> descendingIterator()
Answers a NavigableSet of the specified portion of this set which contains elements
greater (or equal to, depends on startInclusive) the start element but less than (or
equal to, depends on endInclusive) the end element. The returned NavigableSet is
backed by this set so changes to one are reflected by the other.
Parameters:
start - the start element
startInclusive - true if the start element is in the returned set
end - the end element
endInclusive - true if the end element is in the returned set
Returns:
the subset
Throws:
ClassCastException - when the start or end object cannot be compared with
the elements in this set
NullPointerException - when the start or end object is null and the set
cannot contain null
IllegalArgumentException - when the start is bigger than end; or start or end
is out of range and the set has a range
Method Detail
186
Answers a NavigableSet of the specified portion of this set which contains elements
less than (or equal to, depends on endInclusive) the end element. The returned
NavigableSet is backed by this set so changes to one are reflected by the other.
Parameters:
end - the end element
endInclusive - true if the end element is in the returned set
Returns:
the subset
Throws:
ClassCastException - when the end object cannot be compared with the
elements in this set
NullPointerException - when the end object is null and the set cannot
contain handle null
IllegalArgumentException - when end is out of range and the set has a
range
tailSet
NavigableSet<E> tailSet(E start,
boolean startInclusive)
Answers a NavigableSet of the specified portion of this set which contains elements
greater (or equal to, depends on startInclusive) the start element. The returned
NavigableSet is backed by this set so changes to one are reflected by the other.
Parameters:
start - the start element
startInclusive - true if the start element is in the returned set
Returns:
the subset
Throws:
ClassCastException - when the start object cannot be compared with the
elements in this set
NullPointerException - when the start object is null and the set cannot
contain null
IllegalArgumentException - when start is out of range and the set has a
range
Method Detail
187
Interface NavigableMap<K,V>
Type Parameters:
K - the type of key
V - the type of value
All Superinterfaces:
Map<K,V>, SortedMap<K,V>
All Known Implementing Classes:
TreeMap
public interface
extends SortedMap<K,V>
NavigableMap is a SortedMap with navigation methods answering the closest matches for specified
item.
Since:
1.6
Method Summary
Modifier and Type
Map.Entry<K,V>
Answers an entry related with the smallest key greater than or equal to
the specified key, or null if no such key.
ceilingKey(K key)
NavigableSet<K>
NavigableMap<K,V>
Map.Entry<K,V>
Answers the smallest key greater than or equal to the specified key, or
null if no such key.
descendingKeySet()
Answers the entry with the smallest key, or null if the map is empty.
floorEntry(K key)
Map.Entry<K,V>
Answers an entry related with the biggest key less than or equal to the
specified key, or null if no such key.
floorKey(K key)
Answers the biggest key less than or equal to the specified key, or null
if no such key.
headMap(K endKey, boolean inclusive)
NavigableMap<K,V>
Answers a view of the head of the map whose keys are smaller than
(or equal to, depends on inclusive argument) endKey.
higherEntry(K key)
Map.Entry<K,V>
Answers an entry related with the smallest key greater than the
specified key, or null if no such key.
higherKey(K key)
Answers the smallest key greater than the specified key, or null if no
such key.
Map.Entry<K,V>
lastEntry()
Interface NavigableMap<K,V>
188
Answers an entry related with the biggest key less than the specified
key, or null if no such key.
lowerKey(K key)
Answers the biggest key less than the specified key, or null if no such
key.
NavigableSet<K>
navigableKeySet()
Map.Entry<K,V>
Deletes and answers the entry with the smallest key, or null if the map
is empty.
pollLastEntry()
Map.Entry<K,V>
NavigableMap<K,V>
Deletes and answers the entry with the biggest key, or null if the map
is empty.
subMap(K startKey, boolean startInclusive, K endKey,
boolean endInclusive)
NavigableMap<K,V>
Answers a view of the tail of the map whose keys are bigger than (or
equal to, depends on inclusive argument) startKey.
Method Detail
firstEntry
Map.Entry<K,V> firstEntry()
Answers the entry with the smallest key, or null if the map is empty.
Returns:
the entry with the smallest key, or null if the map is empty
lastEntry
Map.Entry<K,V> lastEntry()
Answers the entry with the biggest key, or null if the map is empty.
Returns:
the entry with the biggest key, or null if the map is empty
pollFirstEntry
Map.Entry<K,V> pollFirstEntry()
Deletes and answers the entry with the smallest key, or null if the map is empty.
Returns:
the entry with the smallest key, or null if the map is empty
pollLastEntry
Map.Entry<K,V> pollLastEntry()
Deletes and answers the entry with the biggest key, or null if the map is empty.
Returns:
the entry with the biggest key, or null if the map is empty
Method Summary
189
Answers an entry related with the smallest key greater than or equal to the specified
key, or null if no such key.
Parameters:
key - the key
Returns:
the entry, or null if no such key
Throws:
ClassCastException - if the key cannot be compared with the keys in the map
NullPointerException - if the key is null and the map can not contain null key
ceilingKey
K ceilingKey(K key)
Answers the smallest key greater than or equal to the specified key, or null if no such
key.
Parameters:
key - the key
Returns:
the smallest key greater than or equal to key, or null if no such key
Throws:
ClassCastException - if the key cannot be compared with the keys in the map
NullPointerException - if the key is null and the map can not contain null key
higherEntry
Map.Entry<K,V> higherEntry(K key)
Answers an entry related with the smallest key greater than the specified key, or null
if no such key.
Parameters:
key - the key
Returns:
the entry, or null if no such key
Throws:
ClassCastException - if the key cannot be compared with the keys in the map
NullPointerException - if the key is null and the map can not contain null key
higherKey
K higherKey(K key)
Answers the smallest key greater than the specified key, or null if no such key.
Parameters:
key - the key
Returns:
the smallest key greater than key, or null if no such key
Throws:
ClassCastException - if the key cannot be compared with the keys in the map
NullPointerException - if the key is null and the map can not contain null key
floorEntry
Map.Entry<K,V> floorEntry(K key)
Answers an entry related with the biggest key less than or equal to the specified key,
or null if no such key.
Parameters:
key - the key
Returns:
the entry, or null if no such key
Method Detail
190
floorKey
K floorKey(K key)
Answers the biggest key less than or equal to the specified key, or null if no such key.
Parameters:
key - the key
Returns:
the biggest key less than or equal to key, or null if no such key
Throws:
ClassCastException - if the key cannot be compared with the keys in the map
NullPointerException - if the key is null and the map can not contain null key
lowerEntry
Map.Entry<K,V> lowerEntry(K key)
Answers an entry related with the biggest key less than the specified key, or null if no
such key.
Parameters:
key - the key
Returns:
the entry, or null if no such key
Throws:
ClassCastException - if the key cannot be compared with the keys in the map
NullPointerException - if the key is null and the map can not contain null key
lowerKey
K lowerKey(K key)
Answers the biggest key less than the specified key, or null if no such key.
Parameters:
key - the key
Returns:
the biggest key less than key, or null if no such key
Throws:
ClassCastException - if the key cannot be compared with the keys in the map
NullPointerException - if the key is null and the map can not contain null key
navigableKeySet
NavigableSet<K> navigableKeySet()
Method Detail
191
Answers a view of part of the map whose keys is from startKey to endKey.
Parameters:
startKey - the start key
startInclusive - true if the start key is in the returned map
endKey - the end key
endInclusive - true if the end key is in the returned map
Returns:
the sub-map view
Throws:
ClassCastException - when the class of the start or end key is inappropriate
for this SubMap
NullPointerException - when the start or end key is null and this SortedMap
does not support null keys
IllegalArgumentException - when the start key is greater than the end key
headMap
NavigableMap<K,V> headMap(K endKey,
boolean inclusive)
Answers a view of the head of the map whose keys are smaller than (or equal to,
depends on inclusive argument) endKey.
Parameters:
endKey - the end key
inclusive - true if the end key is in the returned map
Returns:
the head-map view
Throws:
ClassCastException - when the class of the end key is inappropriate for this
SubMap
NullPointerException - when the end key is null and this SortedMap does
not support null keys
IllegalArgumentException - when the map is range-limited and end key is
out of the range of the map
tailMap
NavigableMap<K,V> tailMap(K startKey,
boolean inclusive)
Answers a view of the tail of the map whose keys are bigger than (or equal to,
depends on inclusive argument) startKey.
Parameters:
startKey - the start key
inclusive - true if the start key is in the returned map
Returns:
the tail-map view
Throws:
ClassCastException - when the class of the start key is inappropriate for this
SubMap
NullPointerException - when the start key is null and this SortedMap does
not support null keys
IllegalArgumentException - when the map is range-limited and start key is
out of the range of the map
Method Detail
192
Interface Map<K,V>
All Known Subinterfaces:
NavigableMap<K,V>, SortedMap<K,V>
All Known Implementing Classes:
AbstractMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, Properties, TreeMap,
WeakHashMap
public interface
A Map is a data structure consisting of a set of keys and values in which each key is mapped to a
single value. The class of the objects used as keys is declared when the Map is declared, as is the
class of the corresponding values.
A Map provides helper methods to iterate through all of the keys contained in it, as well as various
methods to access and update the key/value pairs.
Method Summary
Modifier and Type
void
boolean
containsKey(Object key)
Returns whether this Map contains
boolean
containsValue(Object value)
Returns whether this Map contains
Set<Map.Entry<K,V>>
entrySet()
Returns a Set
equals(Object object)
boolean
V
int
boolean
Set<K>
V
void
V
int
Collection<V>
Interface Map<K,V>
193
Method Detail
clear
void clear()
Returns a Set containing all of the mappings in this Map. Each mapping is an instance
of Map.Entry. As the Set is backed by this Map, changes in one will be reflected in the
other.
Returns:
a set of the mappings
equals
boolean equals(Object object)
Compares the argument to the receiver, and returns true if the specified object is a
Map and both Maps contain the same mappings.
Overrides:
equals in class Object
Parameters:
object - the Object to compare with this Object.
Returns:
boolean true if the Object is the same as this Object false if it is different
from this Object.
See Also:
hashCode(), entrySet()
get
V get(Object key)
Method Summary
194
Returns an integer hash code for the receiver. Objects which are equal return the
same value for this method.
Overrides:
hashCode in class Object
Returns:
the receiver's hash.
See Also:
equals(Object)
isEmpty
boolean isEmpty()
keySet
Set<K> keySet()
Returns a set of the keys contained in this Map. The Set is backed by this Map so
changes to one are reflected by the other. The Set does not support adding.
Returns:
a set of the keys.
put
V put(K key,
V value)
Method Detail
195
Returns a Collection of the values contained in this Map. The Collection is backed
by this Map so changes to one are reflected by the other. The Collection supports
Collection.remove(java.lang.Object),
Collection.removeAll(java.util.Collection<?>),
Collection.retainAll(java.util.Collection<?>), and Collection.clear()
operations, and it does not support Collection.add(E) or
Collection.addAll(java.util.Collection<? extends E>) operations.
This method returns a Collection which is the subclass of AbstractCollection. The
AbstractCollection.iterator() method of this subclass returns a "wrapper object"
over the iterator of this Map's entrySet(). The AbstractCollection.size() method
wraps this Map's size() method and the
AbstractCollection.contains(java.lang.Object) method wraps this Map's
containsValue(java.lang.Object) method.
The collection is created when this method is called at first time and returned in
response to all subsequent calls. This method may return different Collection when
multiple calls to this method, since it has no synchronization performed.
Returns:
a collection of the values contained in this map.
Method Detail
196
Interface Map.Entry<K,V>
All Known Implementing Classes:
AbstractMap.SimpleEntry, AbstractMap.SimpleImmutableEntry
Enclosing interface:
Map<K,V>
Method Summary
Modifier and
Type
Compares the specified object to this Map.Entry and returns if they are
equal.
boolean
getKey()
int
Sets the value of this entry to the specified value, replacing any existing
value.
Method Detail
equals
boolean equals(Object object)
Compares the specified object to this Map.Entry and returns if they are equal. To be
equal, the object must be an instance of Map.Entry and have the same key and
value.
Overrides:
equals in class Object
Parameters:
object - the Object to compare with this Object.
Returns:
true if the specified Object is equal to this Map.Entry, false otherwise.
See Also:
hashCode()
getKey
K getKey()
Interface Map.Entry<K,V>
197
Returns an integer hash code for the receiver. Object which are equal return the
same value for this method.
Overrides:
hashCode in class Object
Returns:
the receiver's hash code.
See Also:
equals(Object)
setValue
V setValue(V object)
Sets the value of this entry to the specified value, replacing any existing value.
Parameters:
object - the new value to set.
Returns:
object the replaced value of this entry.
Method Detail
198
Interface ListIterator<E>
All Superinterfaces:
Iterator<E>
public interface
extends Iterator<E>
An ListIterator is used to sequence over a List of objects. ListIterator can move backwards or forwards
through the list.
Method Summary
Modifier and
Type
void
Inserts the specified object into the list between next and previous.
boolean
boolean
hasNext()
int
int
void
Removes the last object returned by next or previous from the list.
set(E object)
Replaces the last object returned by next or previous with the specified
object.
void
Method Detail
add
void add(E object)
Inserts the specified object into the list between next and previous. The object
inserted will be the previous object.
Parameters:
object - the object to insert.
Throws:
java.lang.UnsupportedOperationException - if adding is not supported by
the list being iterated.
ClassCastException - if the class of the object is inappropriate for the list.
IllegalArgumentException - if the object cannot be added to the list.
Interface ListIterator<E>
199
hasPrevious
boolean hasPrevious()
next
E next()
nextIndex
int nextIndex()
previous
E previous()
previousIndex
int previousIndex()
Method Detail
200
Removes the last object returned by next or previous from the list.
Specified by:
remove in interface Iterator<E>
Throws:
java.lang.UnsupportedOperationException - if removing is not supported by
the list being iterated.
IllegalStateException - if next or previous have not been called, or remove
or add have already been called after the last call to next or previous.
set
void set(E object)
Replaces the last object returned by next or previous with the specified object.
Parameters:
object - the object to set.
Throws:
java.lang.UnsupportedOperationException - if setting is not supported by
the list being iterated
ClassCastException - if the class of the object is inappropriate for the list.
IllegalArgumentException - if the object cannot be added to the list.
IllegalStateException - if next or previous have not been called, or remove
or add have already been called after the last call to next or previous.
Method Detail
201
Interface List<E>
All Superinterfaces:
Collection<E>, Iterable<E>
All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, LinkedList, Stack, Vector
public interface
extends Collection<E>
A List is a collection which maintains an ordering for its elements. Every element in the List has an
index. Each element can thus be accessed by its index, with the first index being zero. Normally,
Lists allow duplicate elements, as compared to Sets, where elements have to be unique.
Method Summary
Modifier and
Type
boolean
void
boolean
Inserts the specified object into this List at the specified location.
addAll(Collection<? extends E> collection)
Adds the objects in the specified collection to the end of this List.
addAll(int location, Collection<? extends E> collection)
boolean
void
boolean
boolean
containsAll(Collection<?> collection)
Tests whether this List contains all objects
collection.
equals(Object object)
boolean
E
int
int
Compares the given object with the List, and returns true if they
represent the same object using a class specific comparison.
get(int location)
first occurrence.
boolean
Iterator<E>
int
isEmpty()
last occurrence.
ListIterator<E>
ListIterator<E>
Interface List<E>
listIterator()
Returns a List iterator
listIterator(int location)
202
boolean
Removes the first occurrence of the specified object from this List.
removeAll(Collection<?> collection)
Removes all occurrences in this List of
boolean
collection.
retainAll(Collection<?> collection)
Removes all objects from this List that are
boolean
collection.
set(int location, E object)
Replaces the element at the specified location in this List with the
specified object.
size()
int
List<E>
toArray()
Object[]
<T> T[]
Method Detail
add
void add(int location,
E object)
Inserts the specified object into this List at the specified location. The object is
inserted before the current element at the specified location. If the location is equal to
the size of this List, the object is added at the end. If the location is smaller than the
size of this List, then all elements beyond the specified location are moved by one
position towards the end of the List.
Parameters:
location - the index at which to insert.
object - the object to add.
Throws:
java.lang.UnsupportedOperationException - if adding to this List is not
supported.
ClassCastException - if the class of the object is inappropriate for this List.
IllegalArgumentException - if the object cannot be added to this List.
IndexOutOfBoundsException - if location < 0 || location > size()
add
boolean add(E object)
supported.
ClassCastException
Method Summary
203
addAll
boolean addAll(int location,
Collection<? extends E> collection)
Inserts the objects in the specified collection at the specified location in this List. The
objects are added in the order they are returned from the collection's iterator.
Parameters:
location - the index at which to insert.
collection - the collection of objects to be inserted.
Returns:
true if this List has been modified through the insertion, false otherwise (i.e.
if the passed collection was empty).
Throws:
java.lang.UnsupportedOperationException - if adding to this List is not
supported.
ClassCastException - if the class of an object is inappropriate for this List.
IllegalArgumentException - if an object cannot be added to this List.
IndexOutOfBoundsException - if location < 0 || > size()
addAll
boolean addAll(Collection<? extends E> collection)
Adds the objects in the specified collection to the end of this List. The objects are
added in the order in which they are returned from the collection's iterator.
Specified by:
addAll in interface Collection<E>
Parameters:
collection - the collection of objects.
Returns:
true if this List is modified, false otherwise (i.e. if the passed collection was
empty).
Throws:
java.lang.UnsupportedOperationException - if adding to this List is not
supported.
ClassCastException - if the class of an object is inappropriate for this List.
IllegalArgumentException - if an object cannot be added to this List.
clear
void clear()
Tests whether this List contains all objects contained in the specified collection.
Specified by:
Method Detail
204
in interface Collection<E>
Parameters:
collection
Returns:
if all objects in the specified collection are elements of this List, false
otherwise.
true
equals
boolean equals(Object object)
Compares the given object with the List, and returns true if they represent the same
object using a class specific comparison. For Lists, this means that they contain the
same elements in exactly the same order.
Specified by:
equals in interface Collection<E>
Overrides:
equals in class Object
Parameters:
object - the object to compare with this object.
Returns:
boolean true if the object is the same as this object, and false if it is different
from this object.
See Also:
hashCode()
get
E get(int location)
Returns the hash code for this List. It is calculated by taking each element' hashcode
and its position in the List into account.
Specified by:
hashCode in interface Collection<E>
Overrides:
hashCode in class Object
Returns:
the hash code of the List.
See Also:
Collection.equals(java.lang.Object)
indexOf
int indexOf(Object object)
Searches this List for the specified object and returns the index of the first
occurrence.
Parameters:
object - the object to search for.
Returns:
the index of the first occurrence of the object or -1 if the object was not found.
isEmpty
boolean isEmpty()
Method Detail
205
See Also:
size()
iterator
Iterator<E> iterator()
Returns an iterator on the elements of this List. The elements are iterated in the
same order as they occur in the List.
Specified by:
iterator in interface Collection<E>
Specified by:
iterator in interface Iterable<E>
Returns:
an iterator on the elements of this List.
See Also:
Iterator
lastIndexOf
int lastIndexOf(Object object)
Searches this List for the specified object and returns the index of the last
occurrence.
Parameters:
object - the object to search for.
Returns:
the index of the last occurrence of the object, or -1 if the object was not
found.
listIterator
ListIterator<E> listIterator()
Returns a List iterator on the elements of this List. The elements are iterated in the
same order that they occur in the List.
Returns:
a List iterator on the elements of this List
See Also:
ListIterator
listIterator
ListIterator<E> listIterator(int location)
Returns a list iterator on the elements of this List. The elements are iterated in the
same order as they occur in the List. The iteration starts at the specified location.
Parameters:
location - the index at which to start the iteration.
Returns:
a list iterator on the elements of this List.
Throws:
IndexOutOfBoundsException - if location < 0 || location > size()
See Also:
ListIterator
remove
E remove(int location)
Method Detail
206
Removes the first occurrence of the specified object from this List.
Specified by:
remove in interface Collection<E>
Parameters:
object - the object to remove.
Returns:
true if this List was modified by this operation, false otherwise.
Throws:
java.lang.UnsupportedOperationException - if removing from this List is
not supported.
removeAll
boolean removeAll(Collection<?> collection)
Removes all occurrences in this List of each object in the specified collection.
Specified by:
removeAll in interface Collection<E>
Parameters:
collection - the collection of objects to remove.
Returns:
true if this List is modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - if removing from this List is
not supported.
retainAll
boolean retainAll(Collection<?> collection)
Removes all objects from this List that are not contained in the specified collection.
Specified by:
retainAll in interface Collection<E>
Parameters:
collection - the collection of objects to retain.
Returns:
true if this List is modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - if removing from this List is
not supported.
set
E set(int location,
E object)
Replaces the element at the specified location in this List with the specified object.
This operation does not change the size of the List.
Parameters:
location - the index at which to put the specified object.
object - the object to insert.
Returns:
the previous element at the index.
Throws:
java.lang.UnsupportedOperationException - if replacing elements in this
List is not supported.
ClassCastException - if the class of an object is inappropriate for this List.
IllegalArgumentException - if an object cannot be added to this List.
IndexOutOfBoundsException - if location < 0 || >= size()
size
int size()
Method Detail
207
Returns a List of the specified portion of this List from the given start index to the
end index minus one. The returned List is backed by this List so changes to it are
reflected by the other.
Parameters:
start - the index at which to start the sublist.
end - the index one past the end of the sublist.
Returns:
a list of a portion of this List.
Throws:
IndexOutOfBoundsException - if start < 0, start > end or end > size()
toArray
Object[] toArray()
Returns an array containing all elements contained in this List. If the specified array
is large enough to hold the elements, the specified array is used, otherwise an array
of the same type is created. If the specified array is used and is larger than this List,
the array element following the collection elements is set to null.
Specified by:
toArray in interface Collection<E>
Parameters:
array - the array.
Returns:
an array of the elements from this List.
Throws:
ArrayStoreException - if the type of an element in this List cannot be stored
in the type of the specified array.
Method Detail
208
Class LinkedList<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.AbstractSequentialList<E>
java.util.LinkedList<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, Deque<E>, List<E>, Queue<E>
public class
extends AbstractSequentialList<E>
implements List<E>, Deque<E>
LinkedList is an implementation of List, backed by a linked list. All optional operations are supported,
adding, removing and replacing. The elements can be any objects.
Since:
1.2
Field Summary
Constructor Summary
Constructor and Description
LinkedList()
Method Summary
Modifier and
Type
boolean
void
boolean
Inserts the specified object into this LinkedList at the specified location.
addAll(Collection<? extends E> collection)
boolean
void
void
void
Class LinkedList<E>
209
contains(Object object)
Searches this LinkedList for
descendingIterator()
Gets but does not remove the element at the head of the queue.
get(int location)
int
int
Searches this list for the specified object and returns the index of the first
occurrence.
lastIndexOf(Object object)
Searches this LinkedList for the
listIterator(int location)
boolean
Inserts the specified element into the queue provided that the condition
allows such an operation.
offerFirst(E e)
boolean
Inserts an element at the head of this deque unless it would violate size
limit.
offerLast(E e)
boolean
E
E
E
Inserts an element at the tail of this deque unless it would violate size
limit.
peek()
Gets but does not remove the element at the head of the queue.
peekFirst()
E
E
E
Gets and removes the element at the head of the queue, or returns null
if there is no element in the queue.
pollFirst()
void
E
E
Pushes the element to the deque(at the head of the deque), just same
as addFirst(E).
remove()
boolean
E
boolean
Method Summary
210
boolean
removeLastOccurrence(Object o)
size()
int
Object[]
<T> T[]
Constructor Detail
LinkedList
public LinkedList()
Constructs a new instance of LinkedList that holds all of the elements contained in
the specified collection. The order of the elements in this new LinkedList will be
determined by the iteration order of collection.
Parameters:
collection - the collection of elements to add.
Method Detail
add
public void add(int location,
E object)
211
Inserts the objects in the specified collection at the specified location in this
LinkedList. The objects are added in the order they are returned from the collection's
iterator.
Specified by:
addAll in interface List<E>
Overrides:
addAll in class AbstractSequentialList<E>
Parameters:
location - the index at which to insert.
collection - the collection of objects
Returns:
true if this LinkedList is modified, false otherwise.
Throws:
ClassCastException - if the class of an object is inappropriate for this list.
IllegalArgumentException - if an object cannot be added to this list.
IndexOutOfBoundsException - if location < 0 || > size()
addAll
public boolean addAll(Collection<? extends E> collection)
Method Detail
212
Method Detail
213
Searches this LinkedList for the specified object and returns the index of the last
occurrence.
Specified by:
lastIndexOf in interface List<E>
Overrides:
lastIndexOf in class AbstractList<E>
Parameters:
object - the object to search for
Returns:
the index of the last occurrence of the object, or -1 if it was not found.
listIterator
public ListIterator<E> listIterator(int location)
Returns a ListIterator on the elements of this LinkedList. The elements are iterated
in the same order that they occur in the LinkedList. The iteration starts at the
specified location.
Specified by:
listIterator in interface List<E>
Specified by:
listIterator in class AbstractSequentialList<E>
Parameters:
location - the index at which to start the iteration
Returns:
a ListIterator on the elements of this LinkedList
Throws:
IndexOutOfBoundsException - if location < 0 || >= size()
See Also:
ListIterator
Method Detail
214
Method Detail
215
offerFirst
public boolean offerFirst(E e)
Inserts an element at the head of this deque unless it would violate size limit. It is
better than the addFirst(E) method in a size-limited deque, because the latter one
may fail to add the element only by throwing an exception.
Specified by:
offerFirst in interface Deque<E>
Parameters:
e - the element
Returns:
true if the operation succeeds or false if it fails.
Since:
1.6
See Also:
Deque.offerFirst(java.lang.Object)
offerLast
public boolean offerLast(E e)
Inserts an element at the tail of this deque unless it would violate size limit. It is better
than the addLast(E) method in a size-limited deque, because the latter one may fail
to add the element only by throwing an exception.
Specified by:
offerLast in interface Deque<E>
Parameters:
e - the element
Returns:
true if the operation succeeds or false if it fails
Since:
1.6
See Also:
Deque.offerLast(java.lang.Object)
peekFirst
public E peekFirst()
Gets but not removes the head element of this deque. This method returns null if the
deque is empty.
Specified by:
peekFirst in interface Deque<E>
Returns:
the head element or null if the deque is empty
Since:
1.6
See Also:
Deque.peekFirst()
peekLast
public E peekLast()
Gets but not removes the tail element of this deque. This method returns null if the
deque is empty.
Specified by:
peekLast in interface Deque<E>
Returns:
the tail element or null if the deque is empty
Since:
Method Detail
216
pollFirst
public E pollFirst()
Gets and removes the head element of this deque. This method returns null if the
deque is empty.
Specified by:
pollFirst in interface Deque<E>
Returns:
the head element or null if the deque is empty
Since:
1.6
See Also:
Deque.pollFirst()
pollLast
public E pollLast()
Gets and removes the tail element of this deque. This method returns null if the
deque is empty.
Specified by:
pollLast in interface Deque<E>
Returns:
the tail element or null if the deque is empty
Since:
1.6
See Also:
Deque.pollLast()
pop
public E pop()
push
public void push(E e)
Pushes the element to the deque(at the head of the deque), just same as addFirst(E).
Specified by:
push in interface Deque<E>
Parameters:
e - the element
Since:
1.6
See Also:
Deque.push(java.lang.Object)
removeFirstOccurrence
public boolean removeFirstOccurrence(Object o)
Removes the first equivalent element of the specified object. If the deque does not
contain the element, it is unchanged and returns false.
Specified by:
removeFirstOccurrence in interface Deque<E>
Parameters:
Method Detail
217
removeLastOccurrence
public boolean removeLastOccurrence(Object o)
Removes the last equivalent element of the specified object. If the deque does not
contain the element, it is unchanged and returns false.
Specified by:
removeLastOccurrence in interface Deque<E>
Parameters:
o - the element to be removed
Returns:
true if the operation succeeds or false if the deque does not contain the
element.
Since:
1.6
See Also:
Deque.removeLastOccurrence(java.lang.Object)
set
public E set(int location,
E object)
Replaces the element at the specified location in this LinkedList with the specified
object.
Specified by:
set in interface List<E>
Overrides:
set in class AbstractSequentialList<E>
Parameters:
location - the index at which to put the specified object.
object - the object to add.
Returns:
the previous element at the index.
Throws:
ClassCastException - if the class of an object is inappropriate for this list.
IllegalArgumentException - if an object cannot be added to this list.
IndexOutOfBoundsException - if location < 0 || >= size()
size
public int size()
Method Detail
218
Method Detail
219
Returns an array containing all elements contained in this LinkedList. If the specified
array is large enough to hold the elements, the specified array is used, otherwise an
array of the same type is created. If the specified array is used and is larger than this
LinkedList, the array element following the collection elements is set to null.
Specified by:
toArray in interface Collection<E>
Specified by:
toArray in interface List<E>
Overrides:
toArray in class AbstractList<E>
Parameters:
contents - the array.
Returns:
an array of the elements from this LinkedList.
Throws:
ArrayStoreException - if the type of an element in this LinkedList cannot be
stored in the type of the specified array.
Method Detail
220
Class LinkedHashSet<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractSet<E>
java.util.HashSet<E>
java.util.LinkedHashSet<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, Set<E>
public class
extends HashSet<E>
implements Set<E>
LinkedHashSet is a variant of HashSet. Its entries are kept in a doubly-linked list. The iteration order
is the order in which entries were inserted.
Null elements are allowed, and all the optional Set operations are supported.
Like HashSet, LinkedHashSet is not thread safe, so access by multiple threads must be synchronized
by an external mechanism such as Collections.synchronizedSet(Set).
Since:
1.4
Constructor Summary
Constructor and Description
LinkedHashSet()
collection.
LinkedHashSet(int capacity)
Constructs a new instance of LinkedHashSet
Method Summary
Class LinkedHashSet<E>
221
Constructor Detail
LinkedHashSet
public LinkedHashSet()
Constructs a new instance of LinkedHashSet with the specified capacity and load
factor.
Parameters:
capacity - the initial capacity.
loadFactor - the initial load factor.
LinkedHashSet
public LinkedHashSet(Collection<? extends E> collection)
222
Class LinkedHashMap<K,V>
java.lang.Object
java.util.AbstractMap<K,V>
java.util.HashMap<K,V>
java.util.LinkedHashMap<K,V>
All Implemented Interfaces:
Map<K,V>
public class
extends HashMap<K,V>
implements Map<K,V>
LinkedHashMap is a variant of HashMap. Its entries are kept in a doubly-linked list. The iteration order
is, by default, the order in which keys were inserted. Reinserting an already existing key doesn't
change the order. A key is existing if a call to containsKey would return true.
If the three argument constructor is used, and order is specified as true, the iteration will be in the
order that entries were accessed. The access order gets affected by put(), get(), putAll() operations,
but not by operations on the collection views.
Null elements are allowed, and all the optional map operations are supported.
Note: The implementation of LinkedHashMap is not synchronized. If one thread of several threads
accessing an instance modifies the map structurally, access to the map needs to be synchronized.
For insertion-ordered instances a structural modification is an operation that removes or adds an
entry. Access-ordered instances also are structurally modified by put(), get() and putAll() since these
methods change the order of the entries. Changes in the value of an entry are not structural changes.
The Iterator that can be created by calling the iterator method throws a
ConcurrentModificationException if the map is structurally changed while an iterator is used to
iterate over the elements. Only the remove method that is provided by the iterator allows for removal of
elements during iteration. It is not possible to guarantee that this mechanism works in all cases of
unsynchronized concurrent modification. It should only be used for debugging purposes.
Since:
1.4
Constructor Summary
Constructor and Description
LinkedHashMap()
Constructor Detail
223
Method Summary
Modifier and Type
void
boolean
Set<Map.Entry<K,V>>
containsValue(Object value)
Set<K>
Removes the mapping with the specified key from this map.
removeEldestEntry(Map.Entry<K,V> eldest)
protected boolean
Collection<V>
This method is queried from the put and putAll methods to check if
the eldest member of the map should be deleted before adding the
new member.
values()
Constructor Detail
LinkedHashMap
public LinkedHashMap()
Constructor Summary
224
Constructs a new LinkedHashMap instance with the specified capacity and load factor.
Parameters:
s - the initial capacity of this map.
lf - the initial load factor.
Throws:
IllegalArgumentException - when the capacity is less than zero or the load
factor is less or equal to zero.
LinkedHashMap
public LinkedHashMap(int s,
float lf,
boolean order)
Constructs a new LinkedHashMap instance with the specified capacity, load factor and
a flag specifying the ordering behavior.
Parameters:
s - the initial capacity of this hash map.
lf - the initial load factor.
order - true if the ordering should be done based on the last access (from
least-recently accessed to most-recently accessed), and false if the ordering
should be the order in which the entries were inserted.
Throws:
IllegalArgumentException - when the capacity is less than zero or the load
factor is less or equal to zero.
LinkedHashMap
public LinkedHashMap(Map<? extends K,? extends V> m)
Constructs a new LinkedHashMap instance containing the mappings from the specified
map. The order of the elements is preserved.
Parameters:
m - the mappings to add.
Method Detail
containsValue
public boolean containsValue(Object value)
Constructor Detail
225
Returns a set containing all of the mappings in this map. Each mapping is an
instance of Map.Entry. As the set is backed by this map, changes in one will be
reflected in the other.
Specified by:
entrySet in interface Map<K,V>
Overrides:
entrySet in class HashMap<K,V>
Returns:
a set of the mappings.
keySet
public Set<K> keySet()
Returns a set of the keys contained in this map. The set is backed by this map so
changes to one are reflected by the other. The set does not support adding.
Specified by:
keySet in interface Map<K,V>
Overrides:
keySet in class HashMap<K,V>
Returns:
a set of the keys.
values
public Collection<V> values()
Returns a collection of the values contained in this map. The collection is backed by
this map so changes to one are reflected by the other. The collection supports
remove, removeAll, retainAll and clear operations, and it does not support add or
addAll operations.
This method returns a collection which is the subclass of AbstractCollection. The
iterator method of this subclass returns a "wrapper object" over the iterator of map's
Method Detail
226
in interface Map<K,V>
Overrides:
values in class HashMap<K,V>
Returns:
a collection of the values contained in this map.
remove
public V remove(Object key)
Removes the mapping with the specified key from this map.
Specified by:
remove in interface Map<K,V>
Overrides:
remove in class HashMap<K,V>
Parameters:
key - the key of the mapping to remove.
Returns:
the value of the removed mapping or null if no mapping for the specified key
was found.
removeEldestEntry
protected boolean removeEldestEntry(Map.Entry<K,V> eldest)
This method is queried from the put and putAll methods to check if the eldest
member of the map should be deleted before adding the new member. If this map
was created with accessOrder = true, then the result of removeEldestEntry is
assumed to be false.
Parameters:
eldest - the entry to check if it should be removed.
Returns:
true if the eldest member should be removed.
clear
public void clear()
Method Detail
227
Interface Iterator<E>
Type Parameters:
E - the type of object returned by the iterator.
All Known Subinterfaces:
ListIterator<E>
public interface
Method Summary
Modifier and Type
boolean
void
Method Detail
hasNext
boolean hasNext()
Returns whether there are more elements to iterate, i.e. whether the iterator is
positioned in front of an element.
Returns:
true if there are more elements, false otherwise.
See Also:
next()
next
E next()
Returns the next object in the iteration, i.e. returns the element in front of the iterator
and advances the iterator by one position.
Returns:
the next object.
Throws:
NoSuchElementException - if there are no more elements.
See Also:
hasNext()
remove
void remove()
Removes the last object returned by next from the collection. This method can only
be called once after next was called.
Throws:
java.lang.UnsupportedOperationException - if removing is not supported by
the collection being iterated.
Interface Iterator<E>
228
Method Detail
229
Class IdentityHashMap<K,V>
java.lang.Object
java.util.AbstractMap<K,V>
java.util.IdentityHashMap<K,V>
All Implemented Interfaces:
Map<K,V>
public class
extends AbstractMap<K,V>
implements Map<K,V>
Constructor Summary
Constructor and Description
IdentityHashMap()
Method Summary
Modifier and Type
void
Class IdentityHashMap<K,V>
230
containsKey(Object key)
boolean
isEmpty()
Set<K>
void
Removes the mapping with the specified key from this map.
size()
int
Collection<V>
values()
Constructor Detail
IdentityHashMap
public IdentityHashMap()
Method Summary
231
Method Detail
clear
public void clear()
Method Detail
232
Copies all the mappings in the specified map to this map. These mappings will
replace all mappings that this map had for any of the keys currently in the given map.
Specified by:
putAll in interface Map<K,V>
Overrides:
putAll in class AbstractMap<K,V>
Parameters:
map - the map to copy mappings from.
Throws:
NullPointerException - if map is null.
remove
public V remove(Object key)
Removes the mapping with the specified key from this map.
Specified by:
remove in interface Map<K,V>
Overrides:
remove in class AbstractMap<K,V>
Parameters:
key - the key of the mapping to remove.
Returns:
the value of the removed mapping, or null if no mapping for the specified key
was found.
entrySet
public Set<Map.Entry<K,V>> entrySet()
Returns a set containing all of the mappings in this map. Each mapping is an
instance of Map.Entry. As the set is backed by this map, changes in one will be
reflected in the other.
Specified by:
entrySet in interface Map<K,V>
Specified by:
entrySet in class AbstractMap<K,V>
Returns:
a set of the mappings.
keySet
public Set<K> keySet()
Returns a set of the keys contained in this map. The set is backed by this map so
changes to one are reflected by the other. The set does not support adding.
Specified by:
keySet in interface Map<K,V>
Overrides:
keySet in class AbstractMap<K,V>
Returns:
a set of the keys.
values
public Collection<V> values()
Returns a collection of the values contained in this map. The collection is backed by
this map so changes to one are reflected by the other. The collection supports
remove, removeAll, retainAll and clear operations, and it does not support add or
addAll operations.
Method Detail
233
in interface Map<K,V>
Overrides:
values in class AbstractMap<K,V>
Returns:
a collection of the values contained in this map.
equals
public boolean equals(Object object)
Compares this map with other objects. This map is equal to another map is it
represents the same set of mappings. With this map, two mappings are the same if
both the key and the value are equal by reference. When compared with a map that
is not an IdentityHashMap, the equals method is neither necessarily symmetric
(a.equals(b) implies b.equals(a)) nor transitive (a.equals(b) and b.equals(c) implies
a.equals(c)).
Specified by:
equals in interface Map<K,V>
Overrides:
equals in class AbstractMap<K,V>
Parameters:
object - the object to compare to.
Returns:
whether the argument object is equal to this object.
See Also:
AbstractMap.hashCode(), AbstractMap.entrySet()
isEmpty
public boolean isEmpty()
size
public int size()
Method Detail
234
Class Hashtable<K,V>
java.lang.Object
java.util.Dictionary<K,V>
java.util.Hashtable<K,V>
All Implemented Interfaces:
Map<K,V>
public class
extends Dictionary<K,V>
implements Map<K,V>
Hashtable associates keys with values. Both keys and values cannot be null. The size of the
Hashtable is the number of key/value pairs it contains. The capacity is the number of key/value pairs
the Hashtable can hold. The load factor is a float value which determines how full the Hashtable gets
before expanding the capacity. If the load factor of the Hashtable is exceeded, the capacity is
doubled.
See Also:
Enumeration, Serializable, Object.equals(java.lang.Object), Object.hashCode()
Constructor Summary
Constructor and Description
Hashtable()
Constructs a new Hashtable using the default capacity and load factor.
Hashtable(int capacity)
Constructs a new Hashtable
Method Summary
Modifier and Type
void
Removes all key/value pairs from this Hashtable, leaving the size
zero and the capacity unchanged.
boolean
contains(Object value)
Returns true if this Hashtable
boolean
containsKey(Object key)
Returns true if this Hashtable
boolean
containsValue(Object value)
Searches this Hashtable for the
specified value.
elements()
Class Hashtable<K,V>
get(Object key)
235
int
boolean
Enumeration<K>
isEmpty()
Set<K>
void
protected void
rehash()
Removes the key/value pair with the specified key from this
Hashtable.
size()
int
String
Collection<V>
values()
Constructor Detail
Hashtable
public Hashtable()
Constructs a new Hashtable using the default capacity and load factor.
Hashtable
public Hashtable(int capacity)
Constructs a new Hashtable using the specified capacity and the default load factor.
Parameters:
capacity - the initial capacity.
Hashtable
public Hashtable(int capacity,
float loadFactor)
Constructs a new Hashtable using the specified capacity and load factor.
Parameters:
capacity - the initial capacity.
loadFactor - the initial load factor.
Hashtable
public Hashtable(Map<? extends K,? extends V> map)
Constructs a new instance of Hashtable containing the mappings from the specified
map.
Parameters:
Method Summary
236
Method Detail
clear
public void clear()
Removes all key/value pairs from this Hashtable, leaving the size zero and the
capacity unchanged.
Specified by:
clear in interface Map<K,V>
See Also:
isEmpty(), size()
contains
public boolean contains(Object value)
Returns true if this Hashtable contains the specified object as the value of at least
one of the key/value pairs.
Parameters:
value - the object to look for as a value in this Hashtable.
Returns:
true if object is a value in this Hashtable, false otherwise.
See Also:
containsKey(java.lang.Object), Object.equals(java.lang.Object)
containsKey
public boolean containsKey(Object key)
Returns true if this Hashtable contains the specified object as a key of one of the
key/value pairs.
Specified by:
containsKey in interface Map<K,V>
Parameters:
key - the object to look for as a key in this Hashtable.
Returns:
true if object is a key in this Hashtable, false otherwise.
See Also:
contains(java.lang.Object), Object.equals(java.lang.Object)
containsValue
public boolean containsValue(Object value)
Constructor Detail
237
Returns a set of the mappings contained in this Hashtable. Each element in the set is
a Map.Entry. The set is backed by this Hashtable so changes to one are reflected by
the other. The set does not support adding.
Specified by:
entrySet in interface Map<K,V>
Returns:
a set of the mappings.
equals
public boolean equals(Object object)
Compares this Hashtable with the specified object and indicates if they are equal. In
order to be equal, object must be an instance of Map and contain the same
key/value pairs.
Specified by:
equals in interface Map<K,V>
Overrides:
equals in class Object
Parameters:
object - the object to compare with this object.
Returns:
true if the specified object is equal to this Map, false otherwise.
See Also:
hashCode()
get
public V get(Object key)
Returns the value associated with the specified key in this Hashtable.
Specified by:
get in interface Map<K,V>
Specified by:
get in class Dictionary<K,V>
Parameters:
key - the key of the value returned.
Returns:
the value associated with the specified key, or null if the specified key does
not exist.
See Also:
put(K, V)
hashCode
public int hashCode()
Method Detail
238
in interface Map<K,V>
Overrides:
hashCode in class Object
Returns:
the receiver's hash.
See Also:
Map.equals(Object)
isEmpty
public boolean isEmpty()
keys
public Enumeration<K> keys()
Returns an enumeration on the keys of this Hashtable instance. The results of the
enumeration may be affected if the contents of this Hashtable are modified.
Specified by:
keys in class Dictionary<K,V>
Returns:
an enumeration of the keys of this Hashtable.
See Also:
elements(), size(), Enumeration
keySet
public Set<K> keySet()
Returns a set of the keys contained in this Hashtable. The set is backed by this
Hashtable so changes to one are reflected by the other. The set does not support
adding.
Specified by:
keySet in interface Map<K,V>
Returns:
a set of the keys.
put
public V put(K key,
V value)
Associate the specified value with the specified key in this Hashtable. If the key
already exists, the old value is replaced. The key and value cannot be null.
Specified by:
put in interface Map<K,V>
Specified by:
put in class Dictionary<K,V>
Parameters:
key - the key to add.
value - the value to add.
Returns:
the old value associated with the specified key, or null if the key did not
exist.
See Also:
elements(), get(java.lang.Object), keys(),
Object.equals(java.lang.Object)
Method Detail
239
Increases the capacity of this Hashtable. This method is called when the size of this
Hashtable exceeds the load factor.
remove
public V remove(Object key)
Removes the key/value pair with the specified key from this Hashtable.
Specified by:
remove in interface Map<K,V>
Specified by:
remove in class Dictionary<K,V>
Parameters:
key - the key to remove.
Returns:
the value associated with the specified key, or null if the specified key did
not exist.
See Also:
get(java.lang.Object), put(K, V)
size
public int size()
Method Detail
240
Class HashSet<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractSet<E>
java.util.HashSet<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, Set<E>
Direct Known Subclasses:
LinkedHashSet
public class
extends AbstractSet<E>
implements Set<E>
HashSet is an implementation of a Set. All optional operations (adding and removing) are supported.
The elements can be any objects.
Constructor Summary
Constructor and Description
HashSet()
collection.
HashSet(int capacity)
Method Summary
Modifier and Type
boolean
void
boolean
boolean
Iterator<E>
boolean
contains(Object object)
Searches this HashSet for the
specified object.
isEmpty()
int
Class HashSet<E>
241
Constructor Detail
HashSet
public HashSet()
Constructs a new instance of HashSet with the specified capacity and load factor.
Parameters:
capacity - the initial capacity.
loadFactor - the initial load factor.
HashSet
public HashSet(Collection<? extends E> collection)
Constructs a new instance of HashSet containing the unique elements in the specified
collection.
Parameters:
collection - the collection of elements to add.
Method Detail
add
public boolean add(E object)
242
iterator
public Iterator<E> iterator()
remove
public boolean remove(Object object)
Method Detail
243
in interface Set<E>
Overrides:
remove
in class AbstractCollection<E>
Parameters:
object
Returns:
true
size
public int size()
Method Detail
244
Class HashMap<K,V>
java.lang.Object
java.util.AbstractMap<K,V>
java.util.HashMap<K,V>
All Implemented Interfaces:
Map<K,V>
Direct Known Subclasses:
LinkedHashMap, Properties
public class
extends AbstractMap<K,V>
implements Map<K,V>
HashMap is an implementation of Map. All optional operations (adding and removing) are supported.
Keys and values can be any objects.
Constructor Summary
Constructor and Description
HashMap()
Method Summary
Modifier and Type
void
boolean
boolean
Set<Map.Entry<K,V>>
V
boolean
Set<K>
Class HashMap<K,V>
245
void
Removes the mapping with the specified key from this map.
size()
int
Collection<V>
values()
Constructor Detail
HashMap
public HashMap()
Constructs a new HashMap instance with the specified capacity and load factor.
Parameters:
capacity - the initial capacity of this hash map.
loadFactor - the initial load factor.
Throws:
IllegalArgumentException - when the capacity is less than zero or the load
factor is less or equal to zero.
HashMap
public HashMap(Map<? extends K,? extends V> map)
Constructs a new HashMap instance containing the mappings from the specified map.
Parameters:
map - the mappings to add.
Method Detail
Method Summary
246
Returns a set containing all of the mappings in this map. Each mapping is an
instance of Map.Entry. As the set is backed by this map, changes in one will be
reflected in the other.
Specified by:
entrySet in interface Map<K,V>
Specified by:
entrySet in class AbstractMap<K,V>
Returns:
a set of the mappings.
get
public V get(Object key)
Method Detail
247
keySet
public Set<K> keySet()
Returns a set of the keys contained in this map. The set is backed by this map so
changes to one are reflected by the other. The set does not support adding.
Specified by:
keySet in interface Map<K,V>
Overrides:
keySet in class AbstractMap<K,V>
Returns:
a set of the keys.
put
public V put(K key,
V value)
Copies all the mappings in the specified map to this map. These mappings will
replace all mappings that this map had for any of the keys currently in the given map.
Specified by:
putAll in interface Map<K,V>
Overrides:
putAll in class AbstractMap<K,V>
Parameters:
map - the map to copy mappings from.
Throws:
NullPointerException - if map is null.
remove
public V remove(Object key)
Removes the mapping with the specified key from this map.
Specified by:
remove in interface Map<K,V>
Overrides:
remove in class AbstractMap<K,V>
Parameters:
key - the key of the mapping to remove.
Method Detail
248
Returns a collection of the values contained in this map. The collection is backed by
this map so changes to one are reflected by the other. The collection supports
remove, removeAll, retainAll and clear operations, and it does not support add or
addAll operations.
This method returns a collection which is the subclass of AbstractCollection. The
iterator method of this subclass returns a "wrapper object" over the iterator of map's
entrySet(). The size method wraps the map's size method and the contains method
wraps the map's containsValue method.
The collection is created when this method is called for the first time and returned in
response to all subsequent calls. This method may return different collections when
multiple concurrent calls occur, since no synchronization is performed.
Specified by:
values
in interface Map<K,V>
Overrides:
values in class AbstractMap<K,V>
Returns:
a collection of the values contained in this map.
Method Detail
249
Class EventListenerProxy
java.lang.Object
java.util.EventListenerProxy
All Implemented Interfaces:
EventListener
This abstract class provides a simple wrapper for objects of type EventListener.
Constructor Summary
Constructor and Description
EventListenerProxy(EventListener listener)
Creates a new EventListener proxy instance.
Method Summary
Modifier and Type
EventListener
Constructor Detail
EventListenerProxy
public EventListenerProxy(EventListener listener)
Method Detail
getListener
public EventListener getListener()
Class EventListenerProxy
250
Interface EventListener
All Known Implementing Classes:
EventListenerProxy
public interface
Method Detail
251
Interface Enumeration<T>
All Known Implementing Classes:
StringTokenizer
public interface
An object that implements the Enumeration interface generates a series of elements, one at a time.
Successive calls to the nextElement method return successive elements of the series. For example,
to print all elements of a vector v: Methods are provided to enumerate through the elements of a
vector, the keys of a hashtable, and the values in a hashtable. Since: JDK1.0, CLDC 1.0 Version:
12/17/01 (CLDC 1.1) See Also:nextElement(), Hashtable, Hashtable.elements(), Hashtable.keys(),
Vector, Vector.elements()
Method Summary
Modifier and
Type
boolean
Returns the next element of this enumeration if this enumeration object has
at least one more element to provide.
Method Detail
hasMoreElements
boolean hasMoreElements()
Returns the next element of this enumeration if this enumeration object has at least
one more element to provide.
Interface EventListener
252
Class EmptyStackException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.util.EmptyStackException
public class
extends RuntimeException
Thrown by methods in the Stack class to indicate that the stack is empty. Since: JDK1.0, CLDC 1.0
Version: 12/17/01 (CLDC 1.1) See Also:Stack
Constructor Summary
Constructor and Description
EmptyStackException()
Method Summary
Constructor Detail
EmptyStackException
public EmptyStackException()
Method Detail
253
Class Dictionary<K,V>
java.lang.Object
java.util.Dictionary<K,V>
Direct Known Subclasses:
Hashtable
Note: Do not use this class since it is obsolete. Please use the Map interface for new
implementations.
Dictionary is an abstract class which is the superclass of all classes that associate keys with values,
such as Hashtable.
Since:
1.0
See Also:
Hashtable
Constructor Summary
Constructor and Description
Dictionary()
Method Summary
Modifier and Type
abstract Enumeration<V>
abstract V
abstract boolean
abstract Enumeration<K>
abstract V
in this dictionary.
remove(Object key)
abstract V
abstract int
Removes the key/value pair with the specified key from this
dictionary.
size()
Constructor Detail
Constructor Detail
254
Method Detail
elements
public abstract Enumeration<V> elements()
isEmpty
public abstract boolean isEmpty()
keys
public abstract Enumeration<K> keys()
Associate key with value in this dictionary. If key exists in the dictionary before this
call, the old value in the dictionary is replaced by value.
Parameters:
key - the key to add.
value - the value to add.
Returns:
the old value previously associated with key or null if key is new to the
dictionary.
See Also:
elements(), get(java.lang.Object), keys()
Constructor Detail
255
Removes the key/value pair with the specified key from this dictionary.
Parameters:
key - the key to remove.
Returns:
the associated value before the deletion or null if key was not known to this
dictionary.
See Also:
get(java.lang.Object), put(K, V)
size
public abstract int size()
Method Detail
256
Interface Deque<E>
Type Parameters:
E - the type of elements in this collection
All Superinterfaces:
Collection<E>, Iterable<E>, Queue<E>
All Known Implementing Classes:
ArrayDeque, LinkedList
public interface
extends Queue<E>
A kind of collection that can insert or remove element at both ends("double ended queue"). Mostly a
deque has no limit of its size. Extending from Queue, a deque can be used as a Queue which
behavior is first-in-first-out. Furthermore, a deque can also be used as a Stack(legacy class) which
behavior is last-in-first-out. A typical deque does not allow null to be inserted as its element, while
some implementations allow it. But null should not be inserted even in these implementations, since
method poll return null to indicate that there is no element left in the deque. A deque can also remove
interior elements by removeFirstOccurrence and removeLastOccurrence methods. A deque can not
access elements by index.
Since:
1.6
Method Summary
Modifier and
Type
void
Inserts an element at the head of this deque if it dose not violate size limit
immediately.
addLast(E e)
void
Iterator<E>
E
E
Inserts an element at the tail of this deque if it dose not violate size limit
immediately.
descendingIterator()
boolean
Inserts an element at the head of this deque unless it would violate size
limit.
offerLast(E e)
boolean
E
E
E
E
E
void
Interface Deque<E>
Inserts an element at the tail of this deque unless it would violate size
limit.
peekFirst()
257
boolean
removeFirstOccurrence(Object o)
boolean
removeLastOccurrence(Object o)
Method Detail
addFirst
void addFirst(E e)
Inserts an element at the head of this deque if it dose not violate size limit
immediately. It is better to use offerFirst(E) if a deque is size-limited.
Parameters:
e - the element
Throws:
IllegalStateException - if it can not add now due to size limit
ClassCastException - if the class of element can not be added into this
deque
NullPointerException - if the element is null and the deque can not contain
null element
IllegalArgumentException - if the element can not be added due to some
property.
addLast
void addLast(E e)
Inserts an element at the tail of this deque if it dose not violate size limit immediately.
It is better to use offerLast(E) if a deque is size-limited.
Parameters:
e - the element
Throws:
IllegalStateException - if it can not add now due to size limit
ClassCastException - if the class of element can not be added into this
deque
NullPointerException - if the element is null and the deque can not contain
null element
IllegalArgumentException - if the element can not be added due to some
property.
offerFirst
boolean offerFirst(E e)
Method Summary
258
Inserts an element at the tail of this deque unless it would violate size limit. It is better
than the addLast(E) method in a size-limited deque, because the latter one may fail
to add the element only by throwing an exception.
Parameters:
e - the element
Returns:
true if the operation succeeds or false if it fails
Throws:
ClassCastException - if the class of element can not be added into this
deque
NullPointerException - if the element is null and the deque can not contain
null element
IllegalArgumentException - if the element can not be added due to some
property
removeFirst
E removeFirst()
Gets and removes the head element of this deque. This method throws an exception
if the deque is empty.
Returns:
the head element
Throws:
NoSuchElementException - if the deque is empty
removeLast
E removeLast()
Gets and removes the tail element of this deque. This method throws an exception if
the deque is empty.
Returns:
the tail element
Throws:
NoSuchElementException - if the deque is empty
pollFirst
E pollFirst()
Gets and removes the head element of this deque. This method returns null if the
deque is empty.
Returns:
the head element or null if the deque is empty
pollLast
E pollLast()
Method Detail
259
Gets but not removes the head element of this deque. This method throws an
exception if the deque is empty.
Returns:
the head element
Throws:
NoSuchElementException - if the deque is empty
getLast
E getLast()
Gets but not removes the tail element of this deque. This method throws an exception
if the deque is empty.
Returns:
the tail element
Throws:
NoSuchElementException - if the deque is empty
peekFirst
E peekFirst()
Gets but not removes the head element of this deque. This method returns null if the
deque is empty.
Returns:
the head element or null if the deque is empty
peekLast
E peekLast()
Gets but not removes the tail element of this deque. This method returns null if the
deque is empty.
Returns:
the tail element or null if the deque is empty
removeFirstOccurrence
boolean removeFirstOccurrence(Object o)
Removes the first equivalent element of the specified object. If the deque does not
contain the element, it is unchanged and returns false.
Parameters:
o - the element to be removed
Returns:
true if the operation succeeds or false if the deque does not contain the
element.
Throws:
ClassCastException - if the class of the element is incompatible with the
deque
NullPointerException - if the element is null and the deque can not contain
null element
removeLastOccurrence
boolean removeLastOccurrence(Object o)
Removes the last equivalent element of the specified object. If the deque does not
contain the element, it is unchanged and returns false.
Parameters:
o - the element to be removed
Returns:
true if the operation succeeds or false if the deque does not contain the
element.
Method Detail
260
deque
NullPointerException
null element
push
void push(E e)
Pushes the element to the deque(at the head of the deque), just same as addFirst(E).
Parameters:
e - the element
Throws:
IllegalStateException - if it can not add now due to size limit
ClassCastException - if the class of element can not be added into this
deque
NullPointerException - if the element is null and the deque can not contain
null element
IllegalArgumentException - if the element can not be added due to some
property.
pop
E pop()
Method Detail
261
Class Date
java.lang.Object
java.util.Date
public class
extends Object
The class Date represents a specific instant in time, with millisecond precision. This class has been
subset for the J2ME based on the JDK 1.3 Date class. Many methods and variables have been
pruned, and other methods simplified, in an effort to reduce the size of this class. Although the Date
class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on
the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1
day = 24x60x60 = 86400 seconds in all cases. In UTC, however, about once every year or two there
is an extra second, called a "leap second." The leap second is always added as the last second of the
day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61
seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be
able to reflect the leap-second distinction. Version: CLDC 1.1 03/13/2002 (Based on JDK 1.3) See
Also:TimeZone, Calendar
Constructor Summary
Constructor and Description
Date()
Allocates a Date object and initializes it to represent the current time specified number of
milliseconds since the standard base time known as "the epoch", namely January 1, 1970,
00:00:00 GMT.
Date(long date)
Allocates a Date object and initializes it to represent the specified number of milliseconds
since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00
GMT.
Method Summary
Modifier
and Type
boolean
long
hashCode()
int
Sets this Date object to represent a point in time that is time milliseconds after
January 1, 1970 00:00:00 GMT.
void
toString()
String
Converts this Date object to a String of the form: dow mon dd hh:mm:ss zzz
yyyy where: dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
Class Date
262
Detail
Date
public Date()
Allocates a Date object and initializes it to represent the current time specified
number of milliseconds since the standard base time known as "the epoch", namely
January 1, 1970, 00:00:00 GMT. See Also:System.currentTimeMillis()
Date
public Date(long date)
Method Detail
equals
public boolean equals(Object obj)
Compares two dates for equality. The result is true if and only if the argument is not
null and is a Date object that represents the same point in time, to the millisecond, as
this object. Thus, two Date objects are equal if and only if the getTime method returns
the same long value for both.
Overrides:
equals in class Object
getTime
public long getTime()
Returns a hash code value for this object. The result is the exclusive OR of the two
halves of the primitive long value returned by the method. That is, the hash code is
the value of the expression: (int)(this.getTime()^(this.getTime() >>> 32))
Overrides:
hashCode in class Object
setTime
public void setTime(long time)
Sets this Date object to represent a point in time that is time milliseconds after
January 1, 1970 00:00:00 GMT.
toString
public String toString()
Converts this Date object to a String of the form: dow mon dd hh:mm:ss zzz yyyy
where: dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat). mon is the
month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec). dd is the day of
the month (01 through 31), as two decimal digits. hh is the hour of the day (00
through 23), as two decimal digits. mm is the minute within the hour (00 through 59),
as two decimal digits. ss is the second within the minute (00 through 61, as two
decimal digits. zzz is the time zone (and may reflect daylight savings time). If time
zone information is not available, then zzz is empty - that is, it consists of no
characters at all. yyyy is the year, as four decimal digits.
Constructor Detail
263
Overrides:
toString
Method Detail
in class Object
264
Class ConcurrentModificationException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.util.ConcurrentModificationException
public class
extends RuntimeException
Constructor Summary
Constructor and Description
ConcurrentModificationException()
Constructs a new ConcurrentModificationException
ConcurrentModificationException(String detailMessage)
Constructs a new ConcurrentModificationException with the
Method Summary
Constructor Detail
ConcurrentModificationException
public ConcurrentModificationException()
Class ConcurrentModificationException
265
Interface Comparator<T>
All Known Implementing Classes:
CaseInsensitiveOrder
public interface
A Comparator is used to compare two objects to determine their ordering with respect to each other.
On a given Collection, a Comparator can be used to obtain a sorted Collection which is totally
ordered. For a Comparator to be consistent with equals, its {code #compare(Object, Object)} method
has to return zero for each pair of elements (a,b) where a.equals(b) holds true. It is recommended
that a Comparator implements Serializable.
Since:
1.2
Method Summary
Modifier and
Type
int
boolean
equals(Object object)
Compares this Comparator
Method Detail
compare
int compare(T object1,
T object2)
Compares the two specified objects to determine their relative ordering. The ordering
implied by the return value of this method for all possible pairs of (object1, object2)
should form an equivalence relation. This means that
compare(a,a) returns zero for all a
the sign of compare(a,b) must be the opposite of the sign of compare(b,a) for
all pairs of (a,b)
From compare(a,b) > 0 and compare(b,c) > 0 it must follow compare(a,c) >
0 for all possible combinations of (a,b,c)
Parameters:
object1 - an Object.
object2 - a second Object to compare with object1.
Returns:
an integer < 0 if object1 is less than object2, 0 if they are equal, and > 0 if
object1 is greater than object2.
Throws:
ClassCastException - if objects are not of the correct type.
equals
boolean equals(Object object)
Compares this Comparator with the specified Object and indicates whether they are
equal. In order to be equal, object must represent the same object as this instance
using a class-specific comparison.
Constructor Detail
266
in class Object
Parameters:
object - the Object to compare with this comparator.
Returns:
boolean true if specified Object is the same as this Object, and false
otherwise.
See Also:
Object.hashCode(), Object.equals(java.lang.Object)
Method Detail
267
Class Collections
java.lang.Object
java.util.Collections
public class
extends Object
Collections
Since:
1.2
Field Summary
Modifier and Type
static List
static Map
static Set
Method Summary
Modifier and Type
static <T> boolean
static <T> Queue<T>
Copies the elements from the source list to the destination list.
disjoint(Collection<?> c1, Collection<?> c2)
static boolean
Class Collections
268
static int
static int
that match
index
index
list(Enumeration<T> enumeration)
Returns an ArrayList with all the elements
in the enumeration.
static <T> T
static <T> T
element.
element.
static void
with newObj.
elements.
static <T> Comparator<T>
reverseOrder()
passed.
static void
distance dist
shuffle(List<?> list)
static void
static void
Method Summary
269
and index2.
synchronizedCollection(Collection<T> collection)
static <T> Collection<T>
static
<K,V> SortedMap<K,V>
static
<K,V> SortedMap<K,V>
Field Detail
EMPTY_LIST
public static final List EMPTY_LIST
270
Method Detail
binarySearch
public static <T> int binarySearch(List<? extends Comparable<? super T>> list,
T object)
Performs a binary search for the specified element in the specified sorted list. The list
needs to be already sorted in natural sorting order. Searching in an unsorted array
has an undefined result. It's also undefined which element is found if there are
multiple occurrences of the same element.
Parameters:
list - the sorted list to search.
object - the element to find.
Returns:
the non-negative index of the element, or a negative index which is the
-index - 1 where the element would be inserted
Throws:
ClassCastException - if an element in the List or the search element does not
implement Comparable, or cannot be compared to each other.
binarySearch
public static <T> int binarySearch(List<? extends T> list,
T object,
Comparator<? super T> comparator)
Performs a binary search for the specified element in the specified sorted list using
the specified comparator. The list needs to be already sorted according to the
comparator passed. Searching in an unsorted array has an undefined result. It's also
undefined which element is found if there are multiple occurrences of the same
element.
Type Parameters:
T - The element type
Parameters:
list - the sorted List to search.
object - the element to find.
comparator - the comparator. If the comparator is null then the search uses
the objects' natural ordering.
Returns:
the non-negative index of the element, or a negative index which is the
-index - 1 where the element would be inserted.
Throws:
ClassCastException - when an element in the list and the searched element
cannot be compared to each other using the comparator.
copy
public static <T> void copy(List<? super T> destination,
List<? extends T> source)
Copies the elements from the source list to the destination list. At the end both lists
will have the same objects at the same index. If the destination array is larger than
the source list, the elements in the destination list with index >= source.size() will
be unchanged.
Field Detail
271
Throws:
IndexOutOfBoundsException
source list.
java.lang.UnsupportedOperationException
Searches the specified collection for the maximum element using the specified
comparator.
Parameters:
collection - the collection to search.
comparator - the comparator.
Returns:
the maximum element in the Collection.
Throws:
ClassCastException - when elements in the collection cannot be compared to
each other using the Comparator.
min
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends
Method Detail
272
not implement
min
public static <T> T min(Collection<? extends T> collection,
Comparator<? super T> comparator)
Searches the specified collection for the minimum element using the specified
comparator.
Parameters:
collection - the collection to search.
comparator - the comparator.
Returns:
the minimum element in the collection.
Throws:
ClassCastException - when elements in the collection cannot be compared to
each other using the Comparator.
nCopies
public static <T> List<T> nCopies(int length,
T object)
Returns a list containing the specified number of the specified element. The list
cannot be modified. The list is serializable.
Parameters:
length - the size of the returned list.
object - the element to be added length times to a list.
Returns:
a list containing length copies of the element.
Throws:
IllegalArgumentException - when length < 0.
reverse
public static void reverse(List<?> list)
A comparator which reverses the natural order of the elements. The Comparator that's
returned is Serializable.
Returns:
a Comparator instance.
See Also:
Comparator, Comparable, Serializable
reverseOrder
public static <T> Comparator<T> reverseOrder(Comparator<T> c)
Returns a Comparator that reverses the order of the Comparator passed. If the
Comparator passed is null, then this method is equivalent to reverseOrder().
The Comparator that's returned is Serializable if the Comparator passed is
serializable or null.
Parameters:
c - the Comparator to reverse or null.
Returns:
a Comparator instance.
Since:
Method Detail
273
shuffle
public static void shuffle(List<?> list)
Moves every element of the list to a random new position in the list.
Parameters:
list - the List to shuffle.
Throws:
java.lang.UnsupportedOperationException - when replacing an element in
the List is not supported.
shuffle
public static void shuffle(List<?> list,
Random random)
Moves every element of the list to a random new position in the list using the
specified random number generator.
Parameters:
list - the list to shuffle.
random - the random number generator.
Throws:
java.lang.UnsupportedOperationException - when replacing an element in
the list is not supported.
singleton
public static <E> Set<E> singleton(E object)
Returns a set containing the specified element. The set cannot be modified. The set
is serializable.
Parameters:
object - the element.
Returns:
a set containing the element.
singletonList
public static <E> List<E> singletonList(E object)
Returns a list containing the specified element. The list cannot be modified. The list is
serializable.
Parameters:
object - the element.
Returns:
a list containing the element.
singletonMap
public static <K,V> Map<K,V> singletonMap(K key,
V value)
Returns a Map containing the specified key and value. The map cannot be modified.
The map is serializable.
Parameters:
key - the key.
value - the value.
Returns:
a Map containing the key and value.
sort
public static <T extends Comparable<? super T>> void sort(List<T> list)
Sorts the specified list in ascending natural order. The algorithm is stable which
means equal elements don't get reordered.
Method Detail
274
Throws:
- when an element in the List does not implement
Comparable or elements cannot be compared to each other.
ClassCastException
sort
public static <T> void sort(List<T> list,
Comparator<? super T> comparator)
Sorts the specified list using the specified comparator. The algorithm is stable which
means equal elements don't get reordered.
Parameters:
list - the list to be sorted.
comparator - the comparator.
Throws:
ClassCastException - when elements in the list cannot be compared to each
other using the comparator.
swap
public static void swap(List<?> list,
int index1,
int index2)
Replaces all occurrences of Object obj in list with newObj. If the obj is null, then all
occurrences of null are replaced with newObj.
Parameters:
list - the list to modify.
obj - the object to find and replace occurrences of.
obj2 - the object to replace all occurrences of obj in list.
Returns:
true, if at least one occurrence of obj has been found in list.
Throws:
java.lang.UnsupportedOperationException - if the list does not support
setting elements.
rotate
public static void rotate(List<?> lst,
int dist)
Method Detail
275
Searches the list for sublist and returns the beginning index of the first occurrence.
-1 is returned if the sublist does not exist in list.
Parameters:
list - the List to search sublist in.
sublist - the List to search in list.
Returns:
the beginning index of the first occurrence of sublist in list, or -1.
lastIndexOfSubList
public static int lastIndexOfSubList(List<?> list,
List<?> sublist)
Searches the list for sublist and returns the beginning index of the last occurrence.
-1 is returned if the sublist does not exist in list.
Parameters:
list - the list
sublist - the
Returns:
the beginning index of the last occurrence of sublist in list, or -1.
list
public static <T> ArrayList<T> list(Enumeration<T> enumeration)
Returns an ArrayList with all the elements in the enumeration. The elements in the
returned ArrayList are in the same order as in the enumeration.
Parameters:
enumeration - the source Enumeration.
Returns:
an ArrayList from enumeration.
synchronizedCollection
public static <T> Collection<T> synchronizedCollection(Collection<T> collection)
Returns a wrapper on the specified collection which synchronizes all access to the
collection.
Parameters:
collection - the Collection to wrap in a synchronized collection.
Returns:
a synchronized Collection.
synchronizedList
public static <T> List<T> synchronizedList(List<T> list)
Returns a wrapper on the specified List which synchronizes all access to the List.
Parameters:
list - the List to wrap in a synchronized list.
Returns:
a synchronized List.
synchronizedMap
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> map)
Returns a wrapper on the specified map which synchronizes all access to the map.
Parameters:
map - the map to wrap in a synchronized map.
Returns:
a synchronized Map.
Method Detail
276
Returns a wrapper on the specified set which synchronizes all access to the set.
Parameters:
set - the set to wrap in a synchronized set.
Returns:
a synchronized set.
synchronizedSortedMap
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> map)
Returns a wrapper on the specified sorted map which synchronizes all access to the
sorted map.
Parameters:
map - the sorted map to wrap in a synchronized sorted map.
Returns:
a synchronized sorted map.
synchronizedSortedSet
public static <E> SortedSet<E> synchronizedSortedSet(SortedSet<E> set)
Returns a wrapper on the specified sorted set which synchronizes all access to the
sorted set.
Parameters:
set - the sorted set to wrap in a synchronized sorted set.
Returns:
a synchronized sorted set.
unmodifiableCollection
Method Detail
277
Returns the number of elements in the Collection that match the Object passed. If
the Object is null, then the number of null elements is returned.
Parameters:
c - the Collection to search.
o - the Object to search for.
Returns:
the number of matching elements.
Throws:
NullPointerException - if the Collection parameter is null.
Since:
1.5
emptyList
public static final <T> List<T> emptyList()
emptySet
public static final <T> Set<T> emptySet()
Method Detail
278
checkedCollection
public static <E> Collection<E> checkedCollection(Collection<E> c,
Class<E> type)
Answers a set backed by a map. And the map must be empty when this method is
called.
Type Parameters:
E - type of elements in set
Parameters:
map - the backing map
Returns:
Method Detail
279
Since:
1.6
asLifoQueue
public static <T> Queue<T> asLifoQueue(Deque<T> deque)
Answers a LIFO Queue as a view of a Deque. Methods in the returned Queue need
to be re-written to implement the LIFO feature.
Type Parameters:
T - type of elements
Parameters:
deque - the Deque
Returns:
the LIFO Queue
Since:
1.6
Method Detail
280
Interface Collection<E>
All Superinterfaces:
Iterable<E>
All Known Subinterfaces:
Deque<E>, List<E>, NavigableSet<E>, Queue<E>, Set<E>, SortedSet<E>
All Known Implementing Classes:
AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet,
ArrayDeque, ArrayList, HashSet, LinkedHashSet, LinkedList, PriorityQueue, Stack, TreeSet,
Vector
public interface
extends Iterable<E>
is the root of the collection hierarchy. It defines operations on data collections and the
behavior that they will have in all implementations of Collections. All direct or indirect
implementations of Collection should implement at least two constructors. One with no parameters
which creates an empty collection and one with a parameter of type Collection. This second
constructor can be used to create a collection of different type as the initial collection but with the
same elements. Implementations of Collection cannot be forced to implement these two constructors
but at least all implementations under java.util do. Methods that change the content of a collection
throw an UnsupportedOperationException if the underlying collection does not support that operation,
though it's not mandatory to throw such an Exception in cases where the requested operation would
not change the collection. In these cases it's up to the implementation whether it throws an
UnsupportedOperationException or not. Methods marked with (optional) can throw an
UnsupportedOperationException if the underlying collection doesn't support that method.
Collection
Method Summary
Modifier and
Type
boolean
boolean
void
to the contents of
clear()
boolean
contains(Object object)
Tests whether this Collection
boolean
containsAll(Collection<?> collection)
Tests whether this Collection contains all
specified Collection.
equals(Object object)
boolean
int
boolean
Compares the argument to the receiver, and returns true if they represent
the same object using a class specific comparison.
hashCode()
Iterator<E>
boolean
Interface Collection<E>
Removes one instance of the specified object from this Collection if one is
contained (optional).
281
removeAll(Collection<?> collection)
Removes all occurrences in this Collection
Collection (optional).
boolean
retainAll(Collection<?> collection)
Removes all objects from this Collection
Collection passed (optional).
size()
int
Object[]
<T> T[]
toArray()
Method Detail
add
boolean add(E object)
Attempts to add object to the contents of this Collection (optional). After this
method finishes successfully it is guaranteed that the object is contained in the
collection. If the collection was modified it returns true, false if no changes were
made. An implementation of Collection may narrow the set of accepted objects, but
it has to specify this in the documentation. If the object to be added does not meet
this restriction, then an IllegalArgumentException is thrown. If a collection does not
yet contain an object that is to be added and adding the object fails, this method must
throw an appropriate unchecked Exception. Returning false is not permitted in this
case because it would violate the postcondition that the element will be part of the
collection after this method finishes.
Parameters:
object - the object to add.
Returns:
true if this Collection is modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - if adding to this Collection is
not supported.
ClassCastException - if the class of the object is inappropriate for this
collection.
IllegalArgumentException - if the object cannot be added to this Collection.
NullPointerException - if null elements cannot be added to the Collection.
addAll
boolean addAll(Collection<? extends E> collection)
Attempts to add all of the objects contained in Collection to the contents of this
Collection (optional). If the passed Collection is changed during the process of
adding elements to this Collection, the behavior is not defined.
Parameters:
collection - the Collection of objects.
Returns:
true if this Collection is modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - if adding to this Collection is
not supported.
ClassCastException - if the class of an object is inappropriate for this
Collection.
IllegalArgumentException - if an object cannot be added to this Collection.
NullPointerException - if collection is null, or if it contains null elements
and this Collection does not support such elements.
Method Summary
282
Tests whether this Collection contains the specified object. Returns true if and only
if at least one element elem in this Collection meets following requirement:
(object==null ? elem==null : object.equals(elem)).
Parameters:
object - the object to search for.
Returns:
true if object is an element of this Collection, false otherwise.
Throws:
ClassCastException - if the object to look for isn't of the correct type.
NullPointerException - if the object to look for is null and this Collection
doesn't support null elements.
containsAll
boolean containsAll(Collection<?> collection)
Tests whether this Collection contains all objects contained in the specified
Collection. If an element elem is contained several times in the specified
Collection, the method returns true even if elem is contained only once in this
Collection.
Parameters:
collection - the collection of objects.
Returns:
true if all objects in the specified Collection are elements of this Collection,
false otherwise.
Throws:
ClassCastException - if one or more elements of collection isn't of the
correct type.
NullPointerException - if collection contains at least one null element and
this Collection doesn't support null elements.
NullPointerException - if collection is null.
equals
boolean equals(Object object)
Compares the argument to the receiver, and returns true if they represent the same
object using a class specific comparison.
Overrides:
equals in class Object
Parameters:
object - the object to compare with this object.
Returns:
true if the object is the same as this object and false if it is different from this
object.
See Also:
hashCode()
hashCode
int hashCode()
Returns an integer hash code for the receiver. Objects which are equal return the
same value for this method.
Overrides:
hashCode in class Object
Method Detail
283
isEmpty
boolean isEmpty()
iterator
Iterator<E> iterator()
Returns an instance of Iterator that may be used to access the objects contained by
this Collection. The order in which the elements are returned by the iterator is not
defined. Only if the instance of the Collection has a defined order the elements are
returned in that order.
Specified by:
iterator in interface Iterable<E>
Returns:
an iterator for accessing the Collection contents.
remove
boolean remove(Object object)
Removes one instance of the specified object from this Collection if one is contained
(optional). The element elem that is removed complies with (object==null ?
elem==null : object.equals(elem).
Parameters:
object - the object to remove.
Returns:
true if this Collection is modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - if removing from this
Collection is not supported.
ClassCastException - if the object passed is not of the correct type.
NullPointerException - if object is null and this Collection doesn't support
null elements.
removeAll
boolean removeAll(Collection<?> collection)
Removes all objects from this Collection that are not also found in the Collection
passed (optional). After this method returns this Collection will only contain
Method Detail
284
Returns a new array containing all elements contained in this Collection. If the
implementation has ordered elements it will return the element array in the same
order as an iterator would return them. The array returned does not reflect any
changes of the Collection. A new array is created even if the underlying data
structure is already an array.
Returns:
an array of the elements from this Collection.
toArray
<T> T[] toArray(T[] array)
Returns an array containing all elements contained in this Collection. If the specified
array is large enough to hold the elements, the specified array is used, otherwise an
array of the same type is created. If the specified array is used and is larger than this
Collection, the array element following the Collection elements is set to null. If the
implementation has ordered elements it will return the element array in the same
order as an iterator would return them. toArray(new Object[0]) behaves exactly the
same way as toArray() does.
Parameters:
array - the array.
Returns:
an array of the elements from this Collection.
Throws:
ArrayStoreException - if the type of an element in this Collection cannot be
stored in the type of the specified array.
Method Detail
285
Class Calendar
java.lang.Object
java.util.Calendar
Calendar is an abstract base class for converting between a Date object and a set of integer fields
such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a specific instant in time
with millisecond precision. See Date for information about the Date class.) Subclasses of Calendar
interpret a Date according to the rules of a specific calendar system. Like other locale-sensitive
classes, Calendar provides a class method, getInstance, for getting a generally useful object of this
type. A Calendar object can produce all the time field values needed to implement the date-time
formatting for a particular language and calendar style (for example, Japanese-Gregorian,
Japanese-Traditional). When computing a Date from time fields, there may be insufficient information
to compute the Date (such as only year and month but no day in the month). Insufficient information.
The calendar will use default information to specify the missing fields. This may vary by calendar; for
the Gregorian calendar, the default for a field is the same as that of the start of the epoch: i.e., YEAR
= 1970, MONTH = JANUARY, DATE = 1, etc. Note: The ambiguity in interpretation of what day
midnight belongs to, is resolved as so: midnight "belongs" to the following day. 23:59 on Dec 31, 1969
00:00 on Jan 1, 1970. 12:00 PM is midday, and 12:00 AM is midnight. 11:59 PM on Jan 1 12:00 AM
on Jan 2 12:01 AM on Jan 2. 11:59 AM on Mar 10 12:00 PM on Mar 10 12:01 PM on Mar 10. 24:00 or
greater are invalid. Hours greater than 12 are invalid in AM/PM mode. Setting the time will never
change the date. If equivalent times are entered in AM/PM or 24 hour mode, equality will be
determined by the actual time rather than the entered time. This class has been subset for J2ME
based on the JDK 1.3 Calendar class. Many methods and variables have been pruned, and other
methods simplified, in an effort to reduce the size of this class. Version: CLDC 1.1 02/01/2002 (based
on JDK 1.3) See Also:Date, TimeZone
Field Summary
Modifier and
Type
static int
Value of the AM_PM field indicating the period of the day from midnight
to just before noon.
AM_PM
static int
static int
static int
static int
static int
static int
static int
static int
protected int[]
Class Calendar
Field number for get and set indicating whether the HOUR is before or
after noon.
APRIL
Value of the MONTH field indicating the fourth month of the year.
AUGUST
Value of the MONTH field indicating the eighth month of the year.
DATE
Field number for get and set indicating the day of the month.
DAY_OF_MONTH
Field number for get and set indicating the day of the month.
DAY_OF_WEEK
Field number for get and set indicating the day of the week.
DECEMBER
Value of the MONTH field indicating the twelfth month of the year.
FEBRUARY
Value of the MONTH field indicating the second month of the year.
fields
The field values for the currently set time for this calendar.
286
FRIDAY
static int
static int
protected
boolean[]
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
Field number for get and set indicating the hour of the morning or
afternoon.
HOUR_OF_DAY
Field number for get and set indicating the hour of the day.
isSet
The flags which tell if a specified time field for the calendar is set.
JANUARY
Value of the MONTH field indicating the first month of the year.
JULY
Value of the MONTH field indicating the seventh month of the year.
JUNE
Value of the MONTH field indicating the sixth month of the year.
MARCH
Value of the MONTH field indicating the third month of the year.
MAY
Value of the MONTH field indicating the fifth month of the year.
MILLISECOND
Field number for get and set indicating the millisecond within the second.
MINUTE
Field number for get and set indicating the minute within the hour.
MONDAY
Value of the MONTH field indicating the eleventh month of the year.
OCTOBER
Value of the MONTH field indicating the tenth month of the year.
PM
static int
static int
static int
static int
static int
static int
Value of the AM_PM field indicating the period of the day from noon to
just before midnight.
SATURDAY
Field number for get and set indicating the second within the minute.
SEPTEMBER
Value of the MONTH field indicating the ninth month of the year.
SUNDAY
protected long
static int
static int
static int
The currently set time for this calendar, expressed in milliseconds after
January 1, 1970, 0:00:00 GMT.
TUESDAY
Constructor Summary
Modifier
Field Summary
287
Calendar()
Method Summary
Modifier and
Type
void
boolean
boolean
protected
abstract void
protected
abstract void
boolean
after(Object when)
Converts the current millisecond time value time to field values in fields[].
computeTime()
Converts the current field values in fields[] to the millisecond time value
time.
equals(Object obj)
int
static Calendar
static Calendar
getInstance()
Date
protected long
TimeZone
void
void
protected void
setTimeInMillis(long millis)
Sets this Calendar's current time from the given long value.
setTimeZone(TimeZone value)
void
Sets the time zone with the given time zone value.
Field Detail
AM
public static final int AM
Value of the AM_PM field indicating the period of the day from midnight to just before
noon. See Also:Constant Field Values
See Also:
Constant Field Values
Constructor Summary
288
Field number for get and set indicating whether the HOUR is before or after noon.
E.g., at 10:04:15.250 PM the AM_PM is PM. See Also:AM, PM, HOUR, Constant
Field Values
See Also:
Constant Field Values
APRIL
public static final int APRIL
Value of the MONTH field indicating the fourth month of the year. See Also:Constant
Field Values
See Also:
Constant Field Values
AUGUST
public static final int AUGUST
Value of the MONTH field indicating the eighth month of the year. See Also:Constant
Field Values
See Also:
Constant Field Values
DATE
public static final int DATE
Field number for get and set indicating the day of the month. This is a synonym for
DAY_OF_MONTH. See Also:DAY_OF_MONTH, Constant Field Values
See Also:
Constant Field Values
DAY_OF_MONTH
public static final int DAY_OF_MONTH
Field number for get and set indicating the day of the month. This is a synonym for
DATE. See Also:DATE, Constant Field Values
See Also:
Constant Field Values
DAY_OF_WEEK
public static final int DAY_OF_WEEK
Field number for get and set indicating the day of the week. See Also:Constant Field
Values
See Also:
Constant Field Values
DECEMBER
public static final int DECEMBER
Value of the MONTH field indicating the twelfth month of the year. See Also:Constant
Field Values
See Also:
Constant Field Values
FEBRUARY
public static final int FEBRUARY
Value of the MONTH field indicating the second month of the year. See
Also:Constant Field Values
See Also:
Constant Field Values
Field Detail
289
The field values for the currently set time for this calendar.
FRIDAY
public static final int FRIDAY
Value of the DAY_OF_WEEK field indicating Friday. See Also:Constant Field Values
See Also:
Constant Field Values
HOUR
public static final int HOUR
Field number for get and set indicating the hour of the morning or afternoon. HOUR is
used for the 12-hour clock. E.g., at 10:04:15.250 PM the HOUR is 10. See
Also:AM_PM, HOUR_OF_DAY, Constant Field Values
See Also:
Constant Field Values
HOUR_OF_DAY
public static final int HOUR_OF_DAY
Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used
for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22. See
Also:Constant Field Values
See Also:
Constant Field Values
isSet
protected boolean[] isSet
The flags which tell if a specified time field for the calendar is set. This is an array of
FIELD_COUNT booleans,
JANUARY
public static final int JANUARY
Value of the MONTH field indicating the first month of the year. See Also:Constant
Field Values
See Also:
Constant Field Values
JULY
public static final int JULY
Value of the MONTH field indicating the seventh month of the year. See
Also:Constant Field Values
See Also:
Constant Field Values
JUNE
public static final int JUNE
Value of the MONTH field indicating the sixth month of the year. See Also:Constant
Field Values
See Also:
Constant Field Values
MARCH
public static final int MARCH
Value of the MONTH field indicating the third month of the year. See Also:Constant
Field Values
See Also:
Field Detail
290
Value of the MONTH field indicating the fifth month of the year. See Also:Constant
Field Values
See Also:
Constant Field Values
MILLISECOND
public static final int MILLISECOND
Field number for get and set indicating the millisecond within the second. E.g., at
10:04:15.250 PM the MILLISECOND is 250. See Also:Constant Field Values
See Also:
Constant Field Values
MINUTE
public static final int MINUTE
Field number for get and set indicating the minute within the hour. E.g., at
10:04:15.250 PM the MINUTE is 4. See Also:Constant Field Values
See Also:
Constant Field Values
MONDAY
public static final int MONDAY
Field number for get and set indicating the month. This is a calendar-specific value.
See Also:Constant Field Values
See Also:
Constant Field Values
NOVEMBER
public static final int NOVEMBER
Value of the MONTH field indicating the eleventh month of the year. See
Also:Constant Field Values
See Also:
Constant Field Values
OCTOBER
public static final int OCTOBER
Value of the MONTH field indicating the tenth month of the year. See Also:Constant
Field Values
See Also:
Constant Field Values
PM
public static final int PM
Value of the AM_PM field indicating the period of the day from noon to just before
midnight. See Also:Constant Field Values
See Also:
Constant Field Values
Field Detail
291
Field number for get and set indicating the second within the minute. E.g., at
10:04:15.250 PM the SECOND is 15. See Also:Constant Field Values
See Also:
Constant Field Values
SEPTEMBER
public static final int SEPTEMBER
Value of the MONTH field indicating the ninth month of the year. See Also:Constant
Field Values
See Also:
Constant Field Values
SUNDAY
public static final int SUNDAY
The currently set time for this calendar, expressed in milliseconds after January 1,
1970, 0:00:00 GMT.
TUESDAY
public static final int TUESDAY
Field Detail
292
Constructor Detail
Calendar
protected Calendar()
Method Detail
after
public boolean after(Object when)
Converts the current millisecond time value time to field values in fields[]. This allows
you to sync up the time field values with a new time that is set for the calendar.
computeTime
protected abstract void computeTime()
Converts the current field values in fields[] to the millisecond time value time.
equals
public boolean equals(Object obj)
Compares this calendar to the specified object. The result is true if and only if the
argument is not null and is a Calendar object that represents the same calendar as
this object.
Overrides:
equals in class Object
get
public final int get(int field)
Constructor Detail
293
Gets this Calendar's current time as a long expressed in milliseconds after January 1,
1970, 0:00:00 GMT (the epoch).
getTimeZone
public TimeZone getTimeZone()
Sets this Calendar's current time with the given Date. Note: Calling setTime() with
Date(Long.MAX_VALUE) or Date(Long.MIN_VALUE) may yield incorrect field values
from get().
setTimeInMillis
protected void setTimeInMillis(long millis)
Sets this Calendar's current time from the given long value.
setTimeZone
public void setTimeZone(TimeZone value)
Sets the time zone with the given time zone value.
Method Detail
294
Class BitSet
java.lang.Object
java.util.BitSet
public class
extends Object
The BitSet class implements a bit field. Each element in a BitSet can be on(1) or off(0). A BitSet is
created with a given size and grows if this size is exceeded. Growth is always rounded to a 64 bit
boundary.
Constructor Summary
Constructor and Description
BitSet()
Method Summary
Modifier and
Type
void
void
int
void
void
void
boolean
void
void
boolean
Clears all bits in the receiver which are also set in the parameter BitSet.
cardinality()
Compares the argument to this BitSet and returns whether they are equal.
flip(int pos)
to pos2.
get(int pos)
BitSet
int
boolean
Retrieves the bits starting from pos1 to pos2 and returns back a new bitset
made of these bits.
hashCode()
position.
boolean
Class BitSet
isEmpty()
295
int
Returns the number of bits up to and including the highest bit set.
nextClearBit(int pos)
int
Returns the position of the first bit that is false on or after pos.
nextSetBit(int pos)
int
Returns the position of the first bit that is true on or after pos.
or(BitSet bs)
void
void
void
void
void
size()
int
String
xor(BitSet bs)
void
Constructor Detail
BitSet
public BitSet()
Create a new BitSet with size equal to nbits. If nbits is not a multiple of 64, then
create a BitSet with size nbits rounded to the next closest multiple of 64.
Parameters:
nbits - the size of the bit set.
Throws:
NegativeArraySizeException - if nbits is negative.
See Also:
clear(int), set(int), clear(), clear(int, int), set(int, boolean),
set(int, int), set(int, int, boolean)
Method Detail
Method Summary
296
Compares the argument to this BitSet and returns whether they are equal. The
object must be an instance of BitSet with the same bits set.
Overrides:
equals in class Object
Parameters:
obj - the BitSet object to compare.
Returns:
a boolean indicating whether or not this BitSet and obj are equal.
See Also:
hashCode()
hashCode
public int hashCode()
Computes the hash code for this BitSet. If two BitSets are equal the have to return
the same result for hashCode().
Overrides:
hashCode in class Object
Returns:
the int representing the hash code for this bit set.
See Also:
equals(java.lang.Object), Hashtable
get
public boolean get(int pos)
Retrieves the bit at index pos. Grows the BitSet if pos > size.
Parameters:
pos - the index of the bit to be retrieved.
Returns:
true if the bit at pos is set, false otherwise.
Throws:
IndexOutOfBoundsException - if pos is negative.
See Also:
clear(int), set(int), clear(), clear(int, int), set(int, boolean),
set(int, int), set(int, int, boolean)
get
public BitSet get(int pos1,
int pos2)
Retrieves the bits starting from pos1 to pos2 and returns back a new bitset made of
these bits. Grows the BitSet if pos2 > size.
Parameters:
pos1 - beginning position.
pos2 - ending position.
Returns:
new bitset of the range specified.
Throws:
IndexOutOfBoundsException - if pos1 or pos2 is negative, or if pos2 is smaller
than pos1.
See Also:
get(int)
set
public void set(int pos)
Sets the bit at index pos to 1. Grows the BitSet if pos > size.
Parameters:
pos - the index of the bit to set.
Throws:
IndexOutOfBoundsException - if pos is negative.
See Also:
Method Detail
297
set
public void set(int pos,
boolean val)
Sets the bit at index pos to val. Grows the BitSet if pos > size.
Parameters:
pos - the index of the bit to set.
val - value to set the bit.
Throws:
IndexOutOfBoundsException - if pos is negative.
See Also:
set(int)
set
public void set(int pos1,
int pos2)
Sets the bits starting from pos1 to pos2. Grows the BitSet if pos2 > size.
Parameters:
pos1 - beginning position.
pos2 - ending position.
Throws:
IndexOutOfBoundsException - if pos1 or pos2 is negative, or if pos2 is smaller
than pos1.
See Also:
set(int)
set
public void set(int pos1,
int pos2,
boolean val)
Sets the bits starting from pos1 to pos2 to the given val. Grows the BitSet if pos2 >
size.
Parameters:
pos1 - beginning position.
pos2 - ending position.
val - value to set these bits.
Throws:
IndexOutOfBoundsException - if pos1 or pos2 is negative, or if pos2 is smaller
than pos1.
See Also:
set(int,int)
clear
public void clear()
Clears the bit at index pos. Grows the BitSet if pos > size.
Parameters:
pos - the index of the bit to clear.
Throws:
IndexOutOfBoundsException - if pos is negative.
See Also:
clear(int, int)
clear
public void clear(int pos1,
int pos2)
Method Detail
298
flip
public void flip(int pos)
Flips the bit at index pos. Grows the BitSet if pos > size.
Parameters:
pos - the index of the bit to flip.
Throws:
IndexOutOfBoundsException - if pos is negative.
See Also:
flip(int, int)
flip
public void flip(int pos1,
int pos2)
Flips the bits starting from pos1 to pos2. Grows the BitSet if pos2 > size.
Parameters:
pos1 - beginning position.
pos2 - ending position.
Throws:
IndexOutOfBoundsException - if pos1 or pos2 is negative, or if pos2 is smaller
than pos1.
See Also:
flip(int)
intersects
public boolean intersects(BitSet bs)
Checks if these two BitSets have at least one bit set to true in the same position.
Parameters:
bs - BitSet used to calculate the intersection.
Returns:
true if bs intersects with this BitSet, false otherwise.
and
public void and(BitSet bs)
Performs the logical AND of this BitSet with another BitSet. The values of this
BitSet are changed accordingly.
Parameters:
bs - BitSet to AND with.
See Also:
or(java.util.BitSet), xor(java.util.BitSet)
andNot
public void andNot(BitSet bs)
Clears all bits in the receiver which are also set in the parameter BitSet. The values
of this BitSet are changed accordingly.
Parameters:
bs - BitSet to ANDNOT with.
or
public void or(BitSet bs)
Performs the logical OR of this BitSet with another BitSet. The values of this BitSet
are changed accordingly.
Method Detail
299
xor
public void xor(BitSet bs)
Performs the logical XOR of this BitSet with another BitSet. The values of this
BitSet are changed accordingly.
Parameters:
bs - BitSet to XOR with.
See Also:
or(java.util.BitSet), and(java.util.BitSet)
size
public int size()
length
public int length()
Returns the number of bits up to and including the highest bit set.
Returns:
the length of the BitSet.
toString
public String toString()
Returns the position of the first bit that is true on or after pos.
Parameters:
pos - the starting position (inclusive).
Returns:
-1 if there is no bits that are set to true on or after pos.
nextClearBit
public int nextClearBit(int pos)
Returns the position of the first bit that is false on or after pos.
Parameters:
pos - the starting position (inclusive).
Returns:
the position of the next bit set to false, even if it is further than this BitSet's
size.
isEmpty
public boolean isEmpty()
Returns true if all the bits in this BitSet are set to false.
Returns:
true if the BitSet is empty, false otherwise.
Method Detail
300
Method Detail
301
Class Arrays
java.lang.Object
java.util.Arrays
public class
extends Object
Arrays
Since:
1.2
Method Summary
Modifier and
Type
static
<T> List<T>
static int
Performs a binary search for the specified element in a part of the specified
sorted array.
binarySearch(char[] array, char value)
static int
static int
Performs a binary search for the specified element in the specified sorted
array.
binarySearch(char[] array, int startIndex, int endIndex,
char value)
Performs a binary search for the specified element in a part of the specified
sorted array.
binarySearch(double[] array, double value)
static int
static int
Performs a binary search for the specified element in the specified sorted
array.
binarySearch(double[] array, int startIndex, int endIndex,
double value)
Performs a binary search for the specified element in a part of the specified
sorted array.
binarySearch(float[] array, float value)
static int
static int
Performs a binary search for the specified element in the specified sorted
array.
binarySearch(float[] array, int startIndex, int endIndex,
float value)
Performs a binary search for the specified element in a part of the specified
sorted array.
binarySearch(int[] array, int value)
static int
Performs a binary search for the specified element in the specified sorted
array.
binarySearch(int[] array, int startIndex, int endIndex, int value)
static int
static int
Class Arrays
Performs a binary search for the specified element in a part of the specified
sorted array.
binarySearch(long[] array, int startIndex, int endIndex,
long value)
Performs a binary search for the specified element in a part of the specified
sorted array.
302
static int
Performs a binary search for the specified element in the specified sorted
array.
binarySearch(Object[] array, int startIndex, int endIndex,
Object object)
Performs a binary search for the specified element in a part of the specified
sorted array.
binarySearch(Object[] array, Object object)
static int
static int
Performs a binary search for the specified element in the specified sorted
array.
binarySearch(short[] array, int startIndex, int endIndex,
short value)
Performs a binary search for the specified element in a part of the specified
sorted array.
binarySearch(short[] array, short value)
static int
static
boolean[]
Performs a binary search for the specified element in the specified sorted
array.
binarySearch(T[] array, int startIndex, int endIndex, T object,
Comparator<? super T> comparator)
Performs a binary search for the specified element in a part of the specified
sorted array using the Comparator to compare elements.
binarySearch(T[] array, T object, Comparator<? super
T> comparator)
Performs a binary search for the specified element in the specified sorted
array using the Comparator to compare elements.
copyOfRange(boolean[] original, int start, int end)
static byte[]
static char[]
static
double[]
static float[]
static int[]
static long[]
static short[]
static boolean
static int
static String
to one another.
deepHashCode(Object[] array)
Returns a hash code based on the "deep contents" of the given array.
deepToString(Object[] array)
Creates a "deep" String representation of the Object[] passed, such that
if the array contains other arrays, the String representation of those arrays
is generated as well.
static boolean
static boolean
Method Summary
303
Method Summary
Fills the specified range in the array with the specified element.
fill(byte[] array, byte value)
Fills the specified range in the array with the specified element.
fill(char[] array, char value)
Fills the specified range in the array with the specified element.
fill(double[] array, double value)
Fills the specified range in the array with the specified element.
fill(float[] array, float value)
Fills the specified range in the array with the specified element.
fill(int[] array, int value)
Fills the specified range in the array with the specified element.
fill(long[] array, int start, int end, long value)
Fills the specified range in the array with the specified element.
fill(long[] array, long value)
Fills the specified range in the array with the specified element.
fill(Object[] array, Object value)
Fills the specified range in the array with the specified element.
fill(short[] array, short value)
304
hashCode(float[] array)
static
<T> void
static
<T> void
static String
toString(boolean[] array)
Creates a String representation
static String
toString(byte[] array)
Creates a String representation
static String
toString(char[] array)
Creates a String representation
static String
toString(double[] array)
Creates a String representation
static String
toString(float[] array)
Creates a String representation
static String
toString(int[] array)
Method Summary
305
toString(long[] array)
Creates a String representation
static String
toString(Object[] array)
Creates a String representation
static String
toString(short[] array)
Creates a String representation
Method Detail
asList
public static <T> List<T> asList(T... array)
Returns a List of the objects in the specified array. The size of the List cannot be
modified, i.e. adding and removing are unsupported, but the elements can be set.
Setting an element modifies the underlying array.
Parameters:
array - the array.
Returns:
a List of the elements of the specified array.
binarySearch
public static int binarySearch(byte[] array,
byte value)
Performs a binary search for the specified element in the specified ascending sorted
array. Searching in an unsorted array has an undefined result. It's also undefined
which element is found if there are multiple occurrences of the same element.
Parameters:
array - the sorted byte array to search.
value - the byte element to find.
Returns:
the non-negative index of the element, or a negative index which is -index 1 where the element would be inserted.
binarySearch
public static int binarySearch(char[] array,
char value)
Performs a binary search for the specified element in the specified sorted array.
Parameters:
array - the sorted char array to search
value - the char element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
binarySearch
public static int binarySearch(double[] array,
double value)
Performs a binary search for the specified element in the specified sorted array.
Parameters:
array - the sorted double array to search
value - the double element to find
Returns:
306
Performs a binary search for the specified element in the specified sorted array.
Parameters:
array - the sorted float array to search
value - the float element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
binarySearch
public static int binarySearch(int[] array,
int value)
Performs a binary search for the specified element in the specified sorted array.
Parameters:
array - the sorted int array to search
value - the int element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
binarySearch
public static int binarySearch(long[] array,
long value)
Performs a binary search for the specified element in the specified sorted array.
Parameters:
array - the sorted long array to search
value - the long element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
binarySearch
public static int binarySearch(Object[] array,
Object object)
Performs a binary search for the specified element in the specified sorted array.
Parameters:
array - the sorted Object array to search
object - the Object element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
Throws:
ClassCastException - when an element in the array or the search element
does not implement Comparable, or cannot be compared to each other
binarySearch
public static <T> int binarySearch(T[] array,
T object,
Comparator<? super T> comparator)
Performs a binary search for the specified element in the specified sorted array using
the Comparator to compare elements.
Type Parameters:
T - type of object
Parameters:
array - the sorted Object array to search
object - the char element to find
Method Detail
307
Performs a binary search for the specified element in the specified sorted array.
Parameters:
array - the sorted short array to search
value - the short element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
binarySearch
public static int binarySearch(byte[] array,
int startIndex,
int endIndex,
byte value)
Performs a binary search for the specified element in a part of the specified sorted
array.
Parameters:
array - the sorted byte array to search
startIndex - the inclusive start index
endIndex - the exclusive end index
value - the byte element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
Throws:
IllegalArgumentException - - if startIndex is bigger than endIndex
ArrayIndexOutOfBoundsException - - if startIndex is smaller than zero or or
endIndex is bigger than length of array
Since:
1.6
binarySearch
public static int binarySearch(char[] array,
int startIndex,
int endIndex,
char value)
Performs a binary search for the specified element in a part of the specified sorted
array.
Parameters:
array - the sorted char array to search
startIndex - the inclusive start index
endIndex - the exclusive end index
value - the char element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
Throws:
IllegalArgumentException - - if startIndex is bigger than endIndex
ArrayIndexOutOfBoundsException - - if startIndex is smaller than zero or or
endIndex is bigger than length of array
Since:
1.6
Method Detail
308
Performs a binary search for the specified element in a part of the specified sorted
array.
Parameters:
array - the sorted double array to search
startIndex - the inclusive start index
endIndex - the exclusive end index
value - the double element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
Throws:
IllegalArgumentException - - if startIndex is bigger than endIndex
ArrayIndexOutOfBoundsException - - if startIndex is smaller than zero or or
endIndex is bigger than length of array
Since:
1.6
binarySearch
public static int binarySearch(float[] array,
int startIndex,
int endIndex,
float value)
Performs a binary search for the specified element in a part of the specified sorted
array.
Parameters:
array - the sorted float array to search
startIndex - the inclusive start index
endIndex - the exclusive end index
value - the float element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
Throws:
IllegalArgumentException - - if startIndex is bigger than endIndex
ArrayIndexOutOfBoundsException - - if startIndex is smaller than zero or or
endIndex is bigger than length of array
Since:
1.6
binarySearch
public static int binarySearch(int[] array,
int startIndex,
int endIndex,
int value)
Performs a binary search for the specified element in a part of the specified sorted
array.
Parameters:
array - the sorted int array to search
startIndex - the inclusive start index
endIndex - the exclusive end index
value - the int element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
Throws:
IllegalArgumentException - - if startIndex is bigger than endIndex
ArrayIndexOutOfBoundsException - - if startIndex is smaller than zero or or
endIndex is bigger than length of array
Since:
Method Detail
309
Performs a binary search for the specified element in a part of the specified sorted
array.
Parameters:
array - the sorted long array to search
startIndex - the inclusive start index
endIndex - the exclusive end index
value - the long element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
Throws:
IllegalArgumentException - - if startIndex is bigger than endIndex
ArrayIndexOutOfBoundsException - - if startIndex is smaller than zero or or
endIndex is bigger than length of array
Since:
1.6
binarySearch
public static int binarySearch(Object[] array,
int startIndex,
int endIndex,
Object object)
Performs a binary search for the specified element in a part of the specified sorted
array.
Parameters:
array - the sorted Object array to search
startIndex - the inclusive start index
endIndex - the exclusive end index
object - the object element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
Throws:
ClassCastException - when an element in the array or the search element
does not implement Comparable, or cannot be compared to each other
IllegalArgumentException - - if startIndex is bigger than endIndex
ArrayIndexOutOfBoundsException - - if startIndex is smaller than zero or or
endIndex is bigger than length of array
Since:
1.6
binarySearch
public static <T> int binarySearch(T[] array,
int startIndex,
int endIndex,
T object,
Comparator<? super T> comparator)
Performs a binary search for the specified element in a part of the specified sorted
array using the Comparator to compare elements.
Type Parameters:
T - type of object
Parameters:
array - the sorted Object array to search
startIndex - the inclusive start index
endIndex - the exclusive end index
object - the value element to find
comparator - the Comparator
Method Detail
310
Performs a binary search for the specified element in a part of the specified sorted
array.
Parameters:
array - the sorted short array to search
startIndex - the inclusive start index
endIndex - the exclusive end index
value - the short element to find
Returns:
the non-negative index of the element, or a negative index which is the -index
- 1 where the element would be inserted
Throws:
IllegalArgumentException - - if startIndex is bigger than endIndex
ArrayIndexOutOfBoundsException - - if startIndex is smaller than zero or or
endIndex is bigger than length of array
Since:
1.6
fill
public static void fill(byte[] array,
byte value)
Fills the specified range in the array with the specified element.
Parameters:
array - the byte array to fill.
start - the first index to fill.
end - the last + 1 index to fill.
value - the byte element.
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
fill
public static void fill(short[] array,
short value)
Method Detail
311
Fills the specified range in the array with the specified element.
Parameters:
array - the short array to fill.
start - the first index to fill.
end - the last + 1 index to fill.
value - the short element.
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
fill
public static void fill(char[] array,
char value)
Fills the specified range in the array with the specified element.
Parameters:
array - the char array to fill.
start - the first index to fill.
end - the last + 1 index to fill.
value - the char element.
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
fill
public static void fill(int[] array,
int value)
Fills the specified range in the array with the specified element.
Parameters:
array - the int array to fill.
start - the first index to fill.
end - the last + 1 index to fill.
value - the int element.
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
Method Detail
312
Fills the specified range in the array with the specified element.
Parameters:
array - the long array to fill.
start - the first index to fill.
end - the last + 1 index to fill.
value - the long element.
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
fill
public static void fill(float[] array,
float value)
Fills the specified range in the array with the specified element.
Parameters:
array - the float array to fill.
start - the first index to fill.
end - the last + 1 index to fill.
value - the float element.
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
fill
public static void fill(double[] array,
double value)
Fills the specified range in the array with the specified element.
Parameters:
array - the double array to fill.
Method Detail
313
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0
fill
public static void fill(boolean[] array,
boolean value)
Fills the specified range in the array with the specified element.
Parameters:
array - the boolean array to fill.
start - the first index to fill.
end - the last + 1 index to fill.
value - the boolean element.
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
fill
public static void fill(Object[] array,
Object value)
Fills the specified range in the array with the specified element.
Parameters:
array - the Object array to fill.
start - the first index to fill.
end - the last + 1 index to fill.
value - the Object element.
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
hashCode
public static int hashCode(boolean[] array)
Returns a hash code based on the contents of the given array. For any two boolean
arrays a and b, if Arrays.equals(a, b) returns true, it means that the return value of
Arrays.hashCode(a) equals Arrays.hashCode(b).
The value returned by this method is the same value as the List.hashCode()}
method which is invoked on a List} containing a sequence of Boolean} instances
representing the elements of array in the same order. If the array is null, the return
value is 0.
Method Detail
314
Returns a hash code based on the contents of the given array. For any two not-null
int arrays a and b, if Arrays.equals(a, b) returns true, it means that the return
value of Arrays.hashCode(a) equals Arrays.hashCode(b).
The value returned by this method is the same value as the List.hashCode()}
method which is invoked on a List} containing a sequence of Integer} instances
representing the elements of array in the same order. If the array is null, the return
value is 0.
Parameters:
array - the array whose hash code to compute.
Returns:
the hash code for array.
hashCode
public static int hashCode(short[] array)
Returns a hash code based on the contents of the given array. For any two short
arrays a and b, if Arrays.equals(a, b) returns true, it means that the return value of
Arrays.hashCode(a) equals Arrays.hashCode(b).
The value returned by this method is the same value as the List.hashCode()}
method which is invoked on a List} containing a sequence of Short} instances
representing the elements of array in the same order. If the array is null, the return
value is 0.
Parameters:
array - the array whose hash code to compute.
Returns:
the hash code for array.
hashCode
public static int hashCode(char[] array)
Returns a hash code based on the contents of the given array. For any two char
arrays a and b, if Arrays.equals(a, b) returns true, it means that the return value of
Arrays.hashCode(a) equals Arrays.hashCode(b).
The value returned by this method is the same value as the List.hashCode()}
method which is invoked on a List} containing a sequence of Character} instances
representing the elements of array in the same order. If the array is null, the return
value is 0.
Parameters:
array - the array whose hash code to compute.
Returns:
the hash code for array.
hashCode
public static int hashCode(byte[] array)
Returns a hash code based on the contents of the given array. For any two byte
arrays a and b, if Arrays.equals(a, b) returns true, it means that the return value of
Arrays.hashCode(a) equals Arrays.hashCode(b).
The value returned by this method is the same value as the List.hashCode()}
method which is invoked on a List} containing a sequence of Byte} instances
representing the elements of array in the same order. If the array is null, the return
Method Detail
315
Returns a hash code based on the contents of the given array. For any two long
arrays a and b, if Arrays.equals(a, b) returns true, it means that the return value of
Arrays.hashCode(a) equals Arrays.hashCode(b).
The value returned by this method is the same value as the List.hashCode()}
method which is invoked on a List} containing a sequence of Long} instances
representing the elements of array in the same order. If the array is null, the return
value is 0.
Parameters:
array - the array whose hash code to compute.
Returns:
the hash code for array.
hashCode
public static int hashCode(float[] array)
Returns a hash code based on the contents of the given array. For any two float
arrays a and b, if Arrays.equals(a, b) returns true, it means that the return value of
Arrays.hashCode(a) equals Arrays.hashCode(b).
The value returned by this method is the same value as the List.hashCode()}
method which is invoked on a List} containing a sequence of Float} instances
representing the elements of array in the same order. If the array is null, the return
value is 0.
Parameters:
array - the array whose hash code to compute.
Returns:
the hash code for array.
hashCode
public static int hashCode(double[] array)
Returns a hash code based on the contents of the given array. For any two double
arrays a and b, if Arrays.equals(a, b) returns true, it means that the return value of
Arrays.hashCode(a) equals Arrays.hashCode(b).
The value returned by this method is the same value as the List.hashCode()}
method which is invoked on a List} containing a sequence of Double} instances
representing the elements of array in the same order. If the array is null, the return
value is 0.
Parameters:
array - the array whose hash code to compute.
Returns:
the hash code for array.
hashCode
public static int hashCode(Object[] array)
Returns a hash code based on the contents of the given array. If the array contains
other arrays as its elements, the hash code is based on their identities not their
contents. So it is acceptable to invoke this method on an array that contains itself as
an element, either directly or indirectly.
Method Detail
316
Returns a hash code based on the "deep contents" of the given array. If the array
contains other arrays as its elements, the hash code is based on their contents not
their identities. So it is not acceptable to invoke this method on an array that contains
itself as an element, either directly or indirectly.
For any two arrays a and b, if Arrays.deepEquals(a, b) returns true, it means that
the return value of Arrays.deepHashCode(a) equals Arrays.deepHashCode(b).
The computation of the value returned by this method is similar to that of the value
returned by List.hashCode()} invoked on a List} containing a sequence of instances
representing the elements of array in the same order. The difference is: If an element
e of array is itself an array, its hash code is computed by calling the appropriate
overloading of Arrays.hashCode(e) if e is an array of a primitive type, or by calling
Arrays.deepHashCode(e) recursively if e is an array of a reference type. The value
returned by this method is the same value as the method
Arrays.asList(array).hashCode(). If the array is null, the return value is 0.
Parameters:
array - the array whose hash code to compute.
Returns:
the hash code for array.
equals
public static boolean equals(byte[] array1,
byte[] array2)
Method Detail
317
Returns:
if both arrays are null or if the arrays have the same length and the
elements at each index in the two arrays are equal, false otherwise.
true
equals
public static boolean equals(int[] array1,
int[] array2)
Compares the two arrays. The values are compared in the same manner as
Float.equals().
Parameters:
array1 - the first float array.
array2 - the second float array.
Returns:
true if both arrays are null or if the arrays have the same length and the
elements at each index in the two arrays are equal, false otherwise.
See Also:
Float.equals(Object)
equals
public static boolean equals(double[] array1,
double[] array2)
Compares the two arrays. The values are compared in the same manner as
Double.equals().
Parameters:
array1 - the first double array.
array2 - the second double array.
Returns:
true if both arrays are null or if the arrays have the same length and the
elements at each index in the two arrays are equal, false otherwise.
See Also:
Double.equals(Object)
equals
public static boolean equals(boolean[] array1,
boolean[] array2)
Method Detail
318
equals
public static boolean equals(Object[] array1,
Object[] array2)
Returns true if the two given arrays are deeply equal to one another. Unlike the
method equals(Object[] array1, Object[] array2), this method is appropriate for
use for nested arrays of arbitrary depth.
Two array references are considered deeply equal if they are both null, or if they
refer to arrays that have the same length and the elements at each index in the two
arrays are equal.
Two null elements element1 and element2 are possibly deeply equal if any of the
following conditions satisfied:
element1 and element2 are both arrays of object reference types,
Arrays.deepEquals(element1, element2) would return true.
and
and element2 are arrays of the same primitive type, and the appropriate
overloading of Arrays.equals(element1, element2) would return true.
element1
element1 == element2
element1.equals(element2)
Returns:
if both arrays are null or if the arrays have the same length and the
elements at each index in the two arrays are equal according to equals(),
false otherwise.
true
sort
public static void sort(byte[] array)
Method Detail
319
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0
sort
public static void sort(char[] array)
sort
public static void sort(double[] array,
int start,
int end)
Sorts the specified range in the array in ascending numerical order. The values are
sorted according to the order imposed by Double.compareTo().
Parameters:
array - the double array to be sorted.
start - the start index to sort.
end - the last + 1 index to sort.
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
See Also:
Double#compareTo(Double)
sort
public static void sort(float[] array)
sort
public static void sort(float[] array,
int start,
int end)
Method Detail
320
sort
public static void sort(int[] array)
Method Detail
321
Sorts the specified range in the array in ascending natural order. All elements must
implement the Comparable interface and must be comparable to each other without a
ClassCastException being thrown.
Parameters:
array - the Object array to be sorted.
start - the start index to sort.
end - the last + 1 index to sort.
Throws:
ClassCastException - if an element in the array does not implement
Comparable or some elements cannot be compared to each other.
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
sort
public static <T> void sort(T[] array,
int start,
int end,
Comparator<? super T> comparator)
Sorts the specified range in the array using the specified Comparator. All elements
must be comparable to each other without a ClassCastException being thrown.
Parameters:
array - the Object array to be sorted.
start - the start index to sort.
end - the last + 1 index to sort.
comparator - the Comparator.
Throws:
ClassCastException - if elements in the array cannot be compared to each
other using the Comparator.
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0 or end > array.length.
sort
public static <T> void sort(T[] array,
Comparator<? super T> comparator)
Sorts the specified array using the specified Comparator. All elements must be
comparable to each other without a ClassCastException being thrown.
Parameters:
array - the Object array to be sorted.
comparator - the Comparator.
Throws:
ClassCastException - if elements in the array cannot be compared to each
other using the Comparator.
sort
public static void sort(short[] array)
Method Detail
322
Throws:
IllegalArgumentException - if start > end.
ArrayIndexOutOfBoundsException - if start < 0
toString
public static String toString(boolean[] array)
Method Detail
323
Method Detail
324
Creates a "deep" String representation of the Object[] passed, such that if the array
contains other arrays, the String representation of those arrays is generated as well.
If any of the elements are primitive arrays, the generation is delegated to the other
toString methods in this class. If any element contains a reference to the original
array, then it will be represented as "[...]". If an element is an Object[], then its
representation is generated by a recursive call to this method. All other elements are
converted via the String.valueOf(Object) method.
Parameters:
array - the Object array to convert.
Returns:
the String representation of array.
Since:
1.5
copyOfRange
public static boolean[] copyOfRange(boolean[] original,
int start,
int end)
Method Detail
325
Method Detail
326
Method Detail
327
than end
Since:
1.6
Method Detail
328
Class ArrayList<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.ArrayList<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, List<E>, RandomAccess
public class
extends AbstractList<E>
implements List<E>, RandomAccess
ArrayList is an implementation of List, backed by an array. All optional operations adding, removing,
and replacing are supported. The elements can be any objects.
Since:
1.2
Field Summary
Constructor Summary
Constructor and Description
ArrayList()
ArrayList(int capacity)
Method Summary
Modifier and
Type
boolean
void
boolean
Inserts the specified object into this ArrayList at the specified location.
addAll(Collection<? extends E> collection)
boolean
void
Inserts the objects in the specified collection at the specified location in this
List.
clear()
boolean
contains(Object object)
Searches this ArrayList for
void
ensureCapacity(int minimumCapacity)
Class ArrayList<E>
329
Searches this list for the specified object and returns the index of the first
occurrence.
int
boolean
isEmpty()
Searches this list for the specified object and returns the index of the last
occurrence.
int
remove(int location)
boolean
protected
void
Removes one instance of the specified object from this Collection if one is
contained (optional).
removeRange(int start, int end)
Removes the objects in the specified range from the start to the end, but not
including the end index.
set(int location, E object)
Replaces the element at the specified location in this ArrayList with the
specified object.
size()
int
Object[]
<T> T[]
toArray()
void
Sets the capacity of this ArrayList to be the same as the current size.
Constructor Detail
ArrayList
public ArrayList()
Method Summary
330
Method Detail
add
public void add(int location,
E object)
Inserts the specified object into this ArrayList at the specified location. The object is
inserted before any previous element at the specified location. If the location is equal
to the size of this ArrayList, the object is added at the end.
Specified by:
add in interface List<E>
Overrides:
add in class AbstractList<E>
Parameters:
location - the index at which to insert the object.
object - the object to add.
Throws:
IndexOutOfBoundsException - when location < 0 || > size()
add
public boolean add(E object)
Inserts the objects in the specified collection at the specified location in this List. The
objects are added in the order they are returned from the collection's iterator.
Specified by:
addAll in interface List<E>
Overrides:
addAll in class AbstractList<E>
Parameters:
Constructor Detail
331
Returns:
true
Throws:
IndexOutOfBoundsException
addAll
public boolean addAll(Collection<? extends E> collection)
Ensures that after this operation the ArrayList can hold the specified number of
elements without further growing.
Parameters:
minimumCapacity - the minimum capacity asked for.
get
public E get(int location)
Method Detail
332
lastIndexOf
public int lastIndexOf(Object object)
Method Detail
333
Removes the objects in the specified range from the start to the end, but not including
the end index.
Overrides:
removeRange in class AbstractList<E>
Parameters:
start - the index at which to start removing.
end - the index one after the end of the range to remove.
Throws:
IndexOutOfBoundsException - when start < 0, start > end or end >
size()
set
public E set(int location,
E object)
Replaces the element at the specified location in this ArrayList with the specified
object.
Specified by:
set in interface List<E>
Overrides:
set in class AbstractList<E>
Parameters:
location - the index at which to put the specified object.
object - the object to add.
Returns:
the previous element at the index.
Throws:
IndexOutOfBoundsException - when location < 0 || >= size()
size
public int size()
Method Detail
334
Returns an array containing all elements contained in this ArrayList. If the specified
array is large enough to hold the elements, the specified array is used, otherwise an
array of the same type is created. If the specified array is used and is larger than this
ArrayList, the array element following the collection elements is set to null.
Specified by:
toArray in interface Collection<E>
Specified by:
toArray in interface List<E>
Overrides:
toArray in class AbstractList<E>
Parameters:
contents - the array.
Returns:
an array of the elements from this ArrayList.
Throws:
ArrayStoreException - when the type of an element in this ArrayList cannot
be stored in the type of the specified array.
trimToSize
public void trimToSize()
Sets the capacity of this ArrayList to be the same as the current size.
See Also:
size
Method Detail
335
Class ArrayDeque<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.ArrayDeque<E>
Type Parameters:
E - the type of elements in this collection
All Implemented Interfaces:
Iterable<E>, Collection<E>, Deque<E>, Queue<E>
public class
extends AbstractCollection<E>
implements Deque<E>
An implementation of Deque, backed by an array. ArrayDeques have no size limit, can not contain
null element, and they are not thread-safe. All optional operations are supported, and the elements
can be any objects.
Since:
1.6
Constructor Summary
Constructor and Description
ArrayDeque()
Constructs a new instance of ArrayDeque containing the elements of the specified collection,
with the order returned by the collection's iterator.
ArrayDeque(int minSize)
Constructs a new empty instance of ArrayDeque big enough for specified number of
elements.
Method Summary
Modifier and
Type
boolean
void
Inserts an element at the head of this deque if it dose not violate size limit
immediately.
addLast(E e)
void
void
boolean
Iterator<E>
E
E
Class ArrayDeque<E>
Inserts an element at the tail of this deque if it dose not violate size limit
immediately.
clear()
Gets but does not remove the head element of this deque.
getFirst()
336
boolean
Iterator<E>
boolean
isEmpty()
boolean
Inserts an element at the head of this deque unless it would violate size
limit.
offerLast(E e)
boolean
Inserts an element at the tail of this deque unless it would violate size
limit.
peek()
Pushes the element to the deque(at the head of the deque), just same as
addFirst(E).
void
remove()
boolean
remove(Object obj)
boolean
removeFirstOccurrence(Object obj)
boolean
removeLastOccurrence(Object obj)
int
Method Summary
337
Detail
ArrayDeque
public ArrayDeque()
Constructs a new empty instance of ArrayDeque big enough for specified number of
elements.
Parameters:
minSize - the smallest size of the ArrayDeque
ArrayDeque
public ArrayDeque(Collection<? extends E> c)
Method Detail
addFirst
public void addFirst(E e)
Inserts an element at the head of this deque if it dose not violate size limit
immediately. It is better to use offerFirst(E) if a deque is size-limited.
Specified by:
addFirst in interface Deque<E>
Parameters:
e - the element
Throws:
NullPointerException - if the element is null
See Also:
Deque.addFirst(java.lang.Object)
addLast
public void addLast(E e)
Inserts an element at the tail of this deque if it dose not violate size limit immediately.
It is better to use offerLast(E) if a deque is size-limited.
Specified by:
addLast in interface Deque<E>
Parameters:
e - the element
Throws:
NullPointerException - if the element is null
See Also:
Deque.addLast(java.lang.Object)
offerFirst
public boolean offerFirst(E e)
Inserts an element at the head of this deque unless it would violate size limit. It is
Constructor Detail
338
offerLast
public boolean offerLast(E e)
Inserts an element at the tail of this deque unless it would violate size limit. It is better
than the addLast(E) method in a size-limited deque, because the latter one may fail
to add the element only by throwing an exception.
Specified by:
offerLast in interface Deque<E>
Parameters:
e - the element
Returns:
true if the operation succeeds or false if it fails
Throws:
NullPointerException - if the element is null
See Also:
Deque.offerLast(java.lang.Object)
offer
public boolean offer(E e)
add
public boolean add(E e)
Method Detail
339
Pushes the element to the deque(at the head of the deque), just same as addFirst(E).
Specified by:
push in interface Deque<E>
Parameters:
e - the element to push
Throws:
NullPointerException - if the element is null
See Also:
Deque.push(java.lang.Object)
removeFirst
public E removeFirst()
Gets and removes the head element of this deque. This method throws an exception
if the deque is empty.
Specified by:
removeFirst in interface Deque<E>
Returns:
the head element
Throws:
NoSuchElementException - if the deque is empty
See Also:
Deque.removeFirst()
remove
public E remove()
Gets and removes the head element of this deque. This method throws an exception
if the deque is empty.
Specified by:
remove in interface Queue<E>
Returns:
the head element
Throws:
NoSuchElementException - if the deque is empty
See Also:
Queue.remove()
pop
public E pop()
removeLast
public E removeLast()
Gets and removes the tail element of this deque. This method throws an exception if
the deque is empty.
Specified by:
removeLast in interface Deque<E>
Returns:
the tail element
Throws:
NoSuchElementException - if the deque is empty
See Also:
Method Detail
340
pollFirst
public E pollFirst()
Gets and removes the head element of this deque. This method returns null if the
deque is empty.
Specified by:
pollFirst in interface Deque<E>
Returns:
the head element or null if the deque is empty
See Also:
Deque.pollFirst()
poll
public E poll()
Gets and removes the head element of this deque. This method returns null if the
deque is empty.
Specified by:
poll in interface Queue<E>
Returns:
the head element or null if the deque is empty
See Also:
Queue.poll()
pollLast
public E pollLast()
Gets and removes the tail element of this deque. This method returns null if the
deque is empty.
Specified by:
pollLast in interface Deque<E>
Returns:
the tail element or null if the deque is empty
See Also:
Deque.pollLast()
getFirst
public E getFirst()
Gets but not removes the head element of this deque. This method throws an
exception if the deque is empty.
Specified by:
getFirst in interface Deque<E>
Returns:
the head element
Throws:
NoSuchElementException - if the deque is empty
See Also:
Deque.getFirst()
element
public E element()
Gets but does not remove the head element of this deque. It throws an exception if
the deque is empty.
Specified by:
element in interface Queue<E>
Returns:
the head element
Throws:
NoSuchElementException - if the deque is empty
See Also:
Queue.element()
Method Detail
341
Gets but not removes the tail element of this deque. This method throws an exception
if the deque is empty.
Specified by:
getLast in interface Deque<E>
Returns:
the tail element
Throws:
NoSuchElementException - if the deque is empty
See Also:
Deque.getLast()
peekFirst
public E peekFirst()
Gets but not removes the head element of this deque. This method returns null if the
deque is empty.
Specified by:
peekFirst in interface Deque<E>
Returns:
the head element or null if the deque is empty
See Also:
Deque.peekFirst()
peek
public E peek()
Gets but not removes the head element of this deque. This method returns null if the
deque is empty.
Specified by:
peek in interface Queue<E>
Returns:
the head element or null if the deque is empty
See Also:
Queue.peek()
peekLast
public E peekLast()
Gets but not removes the tail element of this deque. This method returns null if the
deque is empty.
Specified by:
peekLast in interface Deque<E>
Returns:
the tail element or null if the deque is empty
See Also:
Deque.peekLast()
removeFirstOccurrence
public boolean removeFirstOccurrence(Object obj)
Removes the first equivalent element of the specified object. If the deque does not
contain the element, it is unchanged and returns false.
Specified by:
removeFirstOccurrence in interface Deque<E>
Parameters:
obj - the element to be removed
Returns:
true if the operation succeeds or false if the deque does not contain the
element
See Also:
Deque.removeFirstOccurrence(java.lang.Object)
Method Detail
342
Removes the first equivalent element of the specified object. If the deque does not
contain the element, it is unchanged and returns false.
Specified by:
remove in interface Collection<E>
Overrides:
remove in class AbstractCollection<E>
Parameters:
obj - the element to be removed
Returns:
true if the operation succeeds or false if the deque does not contain the
element
See Also:
AbstractCollection.remove(java.lang.Object)
removeLastOccurrence
public boolean removeLastOccurrence(Object obj)
Removes the last equivalent element of the specified object. If the deque does not
contain the element, it is unchanged and returns false.
Specified by:
removeLastOccurrence in interface Deque<E>
Parameters:
obj - the element to be removed
Returns:
true if the operation succeeds or false if the deque does not contain the
element.
See Also:
Deque.removeLastOccurrence(java.lang.Object)
size
public int size()
isEmpty
public boolean isEmpty()
contains
public boolean contains(Object obj)
Method Detail
343
Parameters:
obj - the element
Returns:
true if the element is in the deque, false otherwise
See Also:
AbstractCollection.contains(java.lang.Object)
clear
public void clear()
iterator
public Iterator<E> iterator()
Returns the iterator of the deque. The elements will be ordered from head to tail.
Specified by:
iterator in interface Iterable<E>
Specified by:
iterator in interface Collection<E>
Specified by:
iterator in class AbstractCollection<E>
Returns:
the iterator
See Also:
AbstractCollection.iterator()
descendingIterator
public Iterator<E> descendingIterator()
Method Detail
344
Class AbstractSet<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractSet<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, Set<E>
Direct Known Subclasses:
HashSet, TreeSet
An AbstractSet is an abstract implementation of the Set interface. This implementation does not
support adding. A subclass must implement the abstract methods iterator() and size().
Since:
1.2
Constructor Summary
Modifier
protected
Method Summary
Modifier and
Type
boolean
Compares the specified object to this Set and returns true if they are equal.
hashCode()
int
boolean
Constructor Detail
Class AbstractSet<E>
345
Method Detail
equals
public boolean equals(Object object)
Compares the specified object to this Set and returns true if they are equal. The
object must be an instance of Set and contain the same objects.
Specified by:
equals in interface Collection<E>
Specified by:
equals in interface Set<E>
Overrides:
equals in class Object
Parameters:
object - the object to compare with this set.
Returns:
true if the specified object is equal to this set, false otherwise
See Also:
hashCode()
hashCode
public int hashCode()
Returns the hash code for this set. Two set which are equal must return the same
value. This implementation calculates the hash code by adding each element's hash
code.
Specified by:
hashCode in interface Collection<E>
Specified by:
hashCode in interface Set<E>
Overrides:
hashCode in class Object
Returns:
the hash code of this set.
See Also:
equals(java.lang.Object)
removeAll
public boolean removeAll(Collection<?> collection)
Removes all occurrences in this collection which are contained in the specified
collection.
Specified by:
removeAll in interface Collection<E>
Specified by:
removeAll in interface Set<E>
Overrides:
removeAll in class AbstractCollection<E>
Parameters:
collection - the collection of objects to remove.
Returns:
true if this collection was modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - if removing from this collection
is not supported.
Constructor Detail
346
Class AbstractSequentialList<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.AbstractSequentialList<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, List<E>
Direct Known Subclasses:
LinkedList
Field Summary
Constructor Summary
Modifier
protected
Method Summary
Modifier and Type
void
Inserts the specified object into this List at the specified location.
addAll(int location, Collection<? extends E> collection)
boolean
E
Iterator<E>
abstract
ListIterator<E>
E
Method Detail
Replaces the element at the specified location in this list with the
specified object.
347
Constructor Detail
AbstractSequentialList
protected AbstractSequentialList()
Method Detail
add
public void add(int location,
E object)
348
Returns:
true
get
public E get(int location)
listIterator
public abstract ListIterator<E> listIterator(int location)
remove
public E remove(int location)
Method Detail
349
Method Detail
350
Class AbstractQueue<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractQueue<E>
Type Parameters:
E - the type of the element in the collection.
All Implemented Interfaces:
Iterable<E>, Collection<E>, Queue<E>
Direct Known Subclasses:
PriorityQueue
AbstractQueue is an abstract class which implements some of the methods in Queue. The provided
implementations of add, remove and element are based on offer, poll, and peek except that they
throw exceptions to indicate some error instead of returning true or false.
Constructor Summary
Modifier
protected
Method Summary
Modifier and Type
boolean
boolean
void
Returns but does not remove the element at the head of the queue.
remove()
Removes the element at the head of the queue and returns it.
Class AbstractQueue<E>
351
Constructor Detail
AbstractQueue
protected AbstractQueue()
Method Detail
add
public boolean add(E o)
Adds all the elements of a collection to the queue. If the collection is the queue itself,
then an IllegalArgumentException will be thrown. If during the process, some runtime
exception is thrown, then those elements in the collection which have already
successfully been added will remain in the queue. The result of the method is
undefined if the collection is modified during the process of the method.
Specified by:
addAll in interface Collection<E>
Overrides:
addAll in class AbstractCollection<E>
Parameters:
c - the collection to be added to the queue.
Returns:
true if the operation succeeds, otherwise false.
Throws:
NullPointerException - if the collection or any element of it is null.
IllegalArgumentException - If the collection to be added to the queue is the
queue itself.
remove
public E remove()
Removes the element at the head of the queue and returns it.
Specified by:
remove in interface Queue<E>
Returns:
the element at the head of the queue.
Throws:
352
element
public E element()
Returns but does not remove the element at the head of the queue.
Specified by:
element in interface Queue<E>
Returns:
the element at the head of the queue.
Throws:
NoSuchElementException - if the queue is empty.
clear
public void clear()
Method Detail
353
Class AbstractMap<K,V>
java.lang.Object
java.util.AbstractMap<K,V>
All Implemented Interfaces:
Map<K,V>
Direct Known Subclasses:
HashMap, IdentityHashMap, TreeMap
This class is an abstract implementation of the Map interface. This implementation does not support
adding. A subclass must implement the abstract method entrySet().
Since:
1.2
A key-value mapping.
AbstractMap.SimpleImmutableEntry<K,V>
Constructor Summary
Modifier
protected
Method Summary
Modifier and Type
void
boolean
boolean
abstract
Set<Map.Entry<K,V>>
boolean
Class AbstractMap<K,V>
354
int
boolean
isEmpty()
Set<K>
void
int
String
Collection<V>
values()
Constructor Detail
AbstractMap
protected AbstractMap()
Method Detail
clear
public void clear()
Method Summary
355
Returns a set containing all of the mappings in this map. Each mapping is an
instance of Map.Entry. As the set is backed by this map, changes in one will be
reflected in the other.
Specified by:
entrySet in interface Map<K,V>
Returns:
a set of the mappings.
equals
public boolean equals(Object object)
Compares the specified object to this instance, and returns true if the specified
object is a map and both maps contain the same mappings.
Specified by:
equals in interface Map<K,V>
Overrides:
equals in class Object
Parameters:
object - the object to compare with this object.
Returns:
boolean true if the object is the same as this object, and false if it is different
from this object.
See Also:
hashCode(), entrySet()
get
public V get(Object key)
Returns the hash code for this object. Objects which are equal must return the same
value for this method.
Specified by:
hashCode in interface Map<K,V>
Overrides:
hashCode in class Object
Returns:
the hash code of this object.
See Also:
equals(Object)
Method Detail
356
keySet
public Set<K> keySet()
Returns a set of the keys contained in this map. The set is backed by this map so
changes to one are reflected by the other. The returned set does not support adding.
Specified by:
keySet in interface Map<K,V>
Returns:
a set of the keys.
put
public V put(K key,
V value)
Method Detail
357
Returns a collection of the values contained in this map. The collection is backed by
this map so changes to one are reflected by the other. The collection supports
remove, removeAll, retainAll and clear operations, and it does not support add or
addAll operations.
This method returns a collection which is the subclass of AbstractCollection. The
iterator method of this subclass returns a "wrapper object" over the iterator of map's
entrySet(). The size method wraps the map's size method and the contains method
wraps the map's containsValue method.
The collection is created when this method is called for the first time and returned in
response to all subsequent calls. This method may return different collections when
multiple concurrent calls occur to this method, since no synchronization is performed.
Specified by:
values in interface Map<K,V>
Returns:
a collection of the values contained in this map.
Method Detail
358
Class AbstractMap.SimpleImmutableEntry<K,V>
java.lang.Object
java.util.AbstractMap.SimpleImmutableEntry<K,V>
Type Parameters:
K - the type of key
V - the type of value
All Implemented Interfaces:
Map.Entry<K,V>
Enclosing class:
AbstractMap<K,V>
Constructor Summary
Constructor and Description
SimpleImmutableEntry(K theKey, V theValue)
Method Summary
Modifier and Type
boolean
int
Throws an UnsupportedOperationException.
String
toString()
Constructor Detail
Class AbstractMap.SimpleImmutableEntry<K,V>
359
Method Detail
getKey
public K getKey()
getValue
public V getValue()
setValue
public V setValue(V object)
Throws an UnsupportedOperationException.
Specified by:
setValue in interface Map.Entry<K,V>
Parameters:
object - new value
Returns:
(Does not)
Throws:
java.lang.UnsupportedOperationException
- always
See Also:
Map.Entry.setValue(java.lang.Object)
equals
public boolean equals(Object object)
Answers whether the object is equal to this entry. This works across all kinds of the
Map.Entry interface.
Specified by:
equals in interface Map.Entry<K,V>
Overrides:
Constructor Detail
360
in class Object
Parameters:
object
Returns:
true
See Also:
Object.equals(java.lang.Object)
hashCode
public int hashCode()
toString
public String toString()
Method Detail
361
Class AbstractMap.SimpleEntry<K,V>
java.lang.Object
java.util.AbstractMap.SimpleEntry<K,V>
Type Parameters:
K - the type of key
V - the type of value
All Implemented Interfaces:
Map.Entry<K,V>
Enclosing class:
AbstractMap<K,V>
A key-value mapping.
Since:
1.6
Constructor Summary
Constructor and Description
SimpleEntry(K theKey, V theValue)
Method Summary
Modifier and
Type
boolean
int
Sets the value of this entry to the specified value, replacing any existing
value.
String
toString()
Constructor Detail
Class AbstractMap.SimpleEntry<K,V>
362
Method Detail
getKey
public K getKey()
getValue
public V getValue()
setValue
public V setValue(V object)
Sets the value of this entry to the specified value, replacing any existing value.
Specified by:
setValue in interface Map.Entry<K,V>
Parameters:
object - the new value to set.
Returns:
object the replaced value of this entry.
See Also:
Map.Entry.setValue(java.lang.Object)
equals
public boolean equals(Object object)
Answers whether the object is equal to this entry. This works across all kinds of the
Map.Entry interface.
Specified by:
equals in interface Map.Entry<K,V>
Overrides:
equals in class Object
Parameters:
Constructor Detail
363
Returns:
true
See Also:
Object.equals(java.lang.Object)
hashCode
public int hashCode()
toString
public String toString()
Method Detail
364
Class AbstractList<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>, List<E>
Direct Known Subclasses:
AbstractSequentialList, ArrayList, Vector
is an abstract implementation of the List interface, optimized for a backing store which
supports random access. This implementation does not support adding or replacing. A subclass must
implement the abstract methods get() and size(), and to create a modifiable List it's necessary to
override the add() method that currently throws an UnsupportedOperationException.
Since:
1.2
AbstractList
Field Summary
Modifier and Type
protected int
Constructor Summary
Modifier
protected
Method Summary
Modifier and Type
boolean
void
Inserts the specified object into this List at the specified location.
addAll(int location, Collection<? extends E> collection)
boolean
void
boolean
abstract E
int
int
Class AbstractList<E>
Compares the specified object to this list and return true if they are
equal.
get(int location)
365
iterator()
Searches this list for the specified object and returns the index of the
last occurrence.
int
ListIterator<E>
ListIterator<E>
listIterator()
protected void
Removes the objects in the specified range from the start to the end
index minus one.
set(int location, E object)
Replaces the element at the specified location in this list with the
specified object.
List<E>
Object[]
<T> T[]
Field Detail
modCount
protected transient int modCount
Constructor Detail
AbstractList
protected AbstractList()
Method Summary
366
Method Detail
add
public void add(int location,
E object)
Inserts the specified object into this List at the specified location. The object is
inserted before any previous element at the specified location. If the location is equal
to the size of this List, the object is added at the end.
Concrete implementations that would like to support the add functionality must
override this method.
Specified by:
add in interface List<E>
Parameters:
location - the index at which to insert.
object - the object to add.
Throws:
java.lang.UnsupportedOperationException
supported.
ClassCastException - if the class of the object is inappropriate for this
IllegalArgumentException - if the object cannot be added to this List
IndexOutOfBoundsException - if location < 0 || >= size()
List
add
public boolean add(E object)
supported
ClassCastException - if the class of the object is inappropriate for this
IllegalArgumentException - if the object cannot be added to this List
List
addAll
public boolean addAll(int location,
Collection<? extends E> collection)
Inserts the objects in the specified Collection at the specified location in this List. The
objects are added in the order they are returned from the collection's iterator.
Specified by:
addAll in interface List<E>
Parameters:
location - the index at which to insert.
collection - the Collection of objects
Returns:
true if this List is modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - if adding to this list is not
supported.
ClassCastException - if the class of an object is inappropriate for this list.
Method Detail
367
this list.
clear
public void clear()
supported.
See Also:
List.isEmpty(), List.size()
equals
public boolean equals(Object object)
Compares the specified object to this list and return true if they are equal. Two lists
are equal when they both contain the same objects in the same order.
Specified by:
equals in interface Collection<E>
Specified by:
equals in interface List<E>
Overrides:
equals in class Object
Parameters:
object - the object to compare to this object.
Returns:
true if the specified object is equal to this list, false otherwise.
See Also:
hashCode()
get
public abstract E get(int location)
Returns the hash code of this list. The hash code is calculated by taking each
element's hashcode into account.
Specified by:
hashCode in interface Collection<E>
Specified by:
hashCode in interface List<E>
Overrides:
hashCode in class Object
Returns:
the hash code.
See Also:
equals(java.lang.Object), List.hashCode()
Method Detail
368
Searches this list for the specified object and returns the index of the first occurrence.
Specified by:
indexOf in interface List<E>
Parameters:
object - the object to search for.
Returns:
the index of the first occurrence of the object, or -1 if it was not found.
iterator
public Iterator<E> iterator()
Returns an iterator on the elements of this list. The elements are iterated in the same
order as they occur in the list.
Specified by:
iterator in interface Iterable<E>
Specified by:
iterator in interface Collection<E>
Specified by:
iterator in interface List<E>
Specified by:
iterator in class AbstractCollection<E>
Returns:
an iterator on the elements of this list.
See Also:
Iterator
lastIndexOf
public int lastIndexOf(Object object)
Searches this list for the specified object and returns the index of the last occurrence.
Specified by:
lastIndexOf in interface List<E>
Parameters:
object - the object to search for.
Returns:
the index of the last occurrence of the object, or -1 if the object was not
found.
listIterator
public ListIterator<E> listIterator()
Returns a ListIterator on the elements of this list. The elements are iterated in the
same order that they occur in the list.
Specified by:
listIterator in interface List<E>
Returns:
a ListIterator on the elements of this list
See Also:
ListIterator
listIterator
public ListIterator<E> listIterator(int location)
Returns a list iterator on the elements of this list. The elements are iterated in the
same order as they occur in the list. The iteration starts at the specified location.
Specified by:
listIterator in interface List<E>
Parameters:
location - the index at which to start the iteration.
Returns:
a ListIterator on the elements of this list.
Throws:
IndexOutOfBoundsException - if location < 0 || location > size()
Method Detail
369
remove
public E remove(int location)
Removes the objects in the specified range from the start to the end index minus one.
Parameters:
start - the index at which to start removing.
end - the index after the last element to remove.
Throws:
java.lang.UnsupportedOperationException - if removing from this list is not
supported.
IndexOutOfBoundsException - if start < 0 or start >= size().
set
public E set(int location,
E object)
Replaces the element at the specified location in this list with the specified object.
Specified by:
set in interface List<E>
Parameters:
location - the index at which to put the specified object.
object - the object to add.
Returns:
the previous element at the index.
Throws:
java.lang.UnsupportedOperationException - if replacing elements in this list
is not supported.
ClassCastException - if the class of an object is inappropriate for this list.
IllegalArgumentException - if an object cannot be added to this list.
IndexOutOfBoundsException - if location < 0 || >= size()
subList
public List<E> subList(int start,
int end)
Returns a part of consecutive elements of this list as a view. The returned view will be
of zero length if start equals end. Any change that occurs in the returned subList will
be reflected to the original list, and vice-versa. All the supported optional operations
by the original list will also be supported by this subList.
This method can be used as a handy method to do some operations on a sub range
of the original list, for example list.subList(from, to).clear();
If the original list is modified in other ways than through the returned subList, the
behavior of the returned subList becomes undefined.
Method Detail
370
The returned subList is a subclass of AbstractList. The subclass stores offset, size of
itself, and modCount of the original list. If the original list implements RandomAccess
interface, the returned subList also implements RandomAccess interface.
The subList's set(int, Object), get(int), add(int, Object), remove(int), addAll(int,
Collection) and removeRange(int, int) methods first check the bounds, adjust offsets
and then call the corresponding methods of the original AbstractList.
addAll(Collection c) method of the returned subList calls the original addAll(offset +
size, c).
The listIterator(int) method of the subList wraps the original list iterator. The iterator()
method of the subList invokes the original listIterator() method, and the size() method
merely returns the size of the subList.
All methods will throw a ConcurrentModificationException if the modCount of the
original list is not equal to the expected value.
Specified by:
subList
in interface List<E>
Parameters:
start - start index of the subList (inclusive).
end - end index of the subList, (exclusive).
Returns:
a subList view of this list starting from start (inclusive), and ending with end
(exclusive)
Throws:
IndexOutOfBoundsException - if (start < 0 || end > size())
IllegalArgumentException - if (start > end)
toArray
public Object[] toArray()
Returns an array containing all elements contained in this ArrayList. If the specified
array is large enough to hold the elements, the specified array is used, otherwise an
array of the same type is created. If the specified array is used and is larger than this
ArrayList, the array element following the collection elements is set to null.
Specified by:
toArray in interface Collection<E>
Specified by:
toArray in interface List<E>
Overrides:
toArray in class AbstractCollection<E>
Parameters:
contents - the array.
Returns:
an array of the elements from this ArrayList.
Throws:
ArrayStoreException - when the type of an element in this ArrayList cannot
be stored in the type of the specified array.
Method Detail
371
Class AbstractCollection<E>
java.lang.Object
java.util.AbstractCollection<E>
All Implemented Interfaces:
Iterable<E>, Collection<E>
Direct Known Subclasses:
AbstractList, AbstractQueue, AbstractSet, ArrayDeque
Constructor Summary
Modifier
protected
Method Summary
Modifier and
Type
boolean
boolean
void
boolean
contains(Object object)
Tests whether this Collection
boolean
containsAll(Collection<?> collection)
Tests whether this Collection contains all
specified Collection.
boolean
abstract
Iterator<E>
to the
isEmpty()
boolean
boolean
removeAll(Collection<?> collection)
Removes all occurrences in this Collection
specified Collection (optional).
boolean
retainAll(Collection<?> collection)
Class AbstractCollection<E>
372
size()
String
Constructor Detail
AbstractCollection
protected AbstractCollection()
Method Detail
add
public boolean add(E object)
Attempts to add all of the objects contained in collection to the contents of this
Collection (optional). This implementation iterates over the given Collection and
calls add for each element. If any of these calls return true, then true is returned as
result of this method call, false otherwise. If this Collection does not support adding
elements, an UnsupportedOperationException is thrown.
Method Summary
373
in interface Collection<E>
Parameters:
collection
Returns:
true
Throws:
java.lang.UnsupportedOperationException
not supported.
ClassCastException - if the class of an object is inappropriate for this
Collection.
IllegalArgumentException - if an object cannot be added to this Collection.
NullPointerException - if collection is null, or if it contains null elements
and this Collection does not support such elements.
clear
public void clear()
Removes all elements from this Collection, leaving it empty (optional). This
implementation iterates over this Collection and calls the remove method on each
element. If the iterator does not support removal of elements, an
UnsupportedOperationException is thrown.
Concrete implementations usually can clear a Collection more efficiently and should
therefore overwrite this method.
Specified by:
clear
in interface Collection<E>
Throws:
java.lang.UnsupportedOperationException
removing elements from this Collection
See Also:
iterator(), isEmpty(), size()
contains
public boolean contains(Object object)
Tests whether this Collection contains the specified object. This implementation
iterates over this Collection and tests, whether any element is equal to the given
object. If object != null then object.equals(e) is called for each element e
returned by the iterator until the element is found. If object == null then each
element e returned by the iterator is compared with the test e == null.
Specified by:
contains in interface Collection<E>
Parameters:
object - the object to search for.
Returns:
true if object is an element of this Collection, false otherwise.
Throws:
ClassCastException - if the object to look for isn't of the correct type.
NullPointerException - if the object to look for is null and this Collection
doesn't support null elements.
containsAll
public boolean containsAll(Collection<?> collection)
Tests whether this Collection contains all objects contained in the specified
Collection. This implementation iterates over the specified Collection. If one
element returned by the iterator is not contained in this Collection, then false is
returned; true otherwise.
Specified by:
containsAll in interface Collection<E>
Parameters:
Method Detail
374
Returns:
true if all objects
false otherwise.
Throws:
ClassCastException
correct type.
NullPointerException - if collection contains at
this Collection doesn't support null elements.
NullPointerException - if collection is null.
isEmpty
public boolean isEmpty()
iterator
public abstract Iterator<E> iterator()
Returns an instance of Iterator that may be used to access the objects contained by
this Collection. The order in which the elements are returned by the Iterator is not
defined unless the instance of the Collection has a defined order. In that case, the
elements are returned in that order.
In this class this method is declared abstract and has to be implemented by concrete
Collection implementations.
Specified by:
iterator
in interface Iterable<E>
Specified by:
iterator in interface Collection<E>
Returns:
an iterator for accessing the Collection contents.
remove
public boolean remove(Object object)
Removes one instance of the specified object from this Collection if one is contained
(optional). This implementation iterates over this Collection and tests for each
element e returned by the iterator, whether e is equal to the given object. If object !=
null then this test is performed using object.equals(e), otherwise using object ==
null. If an element equal to the given object is found, then the remove method is
called on the iterator and true is returned, false otherwise. If the iterator does not
support removing elements, an UnsupportedOperationException is thrown.
Specified by:
remove in interface Collection<E>
Parameters:
object - the object to remove.
Returns:
true if this Collection is modified, false otherwise.
Throws:
java.lang.UnsupportedOperationException - if removing from this
Collection is not supported.
ClassCastException - if the object passed is not of the correct type.
NullPointerException - if object is null and this Collection doesn't support
null elements.
Method Detail
375
in interface Collection<E>
Parameters:
collection
Returns:
true
Throws:
java.lang.UnsupportedOperationException - if removing from this
Collection is not supported.
ClassCastException - if one or more elements of collection isn't of
the
correct type.
NullPointerException - if collection contains at
this Collection doesn't support null elements.
NullPointerException - if collection is null.
retainAll
public boolean retainAll(Collection<?> collection)
Removes all objects from this Collection that are not also found in the Collection
passed (optional). After this method returns this Collection will only contain
elements that also can be found in the Collection passed to this method.
This implementation iterates over this Collection and tests for each element e
returned by the iterator, whether it is contained in the specified Collection. If this test
is negative, then the remove method is called on the iterator. If the iterator does not
support removing elements, an UnsupportedOperationException is thrown.
Specified by:
retainAll
in interface Collection<E>
Parameters:
collection
Returns:
true
Throws:
java.lang.UnsupportedOperationException - if removing from this
Collection is not supported.
ClassCastException - if one or more elements of collection isn't of
the
correct type.
NullPointerException - if collection contains at
this Collection doesn't support null elements.
NullPointerException - if collection is null.
size
public abstract int size()
in interface Collection<E>
Returns:
Method Detail
376
Returns the string representation of this Collection. The presentation has a specific
format. It is enclosed by square brackets ("[]"). Elements are separated by ', ' (comma
and space).
Overrides:
toString in class Object
Returns:
the string representation of this Collection.
toArray
public Object[] toArray()
Returns an array containing all elements contained in this ArrayList. If the specified
array is large enough to hold the elements, the specified array is used, otherwise an
array of the same type is created. If the specified array is used and is larger than this
ArrayList, the array element following the collection elements is set to null.
Specified by:
toArray in interface Collection<E>
Parameters:
contents - the array.
Returns:
an array of the elements from this ArrayList.
Throws:
ArrayStoreException - when the type of an element in this ArrayList cannot
be stored in the type of the specified array.
Method Detail
377
Class SimpleDateFormat
java.lang.Object
java.text.Format
java.text.DateFormat
java.text.SimpleDateFormat
All Implemented Interfaces:
Cloneable
Deprecated.
this class has many issues in iOS and other platforms, please use the L10NManager
public class
extends DateFormat
A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.
See Also:
http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
Field Summary
Constructor Summary
Constructor and Description
SimpleDateFormat()
Deprecated.
Construct a SimpleDateFormat with no pattern.
SimpleDateFormat(String pattern)
Deprecated.
Construct a SimpleDateFormat with a given pattern.
Method Summary
Modifier and Type
void
Deprecated.
Apply a new pattern.
clone()
Object
Deprecated.
format(Date source)
String
Deprecated.
Format a given date.
getDateFormatSymbols()
DateFormatSymbols
Deprecated.
Get the date format symbols for parsing/formatting textual components
of dates in a localization sensitive way.
parse(String source)
Date
Deprecated.
NOT IMPLEMENTED - use SimpleDateFormat for parsing instead.
void
setDateFormatSymbols(DateFormatSymbols newSymbols)
Class SimpleDateFormat
378
Deprecated.
String
Constructor Detail
SimpleDateFormat
public SimpleDateFormat()
Deprecated.
Construct a SimpleDateFormat with no pattern.
SimpleDateFormat
public SimpleDateFormat(String pattern)
Deprecated.
Construct a SimpleDateFormat with a given pattern.
Parameters:
pattern
Method Detail
toPattern
public String toPattern()
Deprecated.
Returns:
the pattern
getDateFormatSymbols
public DateFormatSymbols getDateFormatSymbols()
Deprecated.
Get the date format symbols for parsing/formatting textual components of dates in a
localization sensitive way.
Returns:
current symbols.
setDateFormatSymbols
public void setDateFormatSymbols(DateFormatSymbols newSymbols)
Deprecated.
Apply new date format symbols for parsing/formatting textual components of dates in
a localisation sensitive way.
Parameters:
newSymbols - new format symbols.
Method Summary
379
Deprecated.
Apply a new pattern.
Parameters:
pattern - the pattern to set
clone
public Object clone()
Deprecated.
Overrides:
clone
in class DateFormat
format
public String format(Date source)
Deprecated.
Description copied from class: DateFormat
Format a given date.
Overrides:
format in class DateFormat
Parameters:
source - date to be formatted.
Returns:
formatted date.
parse
public Date parse(String source)
throws ParseException
Deprecated.
Description copied from class: DateFormat
NOT IMPLEMENTED - use SimpleDateFormat for parsing instead.
Overrides:
parse in class DateFormat
Throws:
ParseException
Method Detail
380
Class ParseException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.text.ParseException
public class
extends Exception
Constructor Summary
Constructor and Description
ParseException(String s, int errorOffset)
Method Summary
Modifier and Type Method and Description
int
getErrorOffset()
Constructor Detail
ParseException
public ParseException(String s,
int errorOffset)
Parameters:
errorOffset
Method Detail
getErrorOffset
public int getErrorOffset()
Returns:
the errorOffset
Class ParseException
381
Class Format
java.lang.Object
java.text.Format
All Implemented Interfaces:
Cloneable
Direct Known Subclasses:
DateFormat
An abstract class for parsing and formatting localisation sensitive information, compatible with JDK 6.
See Also:
http://docs.oracle.com/javase/6/docs/api/java/text/Format.html
Constructor Summary
Constructor and Description
Format()
Method Summary
Modifier and Type
abstract String
abstract Object
Format an object.
parseObject(String source)
Constructor Detail
Format
public Format()
Method Detail
format
public abstract String format(Object source)
throws IllegalArgumentException
Format an object.
Parameters:
source - object to be formatted to text.
Returns:
formatted text.
Throws:
Method Detail
382
parseObject
public abstract Object parseObject(String source)
throws ParseException
Method Detail
383
Class DateFormatSymbols
java.lang.Object
java.text.DateFormatSymbols
All Implemented Interfaces:
Cloneable
public class
extends Object
implements Cloneable
Field Summary
Modifier and Type Field and Description
static int
ZONE_ID
static int
ZONE_LONGNAME
static int
ZONE_LONGNAME_DST
static int
ZONE_SHORTNAME
static int
ZONE_SHORTNAME_DST
Constructor Summary
Constructor and Description
DateFormatSymbols()
Method Summary
Modifier and Type
Object
clone()
String[]
getAmPmStrings()
String[]
getEras()
String[]
getMonths()
Hashtable<String,String>
getResourceBundle()
String[]
getShortMonths()
String[]
getShortWeekdays()
String[]
getWeekdays()
String[][]
getZoneStrings()
void
setAmPmStrings(String[] newAmpms)
void
setEras(String[] newEras)
void
setMonths(String[] newMonths)
void
setResourceBundle(Hashtable<String,String> newResourceBundle)
void
setShortMonths(String[] newShortMonths)
void
setShortWeekdays(String[] newShortWeekdays)
void
setWeekdays(String[] newWeekdays)
void
setZoneStrings(String[][] newZoneStrings)
Class DateFormatSymbols
384
Field Detail
ZONE_ID
public static final int ZONE_ID
See Also:
Constant Field Values
ZONE_LONGNAME
public static final int ZONE_LONGNAME
See Also:
Constant Field Values
ZONE_SHORTNAME
public static final int ZONE_SHORTNAME
See Also:
Constant Field Values
ZONE_LONGNAME_DST
public static final int ZONE_LONGNAME_DST
See Also:
Constant Field Values
ZONE_SHORTNAME_DST
public static final int ZONE_SHORTNAME_DST
See Also:
Constant Field Values
Constructor Detail
DateFormatSymbols
public DateFormatSymbols()
Method Detail
getAmPmStrings
public String[] getAmPmStrings()
setAmPmStrings
public void setAmPmStrings(String[] newAmpms)
getResourceBundle
public Hashtable<String,String> getResourceBundle()
setResourceBundle
public void setResourceBundle(Hashtable<String,String> newResourceBundle)
getZoneStrings
public String[][] getZoneStrings()
385
setShortWeekdays
public void setShortWeekdays(String[] newShortWeekdays)
getShortWeekdays
public String[] getShortWeekdays()
getWeekdays
public String[] getWeekdays()
setWeekdays
public void setWeekdays(String[] newWeekdays)
setShortMonths
public void setShortMonths(String[] newShortMonths)
getShortMonths
public String[] getShortMonths()
setMonths
public void setMonths(String[] newMonths)
getMonths
public String[] getMonths()
getEras
public String[] getEras()
setEras
public void setEras(String[] newEras)
clone
public Object clone()
Method Detail
386
Class DateFormatPatterns
java.lang.Object
java.text.DateFormatPatterns
public class
extends Object
Field Summary
Modifier and Type
static String
static String
static String
static String
static String
static String
static String
static String
Constructor Summary
Constructor and Description
DateFormatPatterns()
Method Summary
Field Detail
RFC2822
public static final String RFC2822
Class DateFormatPatterns
387
Constructor Detail
DateFormatPatterns
public DateFormatPatterns()
Field Detail
388
Class DateFormat
java.lang.Object
java.text.Format
java.text.DateFormat
All Implemented Interfaces:
Cloneable
Direct Known Subclasses:
SimpleDateFormat
Deprecated.
this class has many issues in iOS and other platforms, please use the L10NManager
public class
extends Format
A class for parsing and formatting localisation sensitive dates, compatible with Jave 6 SDK. This
implementation uses the Codename One localization manager for handling formatting dates. Parsing
dates is not implemented in this class since the localization pattern is not exposed.
See Also:
http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
Field Summary
Modifier and Type
static int
Deprecated.
Constant for default style (MEDIUM) parsing/formatting pattern.
FULL
static int
Deprecated.
Constant for full style parsing/formatting pattern.
LONG
static int
Deprecated.
Constant for long style parsing/formatting pattern.
MEDIUM
static int
Deprecated.
Constant for medium style parsing/formatting pattern.
SHORT
static int
Deprecated.
Constant for short style parsing/formatting pattern.
Method Summary
Modifier and
Type
Object
Deprecated.
equals(Object obj)
boolean
Deprecated.
Indicates whether some other object is "equal to" this one.
format(Date source)
String
Deprecated.
Format a given date.
String
format(Object obj)
Deprecated.
Constructor Detail
389
getDateInstance()
Deprecated.
Get a DateFormat instance with default style for date (SHORT).
getDateInstance(int style)
Deprecated.
Get a DateFormat instance that uses a given style for dates.
getDateTimeInstance(int dateStyle, int timeStyle)
Deprecated.
Get a DateFormat instance that uses a given style for dates and times.
getInstance()
static
DateFormat
static
DateFormat
static
DateFormat
Deprecated.
Get a DateFormat instance with default style for date/time
(SHORT/SHORT).
getTimeInstance()
Deprecated.
Get a DateFormat instance with default style for time (SHORT).
getTimeInstance(int style)
Deprecated.
Get a DateFormat instance that uses a given style for times.
hashCode()
Deprecated.
Returns a hash code value for the object.
int
parse(String source)
Deprecated.
NOT IMPLEMENTED - use SimpleDateFormat for parsing instead.
Date
parseObject(String source)
Deprecated.
NOT IMPLEMENTED - use SimpleDateFormat for parsing instead.
Object
Field Detail
FULL
public static final int FULL
Deprecated.
Constant for full style parsing/formatting pattern.
See Also:
Constant Field Values
LONG
public static final int LONG
Deprecated.
Constant for long style parsing/formatting pattern.
See Also:
Constant Field Values
MEDIUM
public static final int MEDIUM
Deprecated.
Constant for medium style parsing/formatting pattern.
See Also:
Constant Field Values
Method Summary
390
Deprecated.
Constant for short style parsing/formatting pattern.
See Also:
Constant Field Values
DEFAULT
public static final int DEFAULT
Deprecated.
Constant for default style (MEDIUM) parsing/formatting pattern.
See Also:
Constant Field Values
Method Detail
format
public String format(Object obj)
throws IllegalArgumentException
Deprecated.
Format a given object.
Specified by:
format in class Format
Parameters:
obj - object to be formatted to text.
Returns:
formatted object.
Throws:
IllegalArgumentException - of the source can not be formatted.
format
public String format(Date source)
Deprecated.
Format a given date.
Parameters:
source - date to be formatted.
Returns:
formatted date.
parseObject
public Object parseObject(String source)
throws ParseException
Deprecated.
NOT IMPLEMENTED - use SimpleDateFormat for parsing instead.
Specified by:
parseObject in class Format
Parameters:
source - document to be parsed.
Returns:
parsed object.
Throws:
ParseException - if the source could not be parsed.
parse
public Date parse(String source)
throws ParseException
Deprecated.
NOT IMPLEMENTED - use SimpleDateFormat for parsing instead.
Field Detail
391
getInstance
public static final DateFormat getInstance()
Deprecated.
Get a DateFormat instance with default style for date/time (SHORT/SHORT).
Returns:
a DateFormat instance.
getDateInstance
public static final DateFormat getDateInstance()
Deprecated.
Get a DateFormat instance with default style for date (SHORT).
Returns:
a DateFormat instance.
getTimeInstance
public static final DateFormat getTimeInstance()
Deprecated.
Get a DateFormat instance with default style for time (SHORT).
Returns:
a DateFormat instance.
getDateInstance
public static final DateFormat getDateInstance(int style)
Deprecated.
Get a DateFormat instance that uses a given style for dates.
Parameters:
style - style to use for parsing and formatting (SHORT, MEDIUM, LONG,
FULL, DEFAULT);
Returns:
a DateFormat instance.
See Also:
SHORT, MEDIUM, LONG, FULL, DEFAULT
getTimeInstance
public static final DateFormat getTimeInstance(int style)
Deprecated.
Get a DateFormat instance that uses a given style for times.
Parameters:
style - style to use for parsing and formatting (SHORT, MEDIUM, LONG,
FULL, DEFAULT);
Returns:
a DateFormat instance.
See Also:
SHORT, MEDIUM, LONG, FULL, DEFAULT
getDateTimeInstance
public static final DateFormat getDateTimeInstance(int dateStyle,
int timeStyle)
Deprecated.
Get a DateFormat instance that uses a given style for dates and times.
Parameters:
style - style to use for parsing and formatting (SHORT, MEDIUM, LONG,
FULL, DEFAULT);
Returns:
a DateFormat instance.
See Also:
SHORT, MEDIUM, LONG, FULL, DEFAULT
Method Detail
392
Deprecated.
Description copied from class: Object
Returns a hash code value for the object. This method is supported for the benefit of
hashtables such as those provided by java.util.Hashtable. The general contract of
hashCode is: Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application. If two objects are equal
according to the equals(Object) method, then calling the hashCode method on each
of the two objects must produce the same integer result. It is not required that if two
objects are unequal according to the equals(java.lang.Object) method, then calling
the hashCode method on each of the two objects must produce distinct integer
results. However, the programmer should be aware that producing distinct integer
results for unequal objects may improve the performance of hashtables. As much as
is reasonably practical, the hashCode method defined by class Object does return
distinct integers for distinct objects. (This is typically implemented by converting the
internal address of the object into an integer, but this implementation technique is not
required by the JavaTM programming language.)
Overrides:
hashCode in class Object
equals
public boolean equals(Object obj)
Deprecated.
Description copied from class: Object
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Object
clone
public Object clone()
Deprecated.
Method Detail
393
Class URISyntaxException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.net.URISyntaxException
public class
extends Exception
Constructor Summary
Constructor and Description
URISyntaxException(String input, String reason)
URISyntaxException(String input, String reason, int index)
Method Summary
Modifier and Type
int
getIndex()
String
getInput()
String
getReason()
void
setIndex(int index)
void
setInput(String input)
void
setReason(String reason)
Constructor Detail
URISyntaxException
public URISyntaxException(String input,
String reason)
Parameters:
input reason -
URISyntaxException
public URISyntaxException(String input,
String reason,
int index)
Parameters:
input
Class URISyntaxException
394
Method Detail
getIndex
public int getIndex()
Returns:
the index
setIndex
public void setIndex(int index)
Parameters:
index
getInput
public String getInput()
Returns:
the input
setInput
public void setInput(String input)
Parameters:
input
getReason
public String getReason()
Returns:
the reason
setReason
public void setReason(String reason)
Parameters:
reason
Constructor Detail
395
Class URI
java.lang.Object
java.net.URI
public class
extends Object
An implementation of a Univeral Resource Identifier (URI). While the output is mostly compatible with
the Java 6 API, there are a few somewhat subtle differences:
1) For socket related URIs, the toString() methods use semicolon (;) as the
query marker instead of the normal question mark (?), and the parameters are separated
with a semicolon instead of the normal ampersand (&). With this, the URIs are compatible
with those used by J2ME socket connectors. (The Java 6 API treats socket URIs as URNs).
2) This implementation does not yet "rigorously parse IPv4" addresses like the Java 6 version doe
the host address is simply stored as provided by the caller. This will be enhanced using the
InetAddress class when available.
3) The characters defined as legal "other characters" are not all interpreted correctly, which
just means some unicode characters will get encoded that aren't required to be. The
method URIHelper.isLegalUnicode() needs to be inspected further.
4) Because of 3) toASCIIString() and toString() return the same value.
TODO: finish this list
See Also:
http://docs.oracle.com/javase/6/docs/api/java/net/URI.html,
http://en.wikipedia.org/wiki/Uniform_resource_identifier,
http://en.wikipedia.org/wiki/Uniform_resource_name,
http://www.ietf.org/rfc/rfc2396.txt, http://www.ietf.org/rfc/rfc2732.txt,
http://tools.ietf.org/html/rfc2141
Constructor Summary
Constructor and Description
URI(String uriString)
Method Summary
Modifier and
Type
static URI
boolean
Method Detail
String
getAuthority()
String
getFragment()
396
getHost()
String
String
String
String
getRawSchemeSpecificPart()
String
getRawUserInfo()
String
getScheme()
String
getSchemeSpecificPart()
String
getUserInfo()
int
hashCode()
boolean
isAbsolute()
boolean
isOpaque()
URI
protected
void
protected
void
protected
String
URI
URI
protected
void
protected
void
normalize()
Rather than attempting to process the uri string in a linear fashion, this
implementation works its way from outside-in
rebuildSchemeSpecificPart()
Utility method to construct the scheme specific part from the uri segments
(less scheme and fragment)
relativize(URI uri)
Create a relative URI object against this URI, given the uri parameter.
resolve(URI uri)
Utility method to construct the authority segment from given host, port, and
userinfo segments.
protected
void
protected
void
protected
void
protected
void
Method Summary
Utility method - set the scheme, ensuring valid format, and determining the
query separator to use.
397
String
toASCIIString()
Utility method - set the scheme specific part, ensuring valid format.
toString()
String
Constructor Detail
URI
public URI(String scheme,
String userInfo,
String host,
int port,
String path,
String query,
String fragment)
throws URISyntaxException
Constructor to create a new URI object. The userInfo, path, query and fragment
should be unencoded values - they will be encoded as required.
Parameters:
scheme - the scheme of the URI (for URLs, this would be the protocol), or null
for relative URIs.
userInfo - the unencoded userinfo segment (ie. username:password) or null.
host - the hostname or address, or null.
port - the host port, or -1.
path - the unencoded path segment.
query - the unencoded query segment.
fragment - the unencoded fragment (often referred to as the 'reference' or
'anchor'), or null.
Throws:
URISyntaxException - if any of the fragments are invalid.
URI
public URI(String scheme,
String authority,
String path,
String query,
String fragment)
throws URISyntaxException
Constructor to create a new URI object. The authority, path, query and fragment
should be unencoded values - they will be encoded as required.
Parameters:
scheme - the scheme of the URI (for URLs, this would be the protocol), or null
for relative URIs.
authority - the unencoded authority segment (ie.
username:password@host:port, or simply: host) or null.
path - the unencoded path segment.
query - the unencoded query segment.
fragment - the unencoded fragment (often referred to as the 'reference' or
'anchor'), or null.
Throws:
URISyntaxException - if any of the fragments are invalid.
URI
public URI(String scheme,
String ssp,
String fragment)
throws URISyntaxException
398
Constructor that parses its values from a URI string. This method expects all
segments to be property encoded by the caller. The URIHelper class can be used to
encode segments.
Parameters:
uriString - a full encoded URI in string form to be parsed.
Throws:
URISyntaxException - if any of the parsed segments are invalid.
Method Detail
setScheme
protected void setScheme(String scheme)
throws URISyntaxException
Utility method - set the scheme, ensuring valid format, and determining the query
separator to use.
Throws:
URISyntaxException
See Also:
http://en.wikipedia.org/wiki/Uniform_resource_name
setSchemeSpecificPart
protected void setSchemeSpecificPart(String ssp,
boolean encode)
throws URISyntaxException
Utility method - set the scheme specific part, ensuring valid format. If encode=true,
then some elements will be run through the encoder (path, userinfo, query, fragment),
otherwise the elements will be validated for proper encoding.
Throws:
URISyntaxException
setAuthority
protected void setAuthority(String newAuthority,
boolean encode)
throws URISyntaxException
Utility method - set the part, ensuring valid format. If encode=true, then some
elements will be run through the encoder (path, userinfo, query, fragment), otherwise
the elements will be validated for proper encoding.
Throws:
URISyntaxException
setQuery
protected void setQuery(String query,
boolean encode)
throws URISyntaxException
Utility method to set the query. If parameter encode=true, then the result will be
encoded, otherwise the result will be validated to ensure encoding is valid. Typically
the multi-parameter constructors will call this method with encode=true, and the
Constructor Detail
399
setPath
protected void setPath(String path,
boolean encode)
throws URISyntaxException
Utility method to set the path. If parameter encode=true, then the result will be
encoded, otherwise the result will be validated to ensure encoding is valid. Typically
the multi-parameter constructors will call this method with encode=true, and the
single parameter construct will pass encode=false.
Parameters:
path encode Throws:
URISyntaxException
setAuthority
protected void setAuthority(String host,
int port,
String userInfo,
boolean encode)
throws URISyntaxException
Utility method to construct the authority segment from given host, port, and userinfo
segments. If parameter encode=true, then the userinfo segment will be encoded,
otherwise the it will be validated to ensure encoding is valid. Typically the
multi-parameter constructors will call this method with encode=true, and the single
parameter construct will pass encode=false.
Parameters:
host port userInfo encode Throws:
URISyntaxException
setFragment
protected void setFragment(String fragment,
boolean encode)
Utility method to set the fragment. If parameter encode=true, then the result will be
encoded, otherwise the result will be validated to ensure encoding is valid. Typically
the multi-parameter constructors will call this method with encode=true, and the
single parameter construct will pass encode=false.
Parameters:
fragment encode rebuildSchemeSpecificPart
protected String rebuildSchemeSpecificPart()
Utility method to construct the scheme specific part from the uri segments (less
scheme and fragment)
Returns:
create
public static URI create(String uriString)
A convenience factory method, intended to be used when the URI string is known to
be valid (ie. a static application URI), so it is not needed for the caller to handle
invalid syntax. NOTE: this is not away to avoid handling errors altogether - passing
an invalid URI string will result in an IllegalArgumentException being thrown. The
Method Detail
400
Rather than attempting to process the uri string in a linear fashion, this
implementation works its way from outside-in
Parameters:
uriString Throws:
URISyntaxException
parseSchemeSpecificPart
protected void parseSchemeSpecificPart(String ssp,
boolean encode)
throws URISyntaxException
Utility method used to parse a given scheme specific part. If parameter encode=true,
then the result will be encoded, otherwise the result will be validated to ensure
encoding is valid. Typically the multi-parameter constructors will call this method with
encode=true, and the single parameter construct will pass encode=false.
Parameters:
ssp - scheme specific part (the URI without the scheme or fragment
included).
encode - true if ssp needs to be encoded, false if ssp needs to be verified.
Throws:
URISyntaxException - if the ssp is invalid.
getScheme
public String getScheme()
Method Detail
401
Get the decoded query part of the uri. The query marker (?) itself is not included in
the result.
Returns:
the query part of the URI.
getRawQuery
public String getRawQuery()
Get the encoded query part of the uri. The query marker (?) itself is not included in
the result.
Returns:
the query part of the URI.
getFragment
public String getFragment()
Get the decoded fragment (otherwise known as the "reference" or "anchor") part of
the uri. The anchor marker (#) itself is not included in the result.
Returns:
the anchor part of the URI.
getRawFragment
public String getRawFragment()
Get the encoded fragment (otherwise known as the "reference" or "anchor") part of
the uri. The anchor marker (#) itself is not included in the result.
Returns:
the anchor part of the URI.
getSchemeSpecificPart
public String getSchemeSpecificPart()
Returns:
the schemeSpecificPart
getRawSchemeSpecificPart
public String getRawSchemeSpecificPart()
Returns:
the schemeSpecificPart
getAuthority
public String getAuthority()
Returns:
the authority
getRawAuthority
public String getRawAuthority()
Returns:
the authority
getUserInfo
public String getUserInfo()
Returns:
the userInfo
Method Detail
402
Returns:
the userInfo
isOpaque
public boolean isOpaque()
Returns:
true if this URI has a scheme and starts with a slash
isAbsolute
public boolean isAbsolute()
Returns:
true if the URI is not a relative URI.
toString
public String toString()
Returns:
the uri as a string with parts encoded.
relativize
public URI relativize(URI uri)
Create a relative URI object against this URI, given the uri parameter.
Parameters:
uri Returns:
See Also:
://docs.oracle.com/javase/6/docs/api/java/net/URI.html#relativize
%28java.net.URI%29
resolve
public URI resolve(URI uri)
Method Detail
403
hashCode
public int hashCode()
Method Detail
404
Class WeakReference
java.lang.Object
java.lang.ref.Reference
java.lang.ref.WeakReference
public class
extends Reference
This class provides support for weak references. Weak references are most often used to implement
canonicalizing mappings. Suppose that the garbage collector determines at a certain point in time that
an object is weakly reachable. At that time it will atomically clear all the weak references to that object
and all weak references to any other weakly- reachable objects from which that object is reachable
through a chain of strong and weak references. Since: JDK1.2, CLDC 1.1
Constructor Summary
Constructor and Description
WeakReference(Object ref)
Method Summary
Constructor Detail
WeakReference
public WeakReference(Object ref)
Class WeakReference
405
Class Reference
java.lang.Object
java.lang.ref.Reference
Direct Known Subclasses:
WeakReference
Abstract base class for reference objects. This class defines the operations common to all reference
objects. Because reference objects are implemented in close cooperation with the garbage collector,
this class may not be subclassed directly. Since: JDK1.2, CLDC 1.1
Constructor Summary
Constructor and Description
Reference()
Method Summary
Modifier and Type
void
Object
Constructor Detail
Reference
public Reference()
Method Detail
clear
public void clear()
Returns this reference object's referent. If this reference object has been cleared,
either by the program or by the garbage collector, then this method returns null.
Constructor Detail
406
Class MethodType
java.lang.Object
java.lang.invoke.MethodType
Deprecated.
these classes are used internally for Lambda compatibility
public class
extends Object
Constructor Summary
Constructor and Description
MethodType()
Deprecated.
Method Summary
Modifier and Type
MethodType
Deprecated.
appendParameterTypes(List<Class<?>> a)
MethodType
Deprecated.
changeParameterType(int a, Class<?> b)
MethodType
Deprecated.
changeReturnType(Class<?> a)
MethodType
Deprecated.
dropParameterTypes(int a, int b)
MethodType
Deprecated.
erase()
MethodType
Deprecated.
generic()
MethodType
Deprecated.
genericMethodType(int a)
static MethodType
Deprecated.
genericMethodType(int a, boolean b)
static MethodType
Deprecated.
hasPrimitives()
boolean
Deprecated.
hasWrappers()
boolean
Method Detail
Deprecated.
407
Deprecated.
insertParameterTypes(int a, List<Class<?>> b)
MethodType
Deprecated.
methodType(Class<?> a)
static MethodType
Deprecated.
methodType(Class<?> a, Class<?> b)
static MethodType
Deprecated.
methodType(Class<?> a, Class<?>[] b)
static MethodType
Deprecated.
methodType(Class<?> a, Class<?> b, Class<?>... c)
static MethodType
Deprecated.
methodType(Class<?> a, List<Class<?>> b)
static MethodType
Deprecated.
methodType(Class<?> a, MethodType b)
static MethodType
Deprecated.
parameterArray()
Class<?>[]
Deprecated.
parameterCount()
Deprecated.
int
parameterList()
List<Class<?>>
Deprecated.
parameterType(int a)
Class<?>
Deprecated.
returnType()
Class<?>
Deprecated.
unwrap()
MethodType
Deprecated.
wrap()
MethodType
Deprecated.
Constructor Detail
MethodType
public MethodType()
Deprecated.
Method Summary
408
Method Detail
methodType
public static MethodType methodType(Class<?> a,
Class<?>[] b)
Deprecated.
methodType
public static MethodType methodType(Class<?> a,
List<Class<?>> b)
Deprecated.
methodType
public static MethodType methodType(Class<?> a,
Class<?> b,
Class<?>... c)
Deprecated.
methodType
public static MethodType methodType(Class<?> a)
Deprecated.
methodType
public static MethodType methodType(Class<?> a,
Class<?> b)
Deprecated.
methodType
public static MethodType methodType(Class<?> a,
MethodType b)
Deprecated.
genericMethodType
public static MethodType genericMethodType(int a,
boolean b)
Deprecated.
genericMethodType
public static MethodType genericMethodType(int a)
Deprecated.
changeParameterType
public MethodType changeParameterType(int a,
Class<?> b)
Deprecated.
insertParameterTypes
public MethodType insertParameterTypes(int a,
Class<?>... b)
Deprecated.
appendParameterTypes
public MethodType appendParameterTypes(Class<?>... a)
Deprecated.
Method Detail
409
Deprecated.
appendParameterTypes
public MethodType appendParameterTypes(List<Class<?>> a)
Deprecated.
dropParameterTypes
public MethodType dropParameterTypes(int a,
int b)
Deprecated.
changeReturnType
public MethodType changeReturnType(Class<?> a)
Deprecated.
hasPrimitives
public boolean hasPrimitives()
Deprecated.
hasWrappers
public boolean hasWrappers()
Deprecated.
erase
public MethodType erase()
Deprecated.
generic
public MethodType generic()
Deprecated.
wrap
public MethodType wrap()
Deprecated.
unwrap
public MethodType unwrap()
Deprecated.
parameterType
public Class<?> parameterType(int a)
Deprecated.
parameterCount
public int parameterCount()
Deprecated.
returnType
public Class<?> returnType()
Deprecated.
Method Detail
410
parameterList
public List<Class<?>> parameterList()
Deprecated.
parameterArray
public Class<?>[] parameterArray()
Deprecated.
Method Detail
411
Class MethodHandles
java.lang.Object
java.lang.invoke.MethodHandles
Deprecated.
these classes are used internally for Lambda compatibility
public abstract class
extends Object
Deprecated.
Constructor Summary
Constructor and Description
MethodHandles()
Deprecated.
Method Summary
Modifier and Type
static MethodHandle
Deprecated.
arrayElementSetter(Class<?> a)
static MethodHandle
static MethodHandle
Deprecated.
catchException(MethodHandle a, Class<? extends
Throwable> b, MethodHandle c)
Deprecated.
collectArguments(MethodHandle a, int b, MethodHandle c)
static MethodHandle
Deprecated.
constant(Class<?> a, Object b)
static MethodHandle
Deprecated.
dropArguments(MethodHandle a, int b, Class<?>... c)
static MethodHandle
Deprecated.
dropArguments(MethodHandle a, int b, List<Class<?>> c)
static MethodHandle
Deprecated.
exactInvoker(MethodType a)
static MethodHandle
Class MethodHandles
Deprecated.
412
static MethodHandle
Deprecated.
filterArguments(MethodHandle a, int b,
MethodHandle... c)
Deprecated.
filterReturnValue(MethodHandle a, MethodHandle b)
static MethodHandle
Deprecated.
foldArguments(MethodHandle a, MethodHandle b)
static MethodHandle
static MethodHandle
Deprecated.
guardWithTest(MethodHandle a, MethodHandle b,
MethodHandle c)
Deprecated.
identity(Class<?> a)
static MethodHandle
Deprecated.
insertArguments(MethodHandle a, int b, Object... c)
static MethodHandle
Deprecated.
invoker(MethodType a)
static MethodHandle
static
MethodHandles.Lookup
Deprecated.
lookup()
Deprecated.
permuteArguments(MethodHandle a, MethodType b, int... c)
static MethodHandle
static
MethodHandles.Lookup
Deprecated.
publicLookup()
Deprecated.
reflectAs(Class<T> a, MethodHandle b)
static <T> T
Deprecated.
spreadInvoker(MethodType a, int b)
static MethodHandle
Deprecated.
throwException(Class<?> a, Class<? extends Throwable> b)
static MethodHandle
Deprecated.
Constructor Detail
MethodHandles
public MethodHandles()
Deprecated.
Method Summary
413
Method Detail
lookup
public static MethodHandles.Lookup lookup()
Deprecated.
publicLookup
public static MethodHandles.Lookup publicLookup()
Deprecated.
reflectAs
public static <T> T reflectAs(Class<T> a,
MethodHandle b)
Deprecated.
arrayElementGetter
public static MethodHandle arrayElementGetter(Class<?> a)
throws IllegalArgumentException
Deprecated.
Throws:
IllegalArgumentException
arrayElementSetter
public static MethodHandle arrayElementSetter(Class<?> a)
throws IllegalArgumentException
Deprecated.
Throws:
IllegalArgumentException
spreadInvoker
public static MethodHandle spreadInvoker(MethodType a,
int b)
Deprecated.
exactInvoker
public static MethodHandle exactInvoker(MethodType a)
Deprecated.
invoker
public static MethodHandle invoker(MethodType a)
Deprecated.
explicitCastArguments
public static MethodHandle explicitCastArguments(MethodHandle a,
MethodType b)
Deprecated.
permuteArguments
public static MethodHandle permuteArguments(MethodHandle a,
MethodType b,
int... c)
Deprecated.
Method Detail
414
Deprecated.
identity
public static MethodHandle identity(Class<?> a)
Deprecated.
insertArguments
public static MethodHandle insertArguments(MethodHandle a,
int b,
Object... c)
Deprecated.
dropArguments
public static MethodHandle dropArguments(MethodHandle a,
int b,
List<Class<?>> c)
Deprecated.
dropArguments
public static MethodHandle dropArguments(MethodHandle a,
int b,
Class<?>... c)
Deprecated.
filterArguments
public static MethodHandle filterArguments(MethodHandle a,
int b,
MethodHandle... c)
Deprecated.
collectArguments
public static MethodHandle collectArguments(MethodHandle a,
int b,
MethodHandle c)
Deprecated.
filterReturnValue
public static MethodHandle filterReturnValue(MethodHandle a,
MethodHandle b)
Deprecated.
foldArguments
public static MethodHandle foldArguments(MethodHandle a,
MethodHandle b)
Deprecated.
guardWithTest
public static MethodHandle guardWithTest(MethodHandle a,
MethodHandle b,
MethodHandle c)
Deprecated.
catchException
public static MethodHandle catchException(MethodHandle a,
Class<? extends Throwable> b,
MethodHandle c)
Method Detail
415
Deprecated.
throwException
public static MethodHandle throwException(Class<?> a,
Class<? extends Throwable> b)
Deprecated.
Method Detail
416
Class MethodHandles.Lookup
java.lang.Object
java.lang.invoke.MethodHandles.Lookup
Enclosing class:
MethodHandles
Field Summary
Modifier and Type Field and Description
static int
PACKAGE
static int
PRIVATE
static int
PROTECTED
static int
PUBLIC
Constructor Summary
Constructor and Description
Lookup()
Method Summary
Modifier and Type
MethodHandle
MethodHandle
findConstructor(Class<?> a, MethodType b)
MethodHandle
MethodHandle
MethodHandle
MethodHandle
MethodHandle
findStaticGetter(Class<?> a, String b,
Class<?> c)
MethodHandle
findStaticSetter(Class<?> a, String b,
Class<?> c)
MethodHandle
MethodHandles.Lookup
in(Class<?> a)
Class<?>
lookupClass()
int
lookupModes()
java.lang.invoke.MethodHandleInfo revealDirect(MethodHandle a)
MethodHandle
unreflect(Object a)
MethodHandle
unreflectConstructor(Object a)
MethodHandle
unreflectGetter(Object a)
MethodHandle
unreflectSetter(Object a)
Class MethodHandles.Lookup
417
unreflectSpecial(Object a, Class<?> b)
Field Detail
PUBLIC
public static final int PUBLIC
See Also:
Constant Field Values
PRIVATE
public static final int PRIVATE
See Also:
Constant Field Values
PROTECTED
public static final int PROTECTED
See Also:
Constant Field Values
PACKAGE
public static final int PACKAGE
See Also:
Constant Field Values
Constructor Detail
Lookup
public Lookup()
Method Detail
lookupClass
public Class<?> lookupClass()
lookupModes
public int lookupModes()
in
public MethodHandles.Lookup in(Class<?> a)
findStatic
public MethodHandle findStatic(Class<?> a,
String b,
MethodType c)
throws java.lang.NoSuchMethodException,
IllegalAccessException
Throws:
java.lang.NoSuchMethodException
IllegalAccessException
Method Summary
418
Throws:
java.lang.NoSuchMethodException
IllegalAccessException
findConstructor
public MethodHandle findConstructor(Class<?> a,
MethodType b)
throws java.lang.NoSuchMethodException,
IllegalAccessException
Throws:
java.lang.NoSuchMethodException
IllegalAccessException
findSpecial
public MethodHandle findSpecial(Class<?> a,
String b,
MethodType c,
Class<?> d)
throws java.lang.NoSuchMethodException,
IllegalAccessException
Throws:
java.lang.NoSuchMethodException
IllegalAccessException
findGetter
public MethodHandle findGetter(Class<?> a,
String b,
Class<?> c)
throws java.lang.NoSuchFieldException,
IllegalAccessException
Throws:
java.lang.NoSuchFieldException
IllegalAccessException
findSetter
public MethodHandle findSetter(Class<?> a,
String b,
Class<?> c)
throws java.lang.NoSuchFieldException,
IllegalAccessException
Throws:
java.lang.NoSuchFieldException
IllegalAccessException
findStaticGetter
public MethodHandle findStaticGetter(Class<?> a,
String b,
Class<?> c)
throws java.lang.NoSuchFieldException,
IllegalAccessException
Throws:
java.lang.NoSuchFieldException
IllegalAccessException
findStaticSetter
public MethodHandle findStaticSetter(Class<?> a,
String b,
Class<?> c)
throws java.lang.NoSuchFieldException,
IllegalAccessException
Method Detail
419
bind
public MethodHandle bind(Object a,
String b,
MethodType c)
throws java.lang.NoSuchMethodException,
IllegalAccessException
Throws:
java.lang.NoSuchMethodException
IllegalAccessException
unreflect
public MethodHandle unreflect(Object a)
throws IllegalAccessException
Throws:
IllegalAccessException
unreflectSpecial
public MethodHandle unreflectSpecial(Object a,
Class<?> b)
throws IllegalAccessException
Throws:
IllegalAccessException
unreflectConstructor
public MethodHandle unreflectConstructor(Object a)
throws IllegalAccessException
Throws:
IllegalAccessException
unreflectGetter
public MethodHandle unreflectGetter(Object a)
throws IllegalAccessException
Throws:
IllegalAccessException
unreflectSetter
public MethodHandle unreflectSetter(Object a)
throws IllegalAccessException
Throws:
IllegalAccessException
revealDirect
public java.lang.invoke.MethodHandleInfo revealDirect(MethodHandle a)
Method Detail
420
Class MethodHandle
java.lang.Object
java.lang.invoke.MethodHandle
Deprecated.
these classes are used internally for Lambda compatibility
public abstract class
extends Object
Constructor Summary
Constructor and Description
MethodHandle()
Deprecated.
Method Summary
Modifier and Type
MethodHandle
Deprecated.
asFixedArity()
MethodHandle
Deprecated.
asSpreader(Class<?> a, int b)
MethodHandle
Deprecated.
asType(MethodType a)
MethodHandle
Deprecated.
asVarargsCollector(Class<?> a)
MethodHandle
Deprecated.
bindTo(Object a)
MethodHandle
Deprecated.
invoke(Object... a)
Object
Deprecated.
invokeExact(Object... a)
Object
Deprecated.
invokeWithArguments(List<?> a)
Object
Deprecated.
invokeWithArguments(Object... a)
Object
Deprecated.
isVarargsCollector()
boolean
Class MethodHandle
Deprecated.
421
Deprecated.
MethodType
Constructor Detail
MethodHandle
public MethodHandle()
Deprecated.
Method Detail
type
public MethodType type()
Deprecated.
invokeExact
public final Object invokeExact(Object... a)
throws Throwable
Deprecated.
Throws:
Throwable
invoke
public final Object invoke(Object... a)
throws Throwable
Deprecated.
Throws:
Throwable
invokeWithArguments
public Object invokeWithArguments(Object... a)
throws Throwable
Deprecated.
Throws:
Throwable
invokeWithArguments
public Object invokeWithArguments(List<?> a)
throws Throwable
Deprecated.
Throws:
Throwable
asType
public MethodHandle asType(MethodType a)
Deprecated.
Method Summary
422
Deprecated.
asCollector
public MethodHandle asCollector(Class<?> a,
int b)
Deprecated.
asVarargsCollector
public MethodHandle asVarargsCollector(Class<?> a)
Deprecated.
isVarargsCollector
public boolean isVarargsCollector()
Deprecated.
asFixedArity
public MethodHandle asFixedArity()
Deprecated.
bindTo
public MethodHandle bindTo(Object a)
Deprecated.
Method Detail
423
Class LambdaMetafactory
java.lang.Object
java.lang.invoke.LambdaMetafactory
Deprecated.
these classes are used internally for Lambda compatibility
public class
extends Object
Field Summary
Modifier and Type Field and Description
FLAG_BRIDGES
static int
Deprecated.
FLAG_MARKERS
static int
Deprecated.
FLAG_SERIALIZABLE
static int
Deprecated.
Constructor Summary
Constructor and Description
LambdaMetafactory()
Deprecated.
Method Summary
Modifier and
Type
static
CallSite
static
CallSite
Deprecated.
metafactory(MethodHandles.Lookup a, String f, MethodType b,
MethodType c, MethodHandle d, MethodType e)
Deprecated.
Field Detail
Class LambdaMetafactory
424
Deprecated.
See Also:
Constant Field Values
FLAG_MARKERS
public static final int FLAG_MARKERS
Deprecated.
See Also:
Constant Field Values
FLAG_BRIDGES
public static final int FLAG_BRIDGES
Deprecated.
See Also:
Constant Field Values
Constructor Detail
LambdaMetafactory
public LambdaMetafactory()
Deprecated.
Method Detail
metafactory
public static CallSite metafactory(MethodHandles.Lookup a,
String f,
MethodType b,
MethodType c,
MethodHandle d,
MethodType e)
throws java.lang.invoke.LambdaConversionException
Deprecated.
Throws:
java.lang.invoke.LambdaConversionException
altMetafactory
public static CallSite altMetafactory(MethodHandles.Lookup a,
String b,
MethodType c,
Object... d)
throws java.lang.invoke.LambdaConversionException
Deprecated.
Throws:
java.lang.invoke.LambdaConversionException
Field Detail
425
Class CallSite
java.lang.Object
java.lang.invoke.CallSite
Deprecated.
these classes are used internally for Lambda compatibility
public abstract class
extends Object
Constructor Summary
Constructor and Description
CallSite()
Deprecated.
Method Summary
Modifier and Type
abstract MethodHandle
Deprecated.
getTarget()
abstract MethodHandle
Deprecated.
setTarget(MethodHandle mh)
abstract void
Deprecated.
type()
MethodType
Deprecated.
Constructor Detail
CallSite
public CallSite()
Deprecated.
Method Detail
type
public MethodType type()
Deprecated.
Method Detail
426
Deprecated.
setTarget
public abstract void setTarget(MethodHandle mh)
Deprecated.
dynamicInvoker
public abstract MethodHandle dynamicInvoker()
Deprecated.
Method Detail
427
@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)
public @interface
value
Element Detail
value
public abstract ElementType[] value
428
Enum RetentionPolicy
java.lang.Object
java.lang.Enum<RetentionPolicy>
java.lang.annotation.RetentionPolicy
All Implemented Interfaces:
Comparable<RetentionPolicy>
public enum
extends Enum<RetentionPolicy>
A mirror of java.lang.annotation.RetentionPolicy.
Method Summary
Modifier and Type
static RetentionPolicy
static
RetentionPolicy[]
Returns the enum constant of this type with the specified name.
values()
RUNTIME
public static final RetentionPolicy RUNTIME
SOURCE
public static final RetentionPolicy SOURCE
Method Detail
Element Detail
429
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
for (RetentionPolicy c : RetentionPolicy.values())
System.out.println(c);
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static RetentionPolicy valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
Method Detail
430
@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)
public @interface
value
Element Detail
value
public abstract RetentionPolicy value
431
@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)
public @interface
Element Detail
432
Class IncompleteAnnotationException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.annotation.IncompleteAnnotationException
public class
extends RuntimeException
A mirror of java.lang.annotation.IncompleteAnnotationException.
Constructor Summary
Constructor and Description
IncompleteAnnotationException(Class<? extends Annotation> annotationType,
String elementName)
Method Summary
Modifier and Type
annotationType()
String
elementName()
Constructor Detail
IncompleteAnnotationException
public IncompleteAnnotationException(Class<? extends Annotation> annotationType,
String elementName)
Method Detail
annotationType
public Class<? extends Annotation> annotationType()
elementName
public String elementName()
433
Enum ElementType
java.lang.Object
java.lang.Enum<ElementType>
java.lang.annotation.ElementType
All Implemented Interfaces:
Comparable<ElementType>
public enum
extends Enum<ElementType>
A mirror of java.lang.annotation.ElementType.
Method Summary
Modifier and Type
static ElementType
static
ElementType[]
Returns the enum constant of this type with the specified name.
values()
Method Detail
434
FIELD
public static final ElementType FIELD
LOCAL_VARIABLE
public static final ElementType LOCAL_VARIABLE
METHOD
public static final ElementType METHOD
PACKAGE
public static final ElementType PACKAGE
PARAMETER
public static final ElementType PARAMETER
TYPE
public static final ElementType TYPE
Method Detail
values
public static ElementType[] values()
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
for (ElementType c : ElementType.values())
System.out.println(c);
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static ElementType valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
435
@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)
public @interface
Method Detail
436
Class AnnotationFormatError
java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.annotation.AnnotationFormatError
public class
extends Error
A mirror of java.lang.annotation.AnnotationFormatError.
Constructor Summary
Constructor and Description
AnnotationFormatError(String message)
AnnotationFormatError(String message, Throwable cause)
AnnotationFormatError(Throwable cause)
Method Summary
Constructor Detail
AnnotationFormatError
public AnnotationFormatError(String message)
AnnotationFormatError
public AnnotationFormatError(String message,
Throwable cause)
AnnotationFormatError
public AnnotationFormatError(Throwable cause)
437
Interface Annotation
All Known Implementing Classes:
Deprecated, Documented, Inherited, Override, Retention, SuppressWarnings, Target
public interface
A mirror of java.lang.Annotation.
Method Summary
Modifier and Type
Class<? extends
Annotation>
boolean
hashCode()
int
String
Method Detail
annotationType
Class<? extends Annotation> annotationType()
Constructor Detail
438
Class Void
java.lang.Object
java.lang.Void
Field Summary
Modifier and Type Field and Description
static Class
TYPE
Constructor Summary
Constructor and Description
Void()
Method Summary
Field Detail
TYPE
public static final Class TYPE
Constructor Detail
Void
public Void()
Method Detail
439
Class VirtualMachineError
java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.VirtualMachineError
Direct Known Subclasses:
OutOfMemoryError
Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it
to continue operating. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
VirtualMachineError()
Method Summary
Constructor Detail
VirtualMachineError
public VirtualMachineError()
Constructor Detail
440
Class Throwable
java.lang.Object
java.lang.Throwable
Direct Known Subclasses:
Error, Exception
public class
extends Object
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects
that are instances of this class (or of one of its subclasses) are thrown by the Java Virtual Machine or
can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be
the argument type in a catch clause. Instances of two subclasses, Error and Exception, are
conventionally used to indicate that exceptional situations have occurred. Typically, these instances
are freshly created in the context of the exceptional situation so as to include relevant information
(such as stack trace data). By convention, class Throwable and its subclasses have two constructors,
one that takes no arguments and one that takes a String argument that can be used to produce an
error message. A Throwable class contains a snapshot of the execution stack of its thread at the time
it was created. It can also contain a message string that gives more information about the error. Here
is one example of catching an exception: Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
Throwable()
Method Summary
Modifier and
Type
void
String
Throwable
Deprecated.
DO NOT USE THIS METHOD, its here just to get the compiler working and
isn't intended for use
printStackTrace()
void
Prints this Throwable and its backtrace to the standard error stream.
String
toString()
Constructor Detail
Constructor Detail
441
Constructs a new Throwable with the specified error message. message - the error
message. The error message is saved for later retrieval by the method.
Method Detail
initCause
public Throwable initCause(Throwable cause)
Deprecated. DO NOT USE THIS METHOD, its here just to get the compiler working
and isn't intended for use
getMessage
public String getMessage()
Prints this Throwable and its backtrace to the standard error stream. This method
prints a stack trace for this Throwable object on the error output stream that is the
value of the field System.err. The first line of output contains the result of the method
for this object. The format of the backtrace information depends on the
implementation.
toString
public String toString()
Returns a short description of this Throwable object. If this Throwable object was with
an error message string, then the result is the concatenation of three strings: The
name of the actual class of this object ": " (a colon and a space) The result of the
method for this object If this Throwable object was with no error message string, then
the name of the actual class of this object is returned.
Overrides:
toString in class Object
addSuppressed
public final void addSuppressed(Throwable exception)
Constructor Detail
442
Class Thread
java.lang.Object
java.lang.Thread
All Implemented Interfaces:
Runnable
public class
extends Object
implements Runnable
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to
have multiple threads of execution running concurrently. Every thread has a priority. Threads with
higher priority are executed in preference to threads with lower priority. There are two ways to create
a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should
override the run method of class Thread. An instance of the subclass can then be allocated and
started. For example, a thread that computes primes larger than a stated value could be written as
follows:
Field Summary
Modifier and Type
static int
static int
static int
Constructor Summary
Constructor and Description
Thread()
Allocates a new Thread object with a specific target object whose run method is called.
Thread(Runnable target, String name)
Allocates a new Thread object with the given target and name.
Thread(String name)
Method Summary
Modifier
and Type
static int
static
Thread
String
int
Method Detail
443
void
boolean
isAlive()
void
If this thread was constructed using a separate Runnable run object, then that
Runnable object's run method is called; otherwise, this method does nothing
and returns.
void
setPriority(int newPriority)
void
static void
Causes this thread to begin execution; the Java Virtual Machine calls the run
method of this thread.
void
toString()
Returns a string representation of this thread, including the thread's name and
priority.
String
yield()
static void
Causes the currently executing thread object to temporarily pause and allow
other threads to execute.
Field Detail
MAX_PRIORITY
public static final int MAX_PRIORITY
The maximum priority that a thread can have. See Also:Constant Field Values
See Also:
Constant Field Values
MIN_PRIORITY
public static final int MIN_PRIORITY
The minimum priority that a thread can have. See Also:Constant Field Values
See Also:
Constant Field Values
NORM_PRIORITY
public static final int NORM_PRIORITY
The default priority that is assigned to a thread. See Also:Constant Field Values
See Also:
Constant Field Values
Constructor Detail
Thread
public Thread()
Method Summary
444
Allocates a new Thread object with a specific target object whose run method is
called. target - the object whose run method is called.
Thread
public Thread(Runnable target,
String name)
Allocates a new Thread object with the given target and name. target - the object
whose run method is called.name - the name of the new thread.
Thread
public Thread(String name)
Allocates a new Thread object with the given name. Threads created this way must
have overridden their run() method to actually do anything. name - the name of the
new thread.
Method Detail
activeCount
public static int activeCount()
Returns this thread's name. Note that in CLDC the name of the thread can only be
set when creating the thread.
getPriority
public final int getPriority()
Tests if this thread is alive. A thread is alive if it has been started and has not yet
died.
join
public final void join()
throws InterruptedException
Constructor Detail
445
run
public void run()
If this thread was constructed using a separate Runnable run object, then that
Runnable object's run method is called; otherwise, this method does nothing and
returns. Subclasses of Thread should override this method.
Specified by:
run in interface Runnable
setPriority
public final void setPriority(int newPriority)
Causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds. The thread does not lose ownership of any
monitors.
Throws:
InterruptedException
start
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method
of this thread. The result is that two threads are running concurrently: the current
thread (which returns from the call to the start method) and the other thread (which
executes its run method).
toString
public String toString()
Returns a string representation of this thread, including the thread's name and
priority.
Overrides:
toString in class Object
yield
public static void yield()
Causes the currently executing thread object to temporarily pause and allow other
threads to execute.
Method Detail
446
Class System
java.lang.Object
java.lang.System
The System class contains several useful class fields and methods. It cannot be instantiated. Since:
JDK1.0, CLDC 1.0
Field Summary
Modifier and Type
static PrintStream
static PrintStream
Constructor Summary
Constructor and Description
System()
Method Summary
Modifier
and Type
static void
static long
static void
static void
Copies an array from the specified source array, beginning at the specified
position, to the specified position of the destination array.
currentTimeMillis()
static
String
static int
Returns the same hashcode for the given object as would be returned by the
default method hashCode(), whether or not the given object's class overrides
hashCode().
Class System
447
Detail
err
public static final PrintStream err
The "standard" error output stream. This stream is already open and ready to accept
output data. Typically this stream corresponds to display output or another output
destination specified by the host environment or user. By convention, this output
stream is used to display error messages or other information that should come to the
immediate attention of a user even if the principal output stream, the value of the
variable out, has been redirected to a file or other destination that is typically not
continuously monitored.
out
public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept
output data. Typically this stream corresponds to display output or another output
destination specified by the host environment or user. For simple stand-alone Java
applications, a typical way to write a line of output data is: System.out.println(data)
See the println methods in class PrintStream. See Also:PrintStream.println(),
PrintStream.println(boolean), PrintStream.println(char), PrintStream.println(char[]),
PrintStream.println(int), PrintStream.println(long),
PrintStream.println(java.lang.Object), PrintStream.println(java.lang.String)
Constructor Detail
System
public System()
Method Detail
arraycopy
public static void arraycopy(Object src,
int srcOffset,
Object dst,
int dstOffset,
int length)
Copies an array from the specified source array, beginning at the specified position,
to the specified position of the destination array. A subsequence of array components
are copied from the source array referenced by src to the destination array
referenced by dst. The number of components copied is equal to the length
argument. The components at positions srcOffset through srcOffset+length-1 in the
source array are copied into positions dstOffset through dstOffset+length-1,
respectively, of the destination array. If the src and dst arguments refer to the same
array object, then the copying is performed as if the components at positions
srcOffset through srcOffset+length-1 were first copied to a temporary array with
length components and then the contents of the temporary array were copied into
positions dstOffset through dstOffset+length-1 of the destination array. If dst is null,
then a NullPointerException is thrown. If src is null, then a NullPointerException is
thrown and the destination array is not modified. Otherwise, if any of the following is
true, an ArrayStoreException is thrown and the destination is not modified: The src
argument refers to an object that is not an array. The dst argument refers to an object
that is not an array. The src argument and dst argument refer to arrays whose
component types are different primitive types. The src argument refers to an array
with a primitive component type and the dst argument refers to an array with a
reference component type. The src argument refers to an array with a reference
component type and the dst argument refers to an array with a primitive component
type. Otherwise, if any of the following is true, an IndexOutOfBoundsException is
Field Detail
448
thrown and the destination is not modified: The srcOffset argument is negative. The
dstOffset argument is negative. The length argument is negative. srcOffset+length is
greater than src.length, the length of the source array. dstOffset+length is greater
than dst.length, the length of the destination array. Otherwise, if any actual
component of the source array from position srcOffset through srcOffset+length-1
cannot be converted to the component type of the destination array by assignment
conversion, an ArrayStoreException is thrown. In this case, let k be the smallest
nonnegative integer less than length such that src[srcOffset+k] cannot be converted
to the component type of the destination array; when the exception is thrown, source
array components from positions srcOffset through srcOffset+k-1 will already have
been copied to destination array positions dstOffset through dstOffset+k-1 and no
other positions of the destination array will have been modified. (Because of the
restrictions already itemized, this paragraph effectively applies only to the situation
where both arrays have component types that are reference types.)
currentTimeMillis
public static long currentTimeMillis()
Terminates the currently running Java application. The argument serves as a status
code; by convention, a nonzero status code indicates abnormal termination. This
method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n) is effectively equivalent to the call:
Runtime.getRuntime().exit(n)
gc
public static void gc()
Runs the garbage collector. Calling the gc method suggests that the Java Virtual
Machine expend effort toward recycling unused objects in order to make the memory
they currently occupy available for quick reuse. When control returns from the
method call, the Java Virtual Machine has made a best effort to reclaim space from
all discarded objects. The call System.gc() is effectively equivalent to the call:
Runtime.getRuntime().gc()
getProperty
public static String getProperty(String key)
Returns the same hashcode for the given object as would be returned by the default
method hashCode(), whether or not the given object's class overrides hashCode().
The hashcode for the null reference is zero.
Method Detail
449
@Target(value={TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})
@Retention(value=SOURCE)
public @interface
An annotation that indicates a compiler should suppress any warnings of the type specified in the
value().
Since:
1.5
value
Element Detail
value
public abstract String[] value
450
Class StringIndexOutOfBoundsException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IndexOutOfBoundsException
java.lang.StringIndexOutOfBoundsException
public class
extends IndexOutOfBoundsException
Thrown by the charAt method in class String and by other String methods to indicate that an index is
either negative or greater than or equal to the size of the string. Since: JDK1.0, CLDC 1.0 See
Also:String.charAt(int)
Constructor Summary
Constructor and Description
StringIndexOutOfBoundsException()
Method Summary
Constructor Detail
StringIndexOutOfBoundsException
public StringIndexOutOfBoundsException()
Element Detail
451
Constructor Detail
452
Class StringBuilder
java.lang.Object
java.lang.StringBuilder
A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can
be modified. At any point in time it contains some particular sequence of characters, but the length
and content of the sequence can be changed through certain method calls. String buffers are safe for
use by multiple threads. The methods are synchronized where necessary so that all the operations on
any particular instance behave as if they occur in some serial order that is consistent with the order of
the method calls made by each of the individual threads involved. String buffers are used by the
compiler to implement the binary string concatenation operator +. For example, the code: is compiled
to the equivalent of: The principal operations on a StringBuffer are the append and insert methods,
which are overloaded so as to accept data of any type. Each effectively converts a given datum to a
string and then appends or inserts the characters of that string to the string buffer. The append
method always adds these characters at the end of the buffer; the insert method adds the characters
at a specified point. For example, if z refers to a string buffer object whose current contents are
"start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas
z.insert(4, "le") would alter the string buffer to contain "starlet". In general, if sb refers to an instance of
a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(),x). Every string buffer
has a capacity. As long as the length of the character sequence contained in the string buffer does
not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer
overflows, it is automatically made larger. Since: JDK1.0, CLDC 1.0 See
Also:ByteArrayOutputStream, String
Constructor Summary
Constructor and Description
StringBuilder()
Constructs a string buffer with no characters in it and an initial capacity specified by the
length argument.
StringBuilder(String str)
Constructs a string buffer so that it represents the same sequence of characters as the string
argument; in other words, the initial contents of the string buffer is a copy of the argument
string.
Method Summary
Modifier and
Type
StringBuilder
StringBuilder
StringBuilder
StringBuilder
append(CharSequence cs)
Class StringBuilder
453
StringBuilder
StringBuilder
StringBuilder
Appends the string representation of the int argument to this string buffer.
append(long l)
StringBuilder
StringBuilder
StringBuilder
int
char
StringBuilder
StringBuilder
void
Ensures that the capacity of the buffer is at least equal to the specified
minimum.
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
void
Characters are copied from this string buffer into the destination character
array dst.
insert(int offset, boolean b)
StringBuilder
Inserts the string representation of the boolean argument into this string
buffer.
insert(int offset, char c)
StringBuilder
Inserts the string representation of the char argument into this string
buffer.
StringBuilder
StringBuilder
StringBuilder
StringBuilder
Inserts the string representation of the double argument into this string
buffer.
insert(int offset, float f)
Inserts the string representation of the float argument into this string buffer.
insert(int offset, int i)
StringBuilder
StringBuilder
Inserts the string representation of the second int argument into this string
buffer.
insert(int offset, long l)
Inserts the string representation of the long argument into this string buffer.
insert(int offset, Object obj)
StringBuilder
StringBuilder
int
Method Summary
Inserts the string representation of the Object argument into this string
buffer.
insert(int offset, String str)
454
void
The character at the specified index of this string buffer is set to ch.
setLength(int newLength)
void
StringBuilder
StringBuffer(CharSequence cs)
toString()
String
void
trimToSize()
Constructor Detail
StringBuilder
public StringBuilder()
Method Detail
append
public StringBuilder append(boolean b)
Appends the string representation of the boolean argument to the string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuilder append(char c)
Appends the string representation of the char argument to this string buffer. The
argument is appended to the contents of this string buffer. The length of this string
buffer increases by 1. The overall effect is exactly as if the argument were converted
to a string by the method String.valueOf(char) and the character in that string were
then appended to this StringBuffer object.
455
Appends the string representation of a subarray of the char array argument to this
string buffer. Characters of the character array str, starting at index offset, are
appended, in order, to the contents of this string buffer. The length of this string buffer
increases by the value of len. The overall effect is exactly as if the arguments were
converted to a string by the method String.valueOf(char[],int,int) and the characters of
that string were then appended to this StringBuffer object.
append
public StringBuilder append(double d)
Appends the string representation of the double argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuilder append(float f)
Appends the string representation of the float argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuilder append(int i)
Appends the string representation of the int argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuilder append(long l)
Appends the string representation of the long argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuilder append(Object obj)
Appends the string representation of the Object argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuilder append(String str)
Appends the string to this string buffer. The characters of the String argument are
appended, in order, to the contents of this string buffer, increasing the length of this
string buffer by the length of the argument. If str is null, then the four characters "null"
are appended to this string buffer. Let n be the length of the old character sequence,
the one contained in the string buffer just prior to execution of the append method.
Then the character at index k in the new character sequence is equal to the character
at index k in the old character sequence, if k is less than n; otherwise, it is equal to
the character at index k-n in the argument str.
capacity
public int capacity()
Returns the current capacity of the String buffer. The capacity is the amount of
storage available for newly inserted characters; beyond which an allocation will occur.
Method Detail
456
The specified character of the sequence currently represented by the string buffer, as
indicated by the index argument, is returned. The first character of a string buffer is at
index 0, the next at index 1, and so on, for array indexing. The index argument must
be greater than or equal to 0, and less than the length of this string buffer.
delete
public StringBuilder delete(int start,
int end)
Removes the character at the specified position in this StringBuffer (shortening the
StringBuffer by one character).
ensureCapacity
public void ensureCapacity(int minimumCapacity)
Ensures that the capacity of the buffer is at least equal to the specified minimum. If
the current capacity of this string buffer is less than the argument, then a new internal
buffer is allocated with greater capacity. The new capacity is the larger of: The
minimumCapacity argument. Twice the old capacity, plus 2. If the minimumCapacity
argument is nonpositive, this method takes no action and simply returns.
getChars
public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Characters are copied from this string buffer into the destination character array dst.
The first character to be copied is at index srcBegin; the last character to be copied is
at index srcEnd-1. The total number of characters to be copied is srcEnd-srcBegin.
The characters are copied into the subarray of dst starting at index dstBegin and
ending at index: dstbegin + (srcEnd-srcBegin) - 1
insert
public StringBuilder insert(int offset,
boolean b)
Inserts the string representation of the boolean argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
insert
public StringBuilder insert(int offset,
char c)
Inserts the string representation of the char argument into this string buffer. The
second argument is inserted into the contents of this string buffer at the position
indicated by offset. The length of this string buffer increases by one. The overall
effect is exactly as if the argument were converted to a string by the method
String.valueOf(char) and the character in that string were then inserted into this
StringBuffer object at the position indicated by offset. The offset argument must be
greater than or equal to 0, and less than or equal to the length of this string buffer.
Method Detail
457
Inserts the string representation of the double argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
insert
public StringBuilder insert(int offset,
float f)
Inserts the string representation of the float argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
insert
public StringBuilder insert(int offset,
int i)
Inserts the string representation of the second int argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
insert
public StringBuilder insert(int offset,
long l)
Inserts the string representation of the long argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the position
indicated by offset. The offset argument must be greater than or equal to 0, and less
than or equal to the length of this string buffer.
insert
public StringBuilder insert(int offset,
Object obj)
Inserts the string representation of the Object argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
insert
public StringBuilder insert(int offset,
String str)
Inserts the string into this string buffer. The characters of the String argument are
inserted, in order, into this string buffer at the indicated offset, moving up any
characters originally above that position and increasing the length of this string buffer
by the length of the argument. If str is null, then the four characters "null" are inserted
into this string buffer. The character at index k in the new character sequence is
equal to: the character at index k in the old character sequence, if k is less than offset
the character at index k-offset in the argument str, if k is not less than offset but is
less than offset+str.length() the character at index k-str.length() in the old character
sequence, if k is not less than offset+str.length() The offset argument must be greater
than or equal to 0, and less than or equal to the length of this string buffer.
Method Detail
458
The character sequence contained in this string buffer is replaced by the reverse of
the sequence. Let n be the length of the old character sequence, the one contained in
the string buffer just prior to execution of the reverse method. Then the character at
index k in the new character sequence is equal to the character at index n-k-1 in the
old character sequence.
setCharAt
public void setCharAt(int index,
char ch)
The character at the specified index of this string buffer is set to ch. The string buffer
is altered to represent a new character sequence that is identical to the old character
sequence, except that it contains the character ch at position index. The offset
argument must be greater than or equal to 0, and less than the length of this string
buffer.
setLength
public void setLength(int newLength)
Sets the length of this string buffer. This string buffer is altered to represent a new
character sequence whose length is specified by the argument. For every
nonnegative index less than newLength, the character at index in the new character
sequence is the same as the character at index in the old sequence if is less than the
length of the old character sequence; otherwise, it is the null character ''. In other
words, if the newLength argument is less than the current length of the string buffer,
the string buffer is truncated to contain exactly the number of characters given by the
newLength argument. If the newLength argument is greater than or equal to the
current length, sufficient null characters ('u0000') are appended to the string buffer so
that length becomes the newLength argument. The newLength argument must be
greater than or equal to 0.
toString
public String toString()
Converts to a string representing the data in this string buffer. A new String object is
allocated and initialized to contain the character sequence currently represented by
this string buffer. This String is then returned. Subsequent changes to the string
buffer do not affect the contents of the String. Implementation advice: This method
can be coded so as to create a new String object without allocating new memory to
hold a copy of the character sequence. Instead, the string can share the memory
used by the string buffer. Any subsequent operation that alters the content or
capacity of the string buffer must then make a copy of the internal buffer at that time.
This strategy is effective for reducing the amount of memory allocated by a string
concatenation operation when it is implemented using a string buffer.
Overrides:
toString in class Object
StringBuffer
public StringBuilder StringBuffer(CharSequence cs)
trimToSize
public void trimToSize()
append
public StringBuilder append(CharSequence cs)
Method Detail
459
insert
public StringBuilder insert(int offset,
CharSequence cs)
insert
public StringBuilder insert(int offset,
CharSequence cs,
int start,
int end)
Method Detail
460
Class StringBuffer
java.lang.Object
java.lang.StringBuffer
A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can
be modified. At any point in time it contains some particular sequence of characters, but the length
and content of the sequence can be changed through certain method calls. String buffers are safe for
use by multiple threads. The methods are synchronized where necessary so that all the operations on
any particular instance behave as if they occur in some serial order that is consistent with the order of
the method calls made by each of the individual threads involved. String buffers are used by the
compiler to implement the binary string concatenation operator +. For example, the code: is compiled
to the equivalent of: The principal operations on a StringBuffer are the append and insert methods,
which are overloaded so as to accept data of any type. Each effectively converts a given datum to a
string and then appends or inserts the characters of that string to the string buffer. The append
method always adds these characters at the end of the buffer; the insert method adds the characters
at a specified point. For example, if z refers to a string buffer object whose current contents are
"start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas
z.insert(4, "le") would alter the string buffer to contain "starlet". In general, if sb refers to an instance of
a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(),x). Every string buffer
has a capacity. As long as the length of the character sequence contained in the string buffer does
not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer
overflows, it is automatically made larger. Since: JDK1.0, CLDC 1.0 See
Also:ByteArrayOutputStream, String
Constructor Summary
Constructor and Description
StringBuffer()
Constructs a string buffer with no characters in it and an initial capacity specified by the
length argument.
StringBuffer(String str)
Constructs a string buffer so that it represents the same sequence of characters as the string
argument; in other words, the initial contents of the string buffer is a copy of the argument
string.
Method Summary
Modifier and
Type
StringBuffer
StringBuffer
Appends the string representation of the char argument to this string buffer.
append(char[] str, int offset, int len)
StringBuffer
StringBuffer
append(CharSequence cs)
Class StringBuffer
461
StringBuffer
StringBuffer
StringBuffer
StringBuffer
Appends the string representation of the float argument to this string buffer.
append(int i)
Appends the string representation of the int argument to this string buffer.
append(long l)
Appends the string representation of the long argument to this string buffer.
append(Object obj)
StringBuffer
StringBuffer
int
char
StringBuffer
StringBuffer
void
Ensures that the capacity of the buffer is at least equal to the specified
minimum.
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
void
Characters are copied from this string buffer into the destination character
array dst.
insert(int offset, boolean b)
StringBuffer
StringBuffer
Inserts the string representation of the boolean argument into this string
buffer.
insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
StringBuffer
StringBuffer
StringBuffer
StringBuffer
Inserts the string representation of the double argument into this string
buffer.
insert(int offset, float f)
Inserts the string representation of the float argument into this string buffer.
insert(int offset, int i)
StringBuffer
StringBuffer
Inserts the string representation of the second int argument into this string
buffer.
insert(int offset, long l)
Inserts the string representation of the long argument into this string buffer.
insert(int offset, Object obj)
StringBuffer
StringBuffer
int
Inserts the string representation of the Object argument into this string
buffer.
insert(int offset, String str)
StringBuffer
Method Summary
462
void
The character at the specified index of this string buffer is set to ch.
setLength(int newLength)
void
StringBuffer
StringBuffer(CharSequence cs)
toString()
String
void
trimToSize()
Constructor Detail
StringBuffer
public StringBuffer()
Method Detail
append
public StringBuffer append(boolean b)
Appends the string representation of the boolean argument to the string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuffer append(char c)
Appends the string representation of the char argument to this string buffer. The
argument is appended to the contents of this string buffer. The length of this string
buffer increases by 1. The overall effect is exactly as if the argument were converted
to a string by the method String.valueOf(char) and the character in that string were
then appended to this StringBuffer object.
append
public StringBuffer append(char[] str,
int offset,
int len)
463
Appends the string representation of the double argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuffer append(float f)
Appends the string representation of the float argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuffer append(int i)
Appends the string representation of the int argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuffer append(long l)
Appends the string representation of the long argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuffer append(Object obj)
Appends the string representation of the Object argument to this string buffer. The
argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then appended to this string buffer.
append
public StringBuffer append(String str)
Appends the string to this string buffer. The characters of the String argument are
appended, in order, to the contents of this string buffer, increasing the length of this
string buffer by the length of the argument. If str is null, then the four characters "null"
are appended to this string buffer. Let n be the length of the old character sequence,
the one contained in the string buffer just prior to execution of the append method.
Then the character at index k in the new character sequence is equal to the character
at index k in the old character sequence, if k is less than n; otherwise, it is equal to
the character at index k-n in the argument str.
capacity
public int capacity()
Returns the current capacity of the String buffer. The capacity is the amount of
storage available for newly inserted characters; beyond which an allocation will occur.
charAt
public char charAt(int index)
The specified character of the sequence currently represented by the string buffer, as
indicated by the index argument, is returned. The first character of a string buffer is at
index 0, the next at index 1, and so on, for array indexing. The index argument must
be greater than or equal to 0, and less than the length of this string buffer.
Method Detail
464
Removes the character at the specified position in this StringBuffer (shortening the
StringBuffer by one character).
ensureCapacity
public void ensureCapacity(int minimumCapacity)
Ensures that the capacity of the buffer is at least equal to the specified minimum. If
the current capacity of this string buffer is less than the argument, then a new internal
buffer is allocated with greater capacity. The new capacity is the larger of: The
minimumCapacity argument. Twice the old capacity, plus 2. If the minimumCapacity
argument is nonpositive, this method takes no action and simply returns.
getChars
public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Characters are copied from this string buffer into the destination character array dst.
The first character to be copied is at index srcBegin; the last character to be copied is
at index srcEnd-1. The total number of characters to be copied is srcEnd-srcBegin.
The characters are copied into the subarray of dst starting at index dstBegin and
ending at index: dstbegin + (srcEnd-srcBegin) - 1
insert
public StringBuffer insert(int offset,
boolean b)
Inserts the string representation of the boolean argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
insert
public StringBuffer insert(int offset,
char c)
Inserts the string representation of the char argument into this string buffer. The
second argument is inserted into the contents of this string buffer at the position
indicated by offset. The length of this string buffer increases by one. The overall
effect is exactly as if the argument were converted to a string by the method
String.valueOf(char) and the character in that string were then inserted into this
StringBuffer object at the position indicated by offset. The offset argument must be
greater than or equal to 0, and less than or equal to the length of this string buffer.
insert
public StringBuffer insert(int offset,
double d)
Inserts the string representation of the double argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
Method Detail
465
Inserts the string representation of the float argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
insert
public StringBuffer insert(int offset,
int i)
Inserts the string representation of the second int argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
insert
public StringBuffer insert(int offset,
long l)
Inserts the string representation of the long argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the position
indicated by offset. The offset argument must be greater than or equal to 0, and less
than or equal to the length of this string buffer.
insert
public StringBuffer insert(int offset,
Object obj)
Inserts the string representation of the Object argument into this string buffer. The
second argument is converted to a string as if by the method String.valueOf, and the
characters of that string are then inserted into this string buffer at the indicated offset.
The offset argument must be greater than or equal to 0, and less than or equal to the
length of this string buffer.
insert
public StringBuffer insert(int offset,
String str)
Inserts the string into this string buffer. The characters of the String argument are
inserted, in order, into this string buffer at the indicated offset, moving up any
characters originally above that position and increasing the length of this string buffer
by the length of the argument. If str is null, then the four characters "null" are inserted
into this string buffer. The character at index k in the new character sequence is
equal to: the character at index k in the old character sequence, if k is less than offset
the character at index k-offset in the argument str, if k is not less than offset but is
less than offset+str.length() the character at index k-str.length() in the old character
sequence, if k is not less than offset+str.length() The offset argument must be greater
than or equal to 0, and less than or equal to the length of this string buffer.
length
public int length()
The character sequence contained in this string buffer is replaced by the reverse of
the sequence. Let n be the length of the old character sequence, the one contained in
the string buffer just prior to execution of the reverse method. Then the character at
index k in the new character sequence is equal to the character at index n-k-1 in the
Method Detail
466
The character at the specified index of this string buffer is set to ch. The string buffer
is altered to represent a new character sequence that is identical to the old character
sequence, except that it contains the character ch at position index. The offset
argument must be greater than or equal to 0, and less than the length of this string
buffer.
setLength
public void setLength(int newLength)
Sets the length of this string buffer. This string buffer is altered to represent a new
character sequence whose length is specified by the argument. For every
nonnegative index less than newLength, the character at index in the new character
sequence is the same as the character at index in the old sequence if is less than the
length of the old character sequence; otherwise, it is the null character ''. In other
words, if the newLength argument is less than the current length of the string buffer,
the string buffer is truncated to contain exactly the number of characters given by the
newLength argument. If the newLength argument is greater than or equal to the
current length, sufficient null characters ('u0000') are appended to the string buffer so
that length becomes the newLength argument. The newLength argument must be
greater than or equal to 0.
toString
public String toString()
Converts to a string representing the data in this string buffer. A new String object is
allocated and initialized to contain the character sequence currently represented by
this string buffer. This String is then returned. Subsequent changes to the string
buffer do not affect the contents of the String. Implementation advice: This method
can be coded so as to create a new String object without allocating new memory to
hold a copy of the character sequence. Instead, the string can share the memory
used by the string buffer. Any subsequent operation that alters the content or
capacity of the string buffer must then make a copy of the internal buffer at that time.
This strategy is effective for reducing the amount of memory allocated by a string
concatenation operation when it is implemented using a string buffer.
Overrides:
toString in class Object
StringBuffer
public StringBuffer StringBuffer(CharSequence cs)
trimToSize
public void trimToSize()
append
public StringBuffer append(CharSequence cs)
append
public StringBuffer append(CharSequence cs,
int start,
int end)
insert
public StringBuffer insert(int offset,
CharSequence cs)
insert
public StringBuffer insert(int offset,
CharSequence cs,
int start,
int end)
Method Detail
467
Class String
java.lang.Object
java.lang.String
The String class represents character strings. All string literals in Java programs, such as "abc", are
implemented as instances of this class. Strings are constant; their values cannot be changed after
they are created. String buffers support mutable strings. Because String objects are immutable they
can be shared. For example: is equivalent to: Here are some more examples of how strings can be
used: The class String includes methods for examining individual characters of the sequence, for
comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string
with all characters translated to uppercase or to lowercase. The Java language provides special
support for the string concatenation operator (+), and for conversion of other objects to strings. String
concatenation is implemented through the StringBuffer class and its append method. String
conversions are implemented through the method toString, defined by Object and inherited by all
classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy,
and Steele, The Java Language Specification. Since: JDK1.0, CLDC 1.0 See Also:Object.toString(),
StringBuffer, StringBuffer.append(boolean), StringBuffer.append(char), StringBuffer.append(char[]),
StringBuffer.append(char[], int, int), StringBuffer.append(int), StringBuffer.append(long),
StringBuffer.append(java.lang.Object), StringBuffer.append(java.lang.String)
Constructor Summary
Constructor and Description
String()
Initializes a newly created String object so that it represents an empty character sequence.
String(byte[] bytes)
Construct a new String by converting the specified array of bytes using the platform's default
character encoding.
String(byte[] bytes, int off, int len)
Construct a new String by converting the specified subarray of bytes using the platform's
default character encoding.
String(byte[] bytes, int off, int len, String enc)
Construct a new String by converting the specified subarray of bytes using the specified
character encoding.
String(byte[] bytes, String enc)
Construct a new String by converting the specified array of bytes using the specified
character encoding.
String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained
in the character array argument.
String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array
argument.
String(String value)
Initializes a newly created String object so that it represents the same sequence of
characters as the argument; in other words, the newly created string is a copy of the
argument string.
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the
string buffer argument.
Class String
468
Method Summary
Modifier
and Type
char
int
String
boolean
boolean
boolean
byte[]
Convert this String into bytes according to the platform's default character
encoding, storing the result into a new byte array.
getBytes(String enc)
byte[]
void
int
Convert this String into bytes according to the specified character encoding,
storing the result into a new byte array.
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
hashCode()
int
Returns the index within this string of the first occurrence of the specified
character.
indexOf(int ch, int fromIndex)
int
Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
indexOf(String str)
int
Returns the index within this string of the first occurrence of the specified
substring.
indexOf(String str, int fromIndex)
int
String
Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
intern()
int
Returns the index within this string of the last occurrence of the specified
character.
lastIndexOf(int ch, int fromIndex)
int
int
int
int
boolean
Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.
lastIndexOf(String string)
Searches in this string for the last index of the specified string.
lastIndexOf(String subString, int start)
Method Summary
Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.
469
boolean
startsWith(String prefix)
boolean
String
String
char[]
String
String
String
String
Tests if this string starts with the specified prefix beginning at the specified
index.
substring(int beginIndex)
static
String
valueOf(boolean b)
static
String
valueOf(char c)
static
String
static
String
valueOf(double d)
static
String
valueOf(float f)
static
String
valueOf(int i)
static
String
valueOf(long l)
static
String
valueOf(Object obj)
Constructor Detail
String
public String()
Construct a new String by converting the specified array of bytes using the platform's
default character encoding. The length of the new String is a function of the encoding,
and hence may not be equal to the length of the byte array. bytes - The bytes to be
converted into characters JDK1.1
470
Construct a new String by converting the specified subarray of bytes using the
platform's default character encoding. The length of the new String is a function of the
encoding, and hence may not be equal to the length of the subarray. bytes - The
bytes to be converted into charactersoff - Index of the first byte to convertlen Number of bytes to convert JDK1.1
String
public String(byte[] bytes,
int off,
int len,
String enc)
throws UnsupportedEncodingException
Construct a new String by converting the specified subarray of bytes using the
specified character encoding. The length of the new String is a function of the
encoding, and hence may not be equal to the length of the subarray. bytes - The
bytes to be converted into charactersoff - Index of the first byte to convertlen Number of bytes to convertenc - The name of a character encoding - If the named
encoding is not supported JDK1.1
Throws:
UnsupportedEncodingException
String
public String(byte[] bytes,
String enc)
throws UnsupportedEncodingException
Construct a new String by converting the specified array of bytes using the specified
character encoding. The length of the new String is a function of the encoding, and
hence may not be equal to the length of the byte array. bytes - The bytes to be
converted into charactersenc - The name of a supported character encoding - If the
named encoding is not supported JDK1.1
Throws:
UnsupportedEncodingException
String
public String(char[] value)
Allocates a new String that contains characters from a subarray of the character array
argument. The offset argument is the index of the first character of the subarray and
the count argument specifies the length of the subarray. The contents of the subarray
are copied; subsequent modification of the character array does not affect the newly
created string. value - array that is the source of characters.offset - the initial
offset.count - the length. - if the offset and count arguments index characters outside
the bounds of the value array. - if value is null.
String
public String(String value)
Initializes a newly created String object so that it represents the same sequence of
characters as the argument; in other words, the newly created string is a copy of the
argument string. value - a String.
Constructor Detail
471
Allocates a new string that contains the sequence of characters currently contained in
the string buffer argument. The contents of the string buffer are copied; subsequent
modification of the string buffer does not affect the newly created string. buffer - a
StringBuffer. - If buffer is null.
Method Detail
charAt
public char charAt(int index)
Returns the character at the specified index. An index ranges from 0 to length() - 1.
The first character of the sequence is at index 0, the next at index 1, and so on, as for
array indexing.
compareTo
public int compareTo(String anotherString)
Concatenates the specified string to the end of this string. If the length of the
argument string is 0, then this String object is returned. Otherwise, a new String
object is created, representing a character sequence that is the concatenation of the
character sequence represented by this String object and the character sequence
represented by the argument string. Examples: "cares".concat("s") returns "caress"
"to".concat("get").concat("her") returns "together"
endsWith
public boolean endsWith(String suffix)
Compares this string to the specified object. The result is true if and only if the
argument is not null and is a String object that represents the same sequence of
characters as this object.
Overrides:
equals in class Object
Constructor Detail
472
Compares this String to another String, ignoring case considerations. Two strings are
considered equal ignoring case if they are of the same length, and corresponding
characters in the two strings are equal ignoring case. Two characters c1 and c2 are
considered the same, ignoring case if at least one of the following is true: The two
characters are the same (as compared by the == operator). Applying the method
Character.toUpperCase(char) to each character produces the same result. Applying
the method Character.toLowerCase(char) to each character produces the same
result.
getBytes
public byte[] getBytes()
Convert this String into bytes according to the platform's default character encoding,
storing the result into a new byte array.
getBytes
public byte[] getBytes(String enc)
throws UnsupportedEncodingException
Convert this String into bytes according to the specified character encoding, storing
the result into a new byte array.
Throws:
UnsupportedEncodingException
getChars
public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Copies characters from this string into the destination character array. The first
character to be copied is at index srcBegin; the last character to be copied is at index
srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin). The
characters are copied into the subarray of dst starting at index dstBegin and ending
at index: dstbegin + (srcEnd-srcBegin) - 1
hashCode
public int hashCode()
Returns a hashcode for this string. The hashcode for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] using int arithmetic, where s[i] is the th
character of the string, n is the length of the string, and ^ indicates exponentiation.
(The hash value of the empty string is zero.)
Overrides:
hashCode in class Object
indexOf
public int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character. If
a character with value ch occurs in the character sequence represented by this String
object, then the index of the first such occurrence is returned -- that is, the smallest
value such that: this.charAt( ) == ch is true. If no such character occurs in this string,
then -1 is returned.
indexOf
public int indexOf(int ch,
int fromIndex)
Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index. If a character with value ch occurs in the
character sequence represented by this String object at an index no smaller than
fromIndex, then the index of the first such occurrence is returned--that is, the smallest
value k such that: (this.charAt( ) == ch) && ( >= fromIndex) is true. If no such
Method Detail
473
Returns the index within this string of the first occurrence of the specified substring.
The integer returned is the smallest value such that: this.startsWith(str, ) is true.
indexOf
public int indexOf(String str,
int fromIndex)
Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index. The integer returned is the smallest value such that:
this.startsWith(str, ) && ( >= fromIndex) is true. There is no restriction on the value of
fromIndex. If it is negative, it has the same effect as if it were zero: this entire string
may be searched. If it is greater than the length of this string, it has the same effect
as if it were equal to the length of this string: -1 is returned.
intern
public String intern()
Returns a canonical representation for the string object. A pool of strings, initially
empty, is maintained privately by the class String. When the intern method is invoked,
if the pool already contains a string equal to this String object as determined by the
equals(Object) method, then the string from the pool is returned. Otherwise, this
String object is added to the pool and a reference to this String object is returned. It
follows that for any two strings s and t, s.intern()==t.intern() is true if and only if
s.equals(t) is true. All literal strings and string-valued constant expressions are
interned. String literals are defined in Section 3.10.5 of the Java Language
Specification
lastIndexOf
public int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
That is, the index returned is the largest value such that: this.charAt( ) == ch is true.
The String is searched backwards starting at the last character.
lastIndexOf
public int lastIndexOf(int ch,
int fromIndex)
Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index. That is, the index returned is the
largest value such that: (this.charAt(k) == ch) && (k <= fromIndex) is true.
lastIndexOf
public int lastIndexOf(String string)
Searches in this string for the last index of the specified string. The search for the
string starts at the end and moves towards the beginning of this string.
Parameters:
string - the string to find.
Returns:
the index of the first character of the specified string in this string, -1 if the
specified string is not a substring.
Throws:
NullPointerException - if string is null.
Method Detail
474
Searches in this string for the index of the specified string. The search for the string
starts at the specified offset and moves towards the beginning of this string.
Parameters:
subString - the string to find.
start - the starting offset.
Returns:
the index of the first character of the specified string in this string , -1 if the
specified string is not a substring.
Throws:
NullPointerException - if subString is null.
length
public int length()
Returns the length of this string. The length is equal to the number of 16-bit Unicode
characters in the string.
regionMatches
public boolean regionMatches(boolean ignoreCase,
int toffset,
String other,
int ooffset,
int len)
Tests if two string regions are equal. A substring of this String object is compared to a
substring of the argument other. The result is true if these substrings represent
character sequences that are the same, ignoring case if and only if ignoreCase is
true. The substring of this String object to be compared begins at index toffset and
has length len. The substring of other to be compared begins at index ooffset and has
length len. The result is false if and only if at least one of the following is true: toffset
is negative. ooffset is negative. toffset+len is greater than the length of this String
object. ooffset+len is greater than the length of the other argument. There is some
nonnegative integer k less than len such that: this.charAt(toffset+k) !=
other.charAt(ooffset+k) ignoreCase is true and there is some nonnegative integer
less than len such that: Character.toLowerCase(this.charAt(toffset+k)) !=
Character.toLowerCase(other.charAt(ooffset+k)) and:
Character.toUpperCase(this.charAt(toffset+k)) !=
Character.toUpperCase(other.charAt(ooffset+k))
replace
public String replace(char oldChar,
char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string
with newChar. If the character oldChar does not occur in the character sequence
represented by this String object, then a reference to this String object is returned.
Otherwise, a new String object is created that represents a character sequence
identical to the character sequence represented by this String object, except that
every occurrence of oldChar is replaced by an occurrence of newChar. Examples:
"mesquite in your cellar".replace('e', 'o') returns "mosquito in your collar" "the war of
baronets".replace('r', 'y') returns "the way of bayonets" "sparring with a purple
porpoise".replace('p', 't') returns "starring with a turtle tortoise" "JonL".replace('q', 'x')
returns "JonL" (no change)
startsWith
public boolean startsWith(String prefix)
Method Detail
475
Tests if this string starts with the specified prefix beginning at the specified index.
substring
public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the
character at the specified index and extends to the end of this string. Examples:
"unhappy".substring(2) returns "happy" "Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
substring
public String substring(int beginIndex,
int endIndex)
Returns a new string that is a substring of this string. The substring begins at the
specified beginIndex and extends to the character at index endIndex - 1. Thus the
length of the substring is endIndex-beginIndex. Examples: "hamburger".substring(4,
8) returns "urge" "smiles".substring(1, 5) returns "mile"
toCharArray
public char[] toCharArray()
Removes white space from both ends of this string. If this String object represents an
empty character sequence, or the first and last characters of character sequence
represented by this String object both have codes greater than 'u0020' (the space
character), then a reference to this String object is returned. Otherwise, if there is no
character with a code greater than 'u0020' in the string, then a new String object
representing an empty string is created and returned. Otherwise, let k be the index of
the first character in the string whose code is greater than 'u0020', and let m be the
index of the last character in the string whose code is greater than 'u0020'. A new
String object is created, representing the substring of this string that begins with the
character at index k and ends with the character at index m-that is, the result of
this.substring(k,m+1). This method may be used to trim whitespace from the
beginning and end of a string; in fact, it trims all ASCII control characters as well.
valueOf
public static String valueOf(boolean b)
Method Detail
476
Returns the string representation of a specific subarray of the char array argument.
The offset argument is the index of the first character of the subarray. The count
argument specifies the length of the subarray. The contents of the subarray are
copied; subsequent modification of the character array does not affect the newly
created string.
valueOf
public static String valueOf(double d)
Returns the string representation of the float argument. The representation is exactly
the one returned by the Float.toString method of one argument.
valueOf
public static String valueOf(int i)
Returns the string representation of the int argument. The representation is exactly
the one returned by the Integer.toString method of one argument.
valueOf
public static String valueOf(long l)
Returns the string representation of the long argument. The representation is exactly
the one returned by the Long.toString method of one argument.
valueOf
public static String valueOf(Object obj)
Method Detail
477
Class Short
java.lang.Object
java.lang.Short
The Short class is the standard wrapper for short values. Since: JDK1.1, CLDC 1.0
Field Summary
Modifier and Type
static short
static short
Constructor Summary
Constructor and Description
Short(short value)
Method Summary
Modifier and
Type
boolean
int
static short
parseShort(String s)
Assuming the specified String represents a short, returns that short's value.
parseShort(String s, int radix)
static short
Assuming the specified String represents a short, returns that short's value in
the radix specified by the second argument.
shortValue()
short
String
static Short
valueOf(short i)
Field Detail
Class Short
478
The maximum value a Short can have. See Also:Constant Field Values
See Also:
Constant Field Values
MIN_VALUE
public static final short MIN_VALUE
The minimum value a Short can have. See Also:Constant Field Values
See Also:
Constant Field Values
Constructor Detail
Short
public Short(short value)
Constructs a Short object initialized to the specified short value. value - the initial
value of the Short
Method Detail
equals
public boolean equals(Object obj)
Assuming the specified String represents a short, returns that short's value. Throws
an exception if the String cannot be parsed as a short. The radix is assumed to be
10.
Throws:
NumberFormatException
parseShort
public static short parseShort(String s,
int radix)
throws NumberFormatException
Assuming the specified String represents a short, returns that short's value in the
radix specified by the second argument. Throws an exception if the String cannot be
parsed as a short.
Throws:
NumberFormatException
Field Detail
479
Method Detail
480
Class SecurityException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.SecurityException
public class
extends RuntimeException
Thrown by the system to indicate a security violation. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
SecurityException()
Method Summary
Constructor Detail
SecurityException
public SecurityException()
Class SecurityException
481
Class RuntimeException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
Direct Known Subclasses:
ArithmeticException, ArrayStoreException, ClassCastException,
ConcurrentModificationException, EmptyStackException, IllegalArgumentException,
IllegalMonitorStateException, IllegalStateException, IncompleteAnnotationException,
IndexOutOfBoundsException, NegativeArraySizeException, NoSuchElementException,
NullPointerException, RESyntaxException, SecurityException
public class
extends Exception
RuntimeException is the superclass of those exceptions that can be thrown during the normal
operation of the Java Virtual Machine. A method is not required to declare in its throws clause any
subclasses of RuntimeException that might be thrown during the execution of the method but not
caught. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
RuntimeException()
Method Summary
Constructor Detail
RuntimeException
public RuntimeException()
Constructor Detail
482
Class Runtime
java.lang.Object
java.lang.Runtime
public class
extends Object
Every Java application has a single instance of class Runtime that allows the application to interface
with the environment in which the application is running. The current runtime can be obtained from the
getRuntime method. An application cannot create its own instance of this class. Since: JDK1.0, CLDC
1.0 See Also:getRuntime()
Constructor Summary
Constructor and Description
Runtime()
Method Summary
Modifier and Type
void
long
void
static Runtime
getRuntime()
Returns the runtime object associated with the current Java application.
totalMemory()
long
Constructor Detail
Runtime
public Runtime()
Method Detail
exit
public void exit(int status)
Terminates the currently running Java application. This method never returns
normally. The argument serves as a status code; by convention, a nonzero status
code indicates abnormal termination.
Constructor Detail
483
Returns the amount of free memory in the system. Calling the gc method may result
in increasing the value returned by freeMemory.
gc
public void gc()
Runs the garbage collector. Calling this method suggests that the Java Virtual
Machine expend effort toward recycling unused objects in order to make the memory
they currently occupy available for quick reuse. When control returns from the
method call, the Java Virtual Machine has made its best effort to recycle all discarded
objects. The name gc stands for "garbage collector". The Java Virtual Machine
performs this recycling process automatically as needed even if the gc method is not
invoked explicitly. The method System.gc() is the conventional and convenient
means of invoking this method.
getRuntime
public static Runtime getRuntime()
Returns the runtime object associated with the current Java application. Most of the
methods of class Runtime are instance methods and must be invoked with respect to
the current runtime object.
totalMemory
public long totalMemory()
Returns the total amount of memory in the Java Virtual Machine. The value returned
by this method may vary over time, depending on the host environment. Note that the
amount of memory required to hold an object of any given type may be
implementation-dependent.
Method Detail
484
Interface Runnable
All Known Implementing Classes:
Thread, TimerTask
public interface
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. The class must define a method of no arguments called run. This interface is
designed to provide a common protocol for objects that wish to execute code while they are active.
For example, Runnable is implemented by class Thread. Being active simply means that a thread has
been started and has not yet been stopped. In addition, Runnable provides the means for a class to
be active while not subclassing Thread. A class that implements Runnable can run without
subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most
cases, the Runnable interface should be used if you are only planning to override the run() method
and no other Thread methods. This is important because classes should not be subclassed unless
the programmer intends on modifying or enhancing the fundamental behavior of the class. Since:
JDK1.0, CLDC 1.0 See Also:Thread
Method Summary
Modifier
and Type
void
Method Detail
run
void run()
Interface Runnable
485
@Target(value=METHOD)
@Retention(value=SOURCE)
public @interface
An annotation to indicate that a method is intended to override a superclass method. This provides a
compile-time assertion that a method actually overrides the superclass method.
Since:
1.5
Method Detail
486
Class OutOfMemoryError
java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.VirtualMachineError
java.lang.OutOfMemoryError
public class
extends VirtualMachineError
Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no
more memory could be made available by the garbage collector. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
OutOfMemoryError()
Method Summary
Constructor Detail
OutOfMemoryError
public OutOfMemoryError()
487
Class Object
java.lang.Object
public class
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects,
including arrays, implement the methods of this class. Since: JDK1.0, CLDC 1.0 See Also:Class
Constructor Summary
Constructor and Description
Object()
Method Summary
Modifier
and Type
boolean
Class
int
void
void
String
toString()
void
Causes current thread to wait until another thread invokes the method or the
method for this object.
wait(long timeout)
void
Causes current thread to wait until either another thread invokes the method or
the method for this object, or a specified amount of time has elapsed.
wait(long timeout, int nanos)
void
Causes current thread to wait until another thread invokes the method or the
method for this object, or some other thread interrupts the current thread, or a
certain amount of real time has elapsed.
Constructor Detail
Object
public Object()
Method Detail
Constructor Detail
488
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
getClass
public final Class getClass()
Returns the runtime class of an object. That Class object is the object that is locked
by static synchronized methods of the represented class.
hashCode
public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of
hashtables such as those provided by java.util.Hashtable. The general contract of
hashCode is: Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application. If two objects are equal
according to the equals(Object) method, then calling the hashCode method on each
of the two objects must produce the same integer result. It is not required that if two
objects are unequal according to the equals(java.lang.Object) method, then calling
the hashCode method on each of the two objects must produce distinct integer
results. However, the programmer should be aware that producing distinct integer
results for unequal objects may improve the performance of hashtables. As much as
is reasonably practical, the hashCode method defined by class Object does return
distinct integers for distinct objects. (This is typically implemented by converting the
internal address of the object into an integer, but this implementation technique is not
required by the JavaTM programming language.)
notify
public final void notify()
Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation. A thread waits on an object's
monitor by calling one of the wait methods. The awakened thread will not be able to
proceed until the current thread relinquishes the lock on this object. The awakened
thread will compete in the usual manner with any other threads that might be actively
competing to synchronize on this object; for example, the awakened thread enjoys no
reliable privilege or disadvantage in being the next thread to lock this object. This
method should only be called by a thread that is the owner of this object's monitor. A
thread becomes the owner of the object's monitor in one of three ways: By executing
a synchronized instance method of that object. By executing the body of a
synchronized statement that synchronizes on the object. For objects of type Class, by
executing a synchronized static method of that class. Only one thread at a time can
own an object's monitor.
notifyAll
public final void notifyAll()
Method Detail
489
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
wait
public final void wait()
throws InterruptedException
Causes current thread to wait until another thread invokes the method or the method
for this object. In other word's this method behaves exactly as if it simply performs the
call wait(0). The current thread must own this object's monitor. The thread releases
ownership of this monitor and waits until another thread notifies threads waiting on
this object's monitor to wake up either through a call to the notify method or the
notifyAll method. The thread then waits until it can re-obtain ownership of the monitor
and resumes execution. This method should only be called by a thread that is the
owner of this object's monitor. See the notify method for a description of the ways in
which a thread can become the owner of a monitor.
Throws:
InterruptedException
wait
public final void wait(long timeout)
throws InterruptedException
Causes current thread to wait until either another thread invokes the method or the
method for this object, or a specified amount of time has elapsed. The current thread
must own this object's monitor. This method causes the current thread (call it T) to
place itself in the wait set for this object and then to relinquish any and all
synchronization claims on this object. Thread T becomes disabled for thread
scheduling purposes and lies dormant until one of four things happens: Some other
thread invokes the notify method for this object and thread T happens to be arbitrarily
chosen as the thread to be awakened. Some other thread invokes the notifyAll
method for this object. Some other thread interrupts thread T. The specified amount
of real time has elapsed, more or less. If timeout is zero, however, then real time is
not taken into consideration and the thread simply waits until notified. The thread T is
then removed from the wait set for this object and re-enabled for thread scheduling. It
then competes in the usual manner with other threads for the right to synchronize on
the object; once it has gained control of the object, all its synchronization claims on
the object are restored to the status quo ante - that is, to the situation as of the time
that the wait method was invoked. Thread T then returns from the invocation of the
wait method. Thus, on return from the wait method, the synchronization state of the
object and of thread T is exactly as it was when the wait method was invoked. If the
current thread is interrupted by another thread while it is waiting, then an
InterruptedException is thrown. This exception is not thrown until the lock status of
this object has been restored as described above. Note that the wait method, as it
places the current thread into the wait set for this object, unlocks only this object; any
other objects on which the current thread may be synchronized remain locked while
the thread waits. This method should only be called by a thread that is the owner of
Method Detail
490
wait
public final void wait(long timeout,
int nanos)
throws InterruptedException
Causes current thread to wait until another thread invokes the method or the method
for this object, or some other thread interrupts the current thread, or a certain amount
of real time has elapsed. This method is similar to the wait method of one argument,
but it allows finer control over the amount of time to wait for a notification before
giving up. The amount of real time, measured in nanoseconds, is given by:
1000000*timeout+nanos In all other respects, this method does the same thing as the
method wait(long) of one argument. In particular, wait(0, 0) means the same thing as
wait(0). The current thread must own this object's monitor. The thread releases
ownership of this monitor and waits until either of the following two conditions has
occurred: Another thread notifies threads waiting on this object's monitor to wake up
either through a call to the notify method or the notifyAll method. The timeout period,
specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.
The thread then waits until it can re-obtain ownership of the monitor and resumes
execution This method should only be called by a thread that is the owner of this
object's monitor. See the notify method for a description of the ways in which a thread
can become the owner of a monitor.
Throws:
InterruptedException
Method Detail
491
Class NumberFormatException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalArgumentException
java.lang.NumberFormatException
public class
extends IllegalArgumentException
Thrown to indicate that the application has attempted to convert a string to one of the numeric types,
but that the string does not have the appropriate format. Since: JDK1.0, CLDC 1.0 See
Also:Integer.toString()
Constructor Summary
Constructor and Description
NumberFormatException()
Method Summary
Constructor Detail
NumberFormatException
public NumberFormatException()
Class NumberFormatException
492
Class NullPointerException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.NullPointerException
public class
extends RuntimeException
Thrown when an application attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object. Accessing or modifying the field of a null object. Taking
the length of null as if it were an array. Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value. Applications should throw instances of this class to
indicate other illegal uses of the null object. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
NullPointerException()
Method Summary
Constructor Detail
NullPointerException
public NullPointerException()
Constructor Detail
493
Class NoSuchFieldError
java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.LinkageError
java.lang.IncompatibleClassChangeError
java.lang.NoSuchFieldError
public class
extends IncompatibleClassChangeError
Thrown when the virtual machine notices that a program tries to reference, on a class or object, a field
that does not exist.
Note that this can only occur when inconsistent class files are being loaded.
Constructor Summary
Constructor and Description
NoSuchFieldError()
Constructs a new NoSuchFieldError
NoSuchFieldError(String detailMessage)
Constructs a new NoSuchFieldError with the
message.
Method Summary
Constructor Detail
NoSuchFieldError
public NoSuchFieldError()
Constructs a new NoSuchFieldError with the current stack trace and the specified
detail message.
Parameters:
detailMessage - the detail message for this error.
Constructor Detail
494
Class NoClassDefFoundError
java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.NoClassDefFoundError
public class
extends Error
Thrown if the Java Virtual Machine tries to load in the definition of a class (as part of a normal method
call or as part of creating a new instance using the new expression) and no definition of the class
could be found. The searched-for class definition existed when the currently executing class was
compiled, but the definition can no longer be found. Since: JDK1.0, CLDC 1.1
Constructor Summary
Constructor and Description
NoClassDefFoundError()
Method Summary
Constructor Detail
NoClassDefFoundError
public NoClassDefFoundError()
Constructor Detail
495
Class NegativeArraySizeException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.NegativeArraySizeException
public class
extends RuntimeException
Thrown if an application tries to create an array with negative size. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
NegativeArraySizeException()
Method Summary
Constructor Detail
NegativeArraySizeException
public NegativeArraySizeException()
Constructor Detail
496
Class Math
java.lang.Object
java.lang.Math
The class Math contains methods for performing basic numeric operations. Since: JDK1.0, CLDC 1.0
Field Summary
Modifier and
Type
static double
The double value that is closer than any other to e, the base of the natural
logarithms.
PI
static double
The double value that is closer than any other to , the ratio of the
circumference of a circle to its diameter.
Constructor Summary
Constructor and Description
Math()
Method Summary
Modifier and
Type
static
double
static float
static int
static long
static
double
static
double
static
double
static
double
static float
static int
Constructor Detail
Returns the smallest (closest to negative infinity) double value that is not less
than the argument and is equal to a mathematical integer.
cos(double a)
Returns the largest (closest to positive infinity) double value that is not greater
than the argument and is equal to a mathematical integer.
max(double a, double b)
497
max(long a, long b)
static
double
static float
static int
static long
static long
static int
min(float a, float b)
static
double
sin(double a)
static
double
sqrt(double a)
static
double
tan(double a)
static
double
static
double
Field Detail
E
public static final double E
The double value that is closer than any other to e, the base of the natural logarithms.
Since: CLDC 1.1 See Also:Constant Field Values
See Also:
Constant Field Values
PI
public static final double PI
The double value that is closer than any other to , the ratio of the circumference of a
circle to its diameter. Since: CLDC 1.1 See Also:Constant Field Values
See Also:
Constant Field Values
Constructor Detail
Math
public Math()
Method Summary
498
Method Detail
abs
public static double abs(double a)
Returns the absolute value of a double value. If the argument is not negative, the
argument is returned. If the argument is negative, the negation of the argument is
returned. Special cases: If the argument is positive zero or negative zero, the result is
positive zero. If the argument is infinite, the result is positive infinity. If the argument is
NaN, the result is NaN. In other words, the result is equal to the value of the
expression: Double.longBitsToDouble((Double.doubleToLongBits(a)<>>1)
abs
public static float abs(float a)
Returns the absolute value of a float value. If the argument is not negative, the
argument is returned. If the argument is negative, the negation of the argument is
returned. Special cases: If the argument is positive zero or negative zero, the result is
positive zero. If the argument is infinite, the result is positive infinity. If the argument is
NaN, the result is NaN. In other words, the result is equal to the value of the
expression: Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))
abs
public static int abs(int a)
Returns the absolute value of an int value. If the argument is not negative, the
argument is returned. If the argument is negative, the negation of the argument is
returned. Note that if the argument is equal to the value of Integer.MIN_VALUE, the
most negative representable int value, the result is that same value, which is
negative.
abs
public static long abs(long a)
Returns the absolute value of a long value. If the argument is not negative, the
argument is returned. If the argument is negative, the negation of the argument is
returned. Note that if the argument is equal to the value of Long.MIN_VALUE, the
most negative representable long value, the result is that same value, which is
negative.
ceil
public static double ceil(double a)
Returns the smallest (closest to negative infinity) double value that is not less than
the argument and is equal to a mathematical integer. Special cases: If the argument
value is already equal to a mathematical integer, then the result is the same as the
argument. If the argument is NaN or an infinity or positive zero or negative zero, then
the result is the same as the argument. If the argument value is less than zero but
greater than -1.0, then the result is negative zero. Note that the value of Math.ceil(x)
is exactly the value of -Math.floor(-x).
cos
public static double cos(double a)
Returns the trigonometric cosine of an angle. Special case: If the argument is NaN or
an infinity, then the result is NaN.
floor
public static double floor(double a)
Returns the largest (closest to positive infinity) double value that is not greater than
the argument and is equal to a mathematical integer. Special cases: If the argument
value is already equal to a mathematical integer, then the result is the same as the
argument. If the argument is NaN or an infinity or positive zero or negative zero, then
Method Detail
499
Returns the greater of two double values. That is, the result is the argument closer to
positive infinity. If the arguments have the same value, the result is that same value.
If either value is NaN, then the result is NaN. Unlike the the numerical comparison
operators, this method considers negative zero to be strictly smaller than positive
zero. If one argument is positive zero and the other negative zero, the result is
positive zero.
max
public static float max(float a,
float b)
Returns the greater of two float values. That is, the result is the argument closer to
positive infinity. If the arguments have the same value, the result is that same value.
If either value is NaN, then the result is NaN. Unlike the the numerical comparison
operators, this method considers negative zero to be strictly smaller than positive
zero. If one argument is positive zero and the other negative zero, the result is
positive zero.
max
public static int max(int a,
int b)
Returns the greater of two int values. That is, the result is the argument closer to the
value of Integer.MAX_VALUE. If the arguments have the same value, the result is
that same value.
max
public static long max(long a,
long b)
Returns the greater of two long values. That is, the result is the argument closer to
the value of Long.MAX_VALUE. If the arguments have the same value, the result is
that same value.
min
public static double min(double a,
double b)
Returns the smaller of two double values. That is, the result is the value closer to
negative infinity. If the arguments have the same value, the result is that same value.
If either value is NaN, then the result is NaN. Unlike the the numerical comparison
operators, this method considers negative zero to be strictly smaller than positive
zero. If one argument is positive zero and the other is negative zero, the result is
negative zero.
min
public static float min(float a,
float b)
Returns the smaller of two float values. That is, the result is the value closer to
negative infinity. If the arguments have the same value, the result is that same value.
If either value is NaN, then the result is NaN. Unlike the the numerical comparison
operators, this method considers negative zero to be strictly smaller than positive
zero. If one argument is positive zero and the other is negative zero, the result is
negative zero.
min
public static int min(int a,
int b)
Returns the smaller of two int values. That is, the result the argument closer to the
value of Integer.MIN_VALUE. If the arguments have the same value, the result is that
Method Detail
500
Returns the smaller of two long values. That is, the result is the argument closer to
the value of Long.MIN_VALUE. If the arguments have the same value, the result is
that same value.
sin
public static double sin(double a)
Returns the trigonometric sine of an angle. Special cases: If the argument is NaN or
an infinity, then the result is NaN. If the argument is positive zero, then the result is
positive zero; if the argument is negative zero, then the result is negative zero.
sqrt
public static double sqrt(double a)
Returns the correctly rounded positive square root of a double value. Special cases:
If the argument is NaN or less than zero, then the result is NaN. If the argument is
positive infinity, then the result is positive infinity. If the argument is positive zero or
negative zero, then the result is the same as the argument.
tan
public static double tan(double a)
Returns the trigonometric tangent of an angle. Special cases: If the argument is NaN
or an infinity, then the result is NaN. If the argument is positive zero, then the result is
positive zero; if the argument is negative zero, then the result is negative zero
toDegrees
public static double toDegrees(double angrad)
Returns the result of rounding the argument to an integer. The result is equivalent to
(long) Math.floor(d+0.5).
Special cases:
round(+0.0) = +0.0
round(-0.0) = +0.0
round((anything > Long.MAX_VALUE) = Long.MAX_VALUE
round((anything < Long.MIN_VALUE) = Long.MIN_VALUE
round(+infintiy) = Long.MAX_VALUE
round(-infintiy) = Long.MIN_VALUE
round(NaN) = +0.0
Parameters:
d - the value to be rounded.
Returns:
the closest integer to the argument.
round
public static int round(float f)
Returns the result of rounding the argument to an integer. The result is equivalent to
(int) Math.floor(f+0.5).
Method Detail
501
Special cases:
round(+0.0) = +0.0
round(-0.0) = +0.0
round((anything > Integer.MAX_VALUE) = Integer.MAX_VALUE
round((anything < Integer.MIN_VALUE) = Integer.MIN_VALUE
round(+infintiy) = Integer.MAX_VALUE
round(-infintiy) = Integer.MIN_VALUE
round(NaN) = +0.0
Parameters:
f - the value to be rounded.
Returns:
the closest integer to the argument.
Method Detail
502
Class Long
java.lang.Object
java.lang.Long
The Long class wraps a value of the primitive type long in an object. An object of type Long contains a
single field whose type is long. In addition, this class provides several methods for converting a long
to a String and a String to a long, as well as other constants and methods useful when dealing with a
long. Since: JDK1.0, CLDC 1.0
Field Summary
Modifier and Type
static long
static long
Constructor Summary
Constructor and Description
Long(long value)
Constructs a newly allocated Long object that represents the primitive long argument.
Method Summary
Modifier and
Type
int
double
boolean
float
int
int
long
static long
static long
String
Class Long
Parses the string argument as a signed long in the radix specified by the
second argument.
toString()
503
toString(long i)
static String
static Long
Field Detail
MAX_VALUE
public static final long MAX_VALUE
Constructor Detail
Long
public Long(long value)
Constructs a newly allocated Long object that represents the primitive long argument.
value - the value to be represented by the Long object.
Method Detail
doubleValue
public double doubleValue()
Compares this object against the specified object. The result is true if and only if the
argument is not null and is a Long object that contains the same long value as this
object.
Overrides:
equals in class Object
floatValue
public float floatValue()
Method Summary
504
Computes a hashcode for this Long. The result is the exclusive OR of the two halves
of the primitive long value represented by this Long object. That is, the hashcode is
the value of the expression: (int)(this.longValue()^(this.longValue()>>>32))
Overrides:
hashCode in class Object
longValue
public long longValue()
Parses the string argument as a signed decimal long. The characters in the string
must all be decimal digits, except that the first character may be an ASCII minus sign
'-' ( u002d') to indicate a negative value. The resulting long value is returned, exactly
as if the argument and the radix 10 were given as arguments to the method that
takes two arguments. Note that neither L nor l is permitted to appear at the end of the
string as a type indicator, as would be permitted in Java programming language
source code.
Throws:
NumberFormatException
parseLong
public static long parseLong(String s,
int radix)
throws NumberFormatException
Parses the string argument as a signed long in the radix specified by the second
argument. The characters in the string must all be digits of the specified radix (as
determined by whether Character.digit returns a nonnegative value), except that the
first character may be an ASCII minus sign '-' (' u002d' to indicate a negative value.
The resulting long value is returned. Note that neither L nor l is permitted to appear at
the end of the string as a type indicator, as would be permitted in Java programming
language source code - except that either L or l may appear as a digit for a radix
greater than 22. An exception of type NumberFormatException is thrown if any of the
following situations occurs: The first argument is null or is a string of length zero. The
radix is either smaller than Character.MIN_RADIX or larger than
Character.MAX_RADIX. The first character of the string is not a digit of the specified
radix and is not a minus sign '-' ('u002d'). The first character of the string is a minus
sign and the string is of length 1. Any character of the string after the first is not a digit
of the specified radix. The integer value represented by the string cannot be
represented as a value of type long. Examples: parseLong("0", 10) returns 0L
parseLong("473", 10) returns 473L parseLong("-0", 10) returns 0L parseLong("-FF",
16) returns -255L parseLong("1100110", 2) returns 102L parseLong("99", 8) throws a
NumberFormatException parseLong("Hazelnut", 10) throws a
NumberFormatException parseLong("Hazelnut", 36) returns 1356099454469L
Throws:
NumberFormatException
Method Detail
505
Returns a String object representing this Long's value. The long integer value
represented by this Long object is converted to signed decimal representation and
returned as a string, exactly as if the long value were given as an argument to the
method that takes one argument.
Overrides:
toString in class Object
toString
public static String toString(long i)
Returns a new String object representing the specified integer. The argument is
converted to signed decimal representation and returned as a string, exactly as if the
argument and the radix 10 were given as arguments to the method that takes two
arguments.
toString
public static String toString(long i,
int radix)
Creates a string representation of the first argument in the radix specified by the
second argument. If the radix is smaller than Character.MIN_RADIX or larger than
Character.MAX_RADIX, then the radix 10 is used instead. If the first argument is
negative, the first element of the result is the ASCII minus sign '-' ('u002d'. If the first
argument is not negative, no sign character appears in the result. The remaining
characters of the result represent the magnitude of the first argument. If the
magnitude is zero, it is represented by a single zero character '0' ('u0030'); otherwise,
the first character of the representation of the magnitude will not be the zero
character. The following ASCII characters are used as digits:
0123456789abcdefghijklmnopqrstuvwxyz These are ' u0030' through ' u0039' and '
u0061' through ' u007a'. If the radix is N, then the first N of these characters are used
as radix-N digits in the order shown. Thus, the digits for hexadecimal (radix 16) are
0123456789abcdef.
valueOf
public static Long valueOf(long i)
Method Detail
506
Class LinkageError
java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.LinkageError
Direct Known Subclasses:
IncompatibleClassChangeError
public class
extends Error
LinkageError
is the superclass of all error classes that occur when loading and linking class files.
See Also:
Error
Constructor Summary
Constructor and Description
LinkageError()
message.
Method Summary
Constructor Detail
LinkageError
public LinkageError()
Constructs a new LinkageError with the current stack trace and the specified detail
message.
Parameters:
detailMessage - the detail message for this error.
Class LinkageError
507
Interface Iterable<T>
All Known Subinterfaces:
Collection<E>, Deque<E>, List<E>, NavigableSet<E>, Queue<E>, Set<E>, SortedSet<E>
All Known Implementing Classes:
AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, Ads,
ArrayDeque, ArrayList, BaseSpinner, BrowserComponent, Calendar, ComponentGroup,
Container, ContainerList, DateSpinner, DateTimeSpinner, Dialog, Element,
EmbeddedContainer, FileTree, FloatingHint, Form, GenericSpinner, HashSet,
HTMLComponent, HTMLElement, InfiniteContainer, InteractionDialog, LinkedHashSet,
LinkedList, MapComponent, MediaPlayer, MenuBar, MultiButton, NumericSpinner,
OnOffSwitch, PriorityQueue, Progress, SideMenuBar, SpanButton, SpanLabel, Stack,
SwipeableContainer, Table, Tabs, TimeSpinner, Toolbar, Tree, TreeSet, Vector,
VirtualKeyboard, WebBrowser
public interface
Objects of classes that implement this interface can be used within a foreach statement.
Since:
1.5
Method Summary
Modifier and Type
Iterator<T>
Method Detail
iterator
Iterator<T> iterator()
Constructor Detail
508
Class InterruptedException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.InterruptedException
public class
extends Exception
Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread
interrupts it. Since: JDK1.0, CLDC 1.0 See Also:Object.wait(), Object.wait(long), Object.wait(long, int),
Thread.sleep(long)
Constructor Summary
Constructor and Description
InterruptedException()
Method Summary
Constructor Detail
InterruptedException
public InterruptedException()
Method Detail
509
Class Integer
java.lang.Object
java.lang.Integer
The Integer class wraps a value of the primitive type int in an object. An object of type Integer
contains a single field whose type is int. In addition, this class provides several methods for converting
an int to a String and a String to an int, as well as other constants and methods useful when dealing
with an int. Since: JDK1.0, CLDC 1.0
Field Summary
Modifier and Type
static int
static int
Constructor Summary
Constructor and Description
Integer(int value)
Constructs a newly allocated Integer object that represents the primitive int argument.
Method Summary
Modifier and
Type
byte
double
boolean
float
int
int
long
static int
static int
short
Constructor Detail
Parses the string argument as a signed integer in the radix specified by the
second argument.
shortValue()
510
signum(int i)
Returns the value of the signum function for the specified integer.
toBinaryString(int i)
static String
static String
static String
String
static String
toString(int i)
static String
static Integer
static Integer
static Integer
Returns a new Integer object initialized to the value of the specified String.
valueOf(String s, int radix)
Returns a new Integer object initialized to the value of the specified String.
Field Detail
MAX_VALUE
public static final int MAX_VALUE
The largest value of type int. The constant value of this field is 2147483647. See
Also:Constant Field Values
See Also:
Constant Field Values
MIN_VALUE
public static final int MIN_VALUE
The smallest value of type int. The constant value of this field is -2147483648. See
Also:Constant Field Values
See Also:
Constant Field Values
Constructor Detail
Integer
public Integer(int value)
Constructs a newly allocated Integer object that represents the primitive int argument.
value - the value to be represented by the Integer.
Method Summary
511
Method Detail
byteValue
public byte byteValue()
Compares this object to the specified object. The result is true if and only if the
argument is not null and is an Integer object that contains the same int value as this
object.
Overrides:
equals in class Object
floatValue
public float floatValue()
Parses the string argument as a signed decimal integer. The characters in the string
must all be decimal digits, except that the first character may be an ASCII minus sign
'-' (' u002d') to indicate a negative value. The resulting integer value is returned,
exactly as if the argument and the radix 10 were given as arguments to the method.
Throws:
NumberFormatException
parseInt
public static int parseInt(String s,
int radix)
throws NumberFormatException
Parses the string argument as a signed integer in the radix specified by the second
argument. The characters in the string must all be digits of the specified radix (as
determined by whether returns a nonnegative value), except that the first character
may be an ASCII minus sign '-' (' u002d') to indicate a negative value. The resulting
integer value is returned. An exception of type NumberFormatException is thrown if
any of the following situations occurs: The first argument is null or is a string of length
Method Detail
512
shortValue
public short shortValue()
Returns a String object representing this Integer's value. The value is converted to
signed decimal representation and returned as a string, exactly as if the integer value
were given as an argument to the method.
Overrides:
toString in class Object
Method Detail
513
Returns a new String object representing the specified integer. The argument is
converted to signed decimal representation and returned as a string, exactly as if the
argument and radix 10 were given as arguments to the method.
toString
public static String toString(int i,
int radix)
Creates a string representation of the first argument in the radix specified by the
second argument. If the radix is smaller than Character.MIN_RADIX or larger than
Character.MAX_RADIX, then the radix 10 is used instead. If the first argument is
negative, the first element of the result is the ASCII minus character '-' ('u002d'). If the
first argument is not negative, no sign character appears in the result. The remaining
characters of the result represent the magnitude of the first argument. If the
magnitude is zero, it is represented by a single zero character '0' ('u0030'); otherwise,
the first character of the representation of the magnitude will not be the zero
character. The following ASCII characters are used as digits:
0123456789abcdefghijklmnopqrstuvwxyz These are ' u0030' through ' u0039' and '
u0061' through ' u007a'. If the radix is N, then the first N of these characters are used
as radix-N digits in the order shown. Thus, the digits for hexadecimal (radix 16) are
0123456789abcdef.
valueOf
public static Integer valueOf(String s)
throws NumberFormatException
Returns a new Integer object initialized to the value of the specified String. The
argument is interpreted as representing a signed decimal integer, exactly as if the
argument were given to the method. The result is an Integer object that represents
the integer value specified by the string. In other words, this method returns an
Integer object equal to the value of: new Integer(Integer.parseInt(s))
Throws:
NumberFormatException
valueOf
public static Integer valueOf(String s,
int radix)
throws NumberFormatException
Returns a new Integer object initialized to the value of the specified String. The first
argument is interpreted as representing a signed integer in the radix specified by the
second argument, exactly as if the arguments were given to the method. The result is
an Integer object that represents the integer value specified by the string. In other
words, this method returns an Integer object equal to the value of: new
Integer(Integer.parseInt(s, radix))
Throws:
NumberFormatException
valueOf
public static Integer valueOf(int i)
Returns the value of the signum function for the specified integer.
Parameters:
i - the integer value to check.
Returns:
Method Detail
514
Since:
1.5
Method Detail
515
Class InstantiationException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.InstantiationException
public class
extends Exception
Thrown when an application tries to create an instance of a class using the newInstance method in
class Class, but the specified class object cannot be instantiated because it is an interface or is an
abstract class. Since: JDK1.0, CLDC 1.0 See Also:Class.newInstance()
Constructor Summary
Constructor and Description
InstantiationException()
Method Summary
Constructor Detail
InstantiationException
public InstantiationException()
Class InstantiationException
516
Class IndexOutOfBoundsException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IndexOutOfBoundsException
Direct Known Subclasses:
ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException
public class
extends RuntimeException
Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of
range. Applications can subclass this class to indicate similar exceptions. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
IndexOutOfBoundsException()
Method Summary
Constructor Detail
IndexOutOfBoundsException
public IndexOutOfBoundsException()
Constructor Detail
517
Class IncompatibleClassChangeError
java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.LinkageError
java.lang.IncompatibleClassChangeError
Direct Known Subclasses:
NoSuchFieldError
public class
extends LinkageError
Error
Constructor Summary
Constructor and Description
IncompatibleClassChangeError()
Constructs a new IncompatibleClassChangeError
IncompatibleClassChangeError(String detailMessage)
Constructs a new IncompatibleClassChangeError with the
Method Summary
Constructor Detail
IncompatibleClassChangeError
public IncompatibleClassChangeError()
Constructs a new IncompatibleClassChangeError with the current stack trace and the
specified detail message.
Parameters:
detailMessage - the detail message for this error.
Constructor Detail
518
Class IllegalThreadStateException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalArgumentException
java.lang.IllegalThreadStateException
public class
extends IllegalArgumentException
Thrown to indicate that a thread is not in an appropriate state for the requested operation. See, for
example, the suspend and resume methods in class Thread. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
IllegalThreadStateException()
Method Summary
Constructor Detail
IllegalThreadStateException
public IllegalThreadStateException()
Constructor Detail
519
Class IllegalStateException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalStateException
public class
extends RuntimeException
Constructor Summary
Constructor and Description
IllegalStateException()
IllegalStateException(String s)
Method Summary
Constructor Detail
IllegalStateException
public IllegalStateException()
IllegalStateException
public IllegalStateException(String s)
Constructor Detail
520
Class IllegalMonitorStateException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalMonitorStateException
public class
extends RuntimeException
Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads
waiting on an object's monitor without owning the specified monitor. Since: JDK1.0, CLDC 1.0 See
Also:Object.notify(), Object.notifyAll(), Object.wait(), Object.wait(long), Object.wait(long, int)
Constructor Summary
Constructor and Description
IllegalMonitorStateException()
Method Summary
Constructor Detail
IllegalMonitorStateException
public IllegalMonitorStateException()
Constructor Detail
521
Class IllegalArgumentException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalArgumentException
Direct Known Subclasses:
IllegalThreadStateException, NumberFormatException
public class
extends RuntimeException
Thrown to indicate that a method has been passed an illegal or inappropriate argument. Since:
JDK1.0, CLDC 1.0 See Also:Thread.setPriority(int)
Constructor Summary
Constructor and Description
IllegalArgumentException()
Method Summary
Constructor Detail
IllegalArgumentException
public IllegalArgumentException()
Constructor Detail
522
Class IllegalAccessException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.IllegalAccessException
public class
extends Exception
Thrown when an application tries to load in a class, but the currently executing method does not have
access to the definition of the specified class, because the class is not public and in another package.
An instance of this class can also be thrown when an application tries to create an instance of a class
using the newInstance method in class Class, but the current method does not have access to the
appropriate zero-argument constructor. Since: JDK1.0, CLDC 1.0 See
Also:Class.forName(java.lang.String), Class.newInstance()
Constructor Summary
Constructor and Description
IllegalAccessException()
Method Summary
Constructor Detail
IllegalAccessException
public IllegalAccessException()
Constructor Detail
523
Class Float
java.lang.Object
java.lang.Float
The Float class wraps a value of primitive type float in an object. An object of type Float contains a
single field whose type is float. In addition, this class provides several methods for converting a float
to a String and a String to a float, as well as other constants and methods useful when dealing with a
float. Since: JDK1.0, CLDC 1.1
Field Summary
Modifier and Type
static float
static float
static float
static float
static float
Constructor Summary
Constructor and Description
Float(double value)
Constructs a newly allocated Floatobject that represents the argument converted to type
float.
Float(float value)
Constructs a newly allocated Float object that represents the primitive float argument.
Method Summary
Modifier and
Type
byte
double
boolean
static int
float
int
Constructor Detail
524
intBitsToFloat(int bits)
int
boolean
static boolean
boolean
isInfinite()
static boolean
long
static float
short
String
static String
static Float
static Float
toString(float f)
Field Detail
MAX_VALUE
public static final float MAX_VALUE
The largest positive value of type float. It is equal to the value returned by
Float.intBitsToFloat(0x7f7fffff). See Also:Constant Field Values
See Also:
Constant Field Values
MIN_VALUE
public static final float MIN_VALUE
The smallest positive value of type float. It is equal to the value returned by
Float.intBitsToFloat(0x1). See Also:Constant Field Values
See Also:
Constant Field Values
NaN
public static final float NaN
The Not-a-Number (NaN) value of type float. It is equal to the value returned by
Float.intBitsToFloat(0x7fc00000). See Also:Constant Field Values
See Also:
Constant Field Values
Method Summary
525
Constructor Detail
Float
public Float(double value)
Constructs a newly allocated Float object that represents the primitive float argument.
value - the value to be represented by the Float.
Method Detail
byteValue
public byte byteValue()
Compares this object against some other object. The result is true if and only if the
argument is not null and is a Float object that represents a float that has the identical
bit pattern to the bit pattern of the float represented by this object. For this purpose,
two float values are considered to be the same if and only if the method returns the
same int value when applied to each. Note that in most cases, for two instances of
class Float, f1 and f2, the value of f1.equals(f2) is true if and only if f1.floatValue() ==
f2.floatValue() also has the value true. However, there are two exceptions: If f1 and f2
both represent Float.NaN, then the equals method returns true, even though
Float.NaN==Float.NaN has the value false. If f1 represents +0.0f while f2 represents
-0.0f, or vice versa, the equal test has the value false, even though 0.0f==-0.0f has
the value true. This definition allows hashtables to operate properly.
Overrides:
equals in class Object
Field Detail
526
Returns a hashcode for this Float object. The result is the integer bit representation,
exactly as produced by the method , of the primitive float value represented by this
Float object.
Overrides:
hashCode in class Object
intBitsToFloat
public static float intBitsToFloat(int bits)
Method Detail
527
Returns true if the specified number is the special Not-a-Number (NaN) value.
longValue
public long longValue()
Returns a new float initialized to the value represented by the specified String.
Throws:
NumberFormatException
shortValue
public short shortValue()
Returns a String representation of this Float object. The primitive float value
represented by this object is converted to a String exactly as if by the method toString
of one argument.
Overrides:
toString in class Object
toString
public static String toString(float f)
Returns a String representation for the specified float value. The argument is
converted to a readable string format as follows. All characters and characters in
strings mentioned below are ASCII characters. If the argument is NaN, the result is
the string "NaN". Otherwise, the result is a string that represents the sign and
magnitude (absolute value) of the argument. If the sign is negative, the first character
of the result is '-' ('-'); if the sign is positive, no sign character appears in the result. As
for the magnitude m: If m is infinity, it is represented by the characters "Infinity"; thus,
positive infinity produces the result "Infinity" and negative infinity produces the result
"-Infinity". If m is zero, it is represented by the characters "0.0"; thus, negative zero
produces the result "-0.0" and positive zero produces the result "0.0". If m is greater
than or equal to 10-3 but less than 107, then it is represented as the integer part of m,
in decimal form with no leading zeroes, followed by '.' (.), followed by one or more
decimal digits representing the fractional part of m. If m is less than 10-3 or not less
than 107, then it is represented in so-called "computerized scientific notation." Let n
be the unique integer such that 10n =m 1; then let a be the mathematically exact
quotient of m and 10n so that 1 a<10. The magnitude is then represented as the
integer part of a, as a single decimal digit, followed by '.' (.), followed by decimal digits
representing the fractional part of a, followed by the letter 'E' (E), followed by a
representation of n as a decimal integer, as produced by the method of one
argument. How many digits must be printed for the fractional part of m or a? There
must be at least one digit to represent the fractional part, and beyond that as many,
but only as many, more digits as are needed to uniquely distinguish the argument
value from adjacent values of type float. That is, suppose that x is the exact
mathematical value represented by the decimal representation produced by this
method for a finite nonzero argument f. Then f must be the float value nearest to x;
or, if two float values are equally close to xthen f must be one of them and the least
significant bit of the significand of f must be 0.
Method Detail
528
Returns the floating point value represented by the specified String. The string s is
interpreted as the representation of a floating-point value and a Float object
representing that value is created and returned. If s is null, then a
NullPointerException is thrown. Leading and trailing whitespace characters in s are
ignored. The rest of s should constitute a FloatValue as described by the lexical
syntax rules: where , are as defined in Section 3.10.2 of the . If it does not have the
form of a , then a NumberFormatException is thrown. Otherwise, it is regarded as
representing an exact decimal value in the usual "computerized scientific notation";
this exact decimal value is then conceptually converted to an "infinitely precise"
binary value that is then rounded to type float by the usual round-to-nearest rule of
IEEE 754 floating-point arithmetic.
Throws:
NumberFormatException
valueOf
public static Float valueOf(float i)
Method Detail
529
Class Exception
java.lang.Object
java.lang.Throwable
java.lang.Exception
Direct Known Subclasses:
ClassNotFoundException, CloneNotSupportedException, CloudException,
IllegalAccessException, InstantiationException, InterruptedException, IOException,
ParseException, ParseException, RuntimeException, URISyntaxException
public class
extends Throwable
The class Exception and its subclasses are a form of Throwable that indicates conditions that a
reasonable application might want to catch. Since: JDK1.0, CLDC 1.0 See Also:Error
Constructor Summary
Constructor and Description
Exception()
Method Summary
Constructor Detail
Exception
public Exception()
Constructs an Exception with the specified detail message. s - the detail message.
Class Exception
530
Class Error
java.lang.Object
java.lang.Throwable
java.lang.Error
Direct Known Subclasses:
AnnotationFormatError, AssertionError, LinkageError, NoClassDefFoundError,
VirtualMachineError
public class
extends Throwable
An Error is a subclass of Throwable that indicates serious problems that a reasonable application
should not try to catch. Most such errors are abnormal conditions. A method is not required to declare
in its throws clause any subclasses of Error that might be thrown during the execution of the method
but not caught, since these errors are abnormal conditions that should never occur. Since: JDK1.0,
CLDC 1.0
Constructor Summary
Constructor and Description
Error()
Method Summary
Constructor Detail
Error
public Error()
Constructs an Error with the specified detail message. s - the detail message.
Constructor Detail
531
java.lang.Enum<E>
All Implemented Interfaces:
Comparable<E>
public class
extends Object
implements Comparable<E>
Constructor Summary
Modifier
Method Summary
Modifier and Type
protected Object
int
boolean
equals(Object other)
Class<E>
getDeclaringClass()
protected static
<T> T[]
getEnumValues(Class<T> class_)
hashCode()
int
String
name()
int
ordinal()
String
Constructor Detail
Constructor Detail
532
Method Detail
clone
protected Object clone()
setEnumValues
protected static final void setEnumValues(Object[] values,
Class c)
getEnumValues
protected static final <T> T[] getEnumValues(Class<T> class_)
valueOf
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
String name)
equals
public final boolean equals(Object other)
Constructor Detail
533
ordinal
public final int ordinal()
getDeclaringClass
public final Class<E> getDeclaringClass()
Method Detail
534
Class Double
java.lang.Object
java.lang.Double
The Double class wraps a value of the primitive type double in an object. An object of type Double
contains a single field whose type is double. In addition, this class provides several methods for
converting a double to a String and a String to a double, as well as other constants and methods
useful when dealing with a double. Since: JDK1.0, CLDC 1.1
Field Summary
Modifier and Type
static double
static double
static double
static double
static double
Constructor Summary
Constructor and Description
Double(double value)
Constructs a newly allocated Double object that represents the primitive double argument.
Method Summary
Modifier and
Type
byte
static long
double
boolean
float
int
int
Class Double
535
isInfinite()
Returns true if this Double value is the special Not-a-Number (NaN) value.
static
boolean
isNaN(double v)
static
double
longBitsToDouble(long bits)
Returns true if the specified number is the special Not-a-Number (NaN) value.
Returns the double-float corresponding to a given bit representation.
longValue()
long
static
double
short
String
static
String
toString(double d)
static
Double
valueOf(double i)
static
Double
Field Detail
MAX_VALUE
public static final double MAX_VALUE
The largest positive finite value of type double. It is equal to the value returned by
Double.longBitsToDouble(0x7fefffffffffffffL) See Also:Constant Field Values
See Also:
Constant Field Values
MIN_VALUE
public static final double MIN_VALUE
The smallest positive value of type double. It is equal to the value returned by
Double.longBitsToDouble(0x1L).
See Also:
Constant Field Values
NaN
public static final double NaN
Method Summary
536
Constructor Detail
Double
public Double(double value)
Constructs a newly allocated Double object that represents the primitive double
argument. value - the value to be represented by the Double.
Method Detail
byteValue
public byte byteValue()
Compares this object against the specified object. The result is true if and only if the
argument is not null and is a Double object that represents a double that has the
identical bit pattern to the bit pattern of the double represented by this object. For this
purpose, two double values are considered to be the same if and only if the method
returns the same long value when applied to each. Note that in most cases, for two
instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if
d1.doubleValue() == d2.doubleValue() also has the value true. However, there are
Field Detail
537
Returns a hashcode for this Double object. The result is the exclusive OR of the two
halves of the long integer bit representation, exactly as produced by the method , of
the primitive double value represented by this Double object. That is, the hashcode is
the value of the expression: (int)(v^(v>>>32)) where v is defined by: long v =
Double.doubleToLongBits(this.doubleValue());
Overrides:
hashCode in class Object
intValue
public int intValue()
Returns true if this Double value is the special Not-a-Number (NaN) value.
isNaN
public static boolean isNaN(double v)
Returns true if the specified number is the special Not-a-Number (NaN) value.
longBitsToDouble
public static double longBitsToDouble(long bits)
Method Detail
538
Returns a new double initialized to the value represented by the specified String, as
performed by the valueOf method of class Double.
Throws:
NumberFormatException
shortValue
public short shortValue()
Returns a String representation of this Double object. The primitive double value
represented by this object is converted to a string exactly as if by the method toString
of one argument.
Overrides:
toString in class Object
toString
public static String toString(double d)
Returns a new Double object initialized to the value represented by the specified
string. The string s is interpreted as the representation of a floating-point value and a
Double object representing that value is created and returned. If s is null, then a
NullPointerException is thrown. Leading and trailing whitespace characters in s are
ignored. The rest of s should constitute a FloatValue as described by the lexical rule:
Method Detail
539
valueOf
public static Double valueOf(double i)
Method Detail
540
@Documented
@Retention(value=RUNTIME)
public @interface
541
Interface Comparable<T>
All Known Implementing Classes:
ActionEvent.Type, BarChart.Type, DialRenderer.Type, ElementType, Enum, PointStyle,
RetentionPolicy, Validator.HighlightMode, XYMultipleSeriesRenderer.Orientation,
XYSeriesRenderer.FillOutsideLine.Type
public interface
This interface should be implemented by all classes that wish to define a natural order of their
instances. Collections.sort(java.util.List<T>) and java.util.Arrays#sort can then be used to
automatically sort lists of classes that implement this interface.
The order rule must be both transitive (if x.compareTo(y) < 0 and y.compareTo(z) < 0, then
x.compareTo(z) < 0 must hold) and invertible (the sign of the result of x.compareTo(y) must be equal
to the negation of the sign of the result of y.compareTo(x) for all combinations of x and y).
In addition, it is recommended (but not required) that if and only if the result of x.compareTo(y) is
zero, then the result of x.equals(y) should be true.
Method Summary
Modifier and
Type
int
Method Detail
compareTo
int compareTo(T another)
Compares this object to the specified object to determine their relative order.
Parameters:
another - the object to compare to this instance.
Returns:
a negative integer if this instance is less than another; a positive integer if
this instance is greater than another; 0 if this instance has the same order as
another.
Throws:
ClassCastException - if another cannot be converted into something
comparable to this instance.
Interface Comparable<T>
542
Interface Cloneable
public interface
This (empty) interface must be implemented by all classes that wish to support cloning. The
implementation of clone() in Object checks if the object being cloned implements this interface and
throws CloneNotSupportedException if it does not.
See Also:
Object#clone, CloneNotSupportedException
Method Detail
543
Class CloneNotSupportedException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.CloneNotSupportedException
public class
extends Exception
Thrown when a program attempts to clone an object which does not support the Cloneable interface.
See Also:
Cloneable
Constructor Summary
Constructor and Description
CloneNotSupportedException()
Constructs a new CloneNotSupportedException
CloneNotSupportedException(String detailMessage)
Constructs a new CloneNotSupportedException with the
Method Summary
Constructor Detail
CloneNotSupportedException
public CloneNotSupportedException()
Constructs a new CloneNotSupportedException with the current stack trace and the
specified detail message.
Parameters:
detailMessage - the detail message for this exception.
Interface Cloneable
544
Class ClassNotFoundException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.ClassNotFoundException
public class
extends Exception
Thrown when an application tries to load in a class through its string name using the forName method
in class Class but no definition for the class with the specified name could be found. Since: JDK1.0,
CLDC 1.0 See Also:Class.forName(java.lang.String)
Constructor Summary
Constructor and Description
ClassNotFoundException()
Method Summary
Constructor Detail
ClassNotFoundException
public ClassNotFoundException()
Constructor Detail
545
Class ClassCastException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.ClassCastException
public class
extends RuntimeException
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an
instance. For example, the following code generates a ClassCastException: Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
ClassCastException()
Method Summary
Constructor Detail
ClassCastException
public ClassCastException()
Constructor Detail
546
Class Class<T>
java.lang.Object
java.lang.Class<T>
Instances of the class Class represent classes and interfaces in a running Java application. Every
array also belongs to a class that is reflected as a Class object that is shared by all arrays with the
same element type and number of dimensions. Class has no public constructor. Instead Class objects
are constructed automatically by the Java Virtual Machine as classes are loaded. The following
example uses a Class object to print the class name of an object: Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
Class()
Method Summary
Modifier and
Type
Class
Object
boolean
static Class
<T extends
Annotation>
T
Annotation[]
Deprecated.
don't use this method for anything important since class names are
obfuscated on the device!
getAnnotation(Class annotationType)
String
Annotation[]
Deprecated.
don't use this method for anything important since class names are
obfuscated on the device!
getDeclaredAnnotations()
String
Deprecated.
don't use this method for anything important since class names are
obfuscated on the device!
getSimpleName()
String
Deprecated.
don't use this method for anything important since class names are
obfuscated on the device!
boolean
isAnnotation()
boolean
isAnnotationPresent(Class annotationType)
Constructor Detail
547
boolean
boolean
boolean
isEnum()
boolean
boolean
isInterface()
boolean
boolean
Object
String
Constructor Detail
Class
public Class()
Method Detail
forName
public static Class forName(String className)
throws ClassNotFoundException
Deprecated. don't use this method for anything important since class names are
obfuscated on the device!
Returns the Class object associated with the class with the given string name. Given
the fully-qualified name for a class or interface, this method attempts to locate, load
and link the class. For example, the following code fragment returns the runtime
Class descriptor for the class named java.lang.Thread: Classt=
Class.forName("java.lang.Thread")
Throws:
ClassNotFoundException
getName
public String getName()
Deprecated. don't use this method for anything important since class names are
obfuscated on the device!
Returns the fully-qualified name of the entity (class, interface, array class, primitive
type, or void) represented by this Class object, as a String. If this Class object
represents a class of arrays, then the internal form of the name consists of the name
of the element type in Java signature format, preceded by one or more "[" characters
Method Summary
548
Determines if the class or interface represented by this Class object is either the
same as, or is a superclass or superinterface of, the class or interface represented by
the specified Class parameter. It returns true if so; otherwise it returns false. If this
Class object represents a primitive type, this method returns true if the specified
Class parameter is exactly this Class object; otherwise it returns false. Specifically,
this method tests whether the type represented by the specified Class parameter can
be converted to the type represented by this Class object via an identity conversion
or via a widening reference conversion. See The Java Language Specification,
sections 5.1.1 and 5.1.4 , for details.
isInstance
public boolean isInstance(Object obj)
toString
public String toString()
Converts the object to a string. The string representation is the string "class" or
"interface", followed by a space, and then by the fully qualified name of the class in
the format returned by getName. If this Class object represents a primitive type, this
method returns the name of the primitive type. If this Class object represents void this
method returns "void".
Overrides:
toString in class Object
Method Detail
549
getAnnotation
public <T extends Annotation> T getAnnotation(Class annotationType)
Returns this element's annotation for the specified type if such an annotation is
present, else null.
getAnnotations
public Annotation[] getAnnotations()
Returns true if an annotation for the specified type is present on this element, else
false.
asSubclass
public Class asSubclass(Class superclass)
Method Detail
550
Deprecated. don't use this method for anything important since class names are
obfuscated on the device!
isSynthetic
public boolean isSynthetic()
Deprecated. don't use this method for anything important since class names are
obfuscated on the device!
desiredAssertionStatus
public boolean desiredAssertionStatus()
Method Detail
551
Class Character
java.lang.Object
java.lang.Character
The Character class wraps a value of the primitive type char in an object. An object of type Character
contains a single field whose type is char. In addition, this class provides several methods for
determining the type of a character and converting characters from uppercase to lowercase and vice
versa. Character information is based on the Unicode Standard, version 3.0. However, in order to
reduce footprint, by default the character property and case conversion operations in CLDC are
available only for the ISO Latin-1 range of characters. Other Unicode character blocks can be
supported as necessary. Since: JDK1.0, CLDC 1.0
Field Summary
Modifier and
Type
static int
static char
static char
static int
static char
static char
static int
The constant value of this field is the largest value of type char.
MIN_CODE_POINT
static char
static char
static int
static int
static char
static char
The constant value of this field is the smallest value of type char.
SIZE
static int
Class Character
552
Summary
Constructor and Description
Character(char value)
Constructs a Character object and initializes it so that it represents the primitive value
argument.
Method Summary
Modifier
and Type
static int
point.
char
static int
charValue()
static int
static int
static int
static int
static int
Returns the Unicode code point that proceeds the index in the char[].
codePointBefore(char[] seq, int index, int start)
Returns the Unicode code point that proceeds the index
isn't less than start.
Returns the Unicode code point that proceeds the index in the CharSequence.
codePointCount(char[] seq, int offset, int count)
static int
Counts the number of Unicode code points in the subsequence of the char[],
as delineated by the offset and count.
codePointCount(CharSequence seq, int beginIndex, int endIndex)
static int
static int
boolean
int
static
boolean
static
boolean
static
boolean
static
boolean
static
boolean
isSupplementaryCodePoint(int codePoint)
A test for determining if the codePoint is within
static
boolean
Constructor Summary
range.
valid surrogate pair.
553
isUpperCase(char ch)
static
boolean
isValidCodePoint(int codePoint)
A test for determining if the codePoint
static
boolean
isWhitespace(char c)
See isWhitespace(int).
static
boolean
isWhitespace(int codePoint)
static int
static int
static char
reverseBytes(char c)
static
char[]
static int
static int
static char
String
static char
static
Character
valueOf(char i)
Field Detail
MAX_RADIX
public static final int MAX_RADIX
The maximum radix available for conversion to and from Strings. See
Also:Integer.toString(int, int), Integer.valueOf(java.lang.String), Constant Field Values
See Also:
Constant Field Values
MAX_VALUE
public static final char MAX_VALUE
The constant value of this field is the largest value of type char. Since: JDK1.0.2 See
Also:Constant Field Values
See Also:
Constant Field Values
Method Summary
554
The minimum radix available for conversion to and from Strings. See
Also:Integer.toString(int, int), Integer.valueOf(java.lang.String), Constant Field Values
See Also:
Constant Field Values
MIN_VALUE
public static final char MIN_VALUE
The constant value of this field is the smallest value of type char. Since: JDK1.0.2
See Also:Constant Field Values
See Also:
Constant Field Values
MIN_HIGH_SURROGATE
public static final char MIN_HIGH_SURROGATE
Minimum value of a high surrogate or leading surrogate unit in UTF-16 encoding '?'.
Since:
1.5
See Also:
Constant Field Values
MAX_HIGH_SURROGATE
public static final char MAX_HIGH_SURROGATE
Maximum value of a high surrogate or leading surrogate unit in UTF-16 encoding '?'.
Since:
1.5
See Also:
Constant Field Values
MIN_LOW_SURROGATE
public static final char MIN_LOW_SURROGATE
Minimum value of a low surrogate or trailing surrogate unit in UTF-16 encoding - '?'.
Since:
1.5
See Also:
Constant Field Values
MAX_LOW_SURROGATE
public static final char MAX_LOW_SURROGATE
Maximum value of a low surrogate or trailing surrogate unit in UTF-16 encoding - '?'.
Since:
1.5
See Also:
Constant Field Values
MIN_SURROGATE
public static final char MIN_SURROGATE
Field Detail
555
Constant for the number of bits to represent a char in two's compliment form.
Since:
1.5
See Also:
Constant Field Values
Constructor Detail
Character
public Character(char value)
Constructs a Character object and initializes it so that it represents the primitive value
argument. value - value for the new Character object.
Method Detail
Field Detail
556
Compares this object against the specified object. The result is true if and only if the
argument is not null and is a Character object that represents the same char value as
this object.
Overrides:
equals in class Object
hashCode
public int hashCode()
The given character is mapped to its lowercase equivalent; if the character has no
lowercase equivalent, the character itself is returned. Note that by default CLDC only
supports the ISO Latin-1 range of characters.
toString
public String toString()
Returns a String object representing this character's value. Converts this Character
object to a string. The result is a string whose length is 1. The string's sole
Method Detail
557
A test for determining if the codePoint is within the supplementary code point range.
Parameters:
codePoint - The code point to test.
Returns:
A boolean value.
Since:
1.5
isHighSurrogate
public static boolean isHighSurrogate(char ch)
A test for determining if the char is a high surrogate/leading surrogate unit that's used
for representing supplementary characters in UTF-16 encoding.
Parameters:
ch - The char unit to test.
Returns:
A boolean value.
Since:
1.5
See Also:
isLowSurrogate(char)
isLowSurrogate
public static boolean isLowSurrogate(char ch)
A test for determining if the char is a high surrogate/leading surrogate unit that's used
for representing supplementary characters in UTF-16 encoding.
Parameters:
ch - The char unit to test.
Returns:
A boolean value.
Since:
1.5
See Also:
isHighSurrogate(char)
Method Detail
558
Returns:
A boolean value.
Since:
1.5
See Also:
isHighSurrogate(char), isLowSurrogate(char)
charCount
public static int charCount(int codePoint)
Calculates the number of char values required to represent the Unicode code point.
This method only tests if the codePoint is greater than or equal to 0x10000, in which
case 2 is returned, otherwise 1. To test if the code point is valid, use the
isValidCodePoint(int) method.
Parameters:
codePoint - The code point to test.
Returns:
An int value of 2 or 1.
Since:
1.5
See Also:
isValidCodePoint(int), isSupplementaryCodePoint(int)
toCodePoint
public static int toCodePoint(char high,
char low)
Converts a surrogate pair into a Unicode code point. This method assume that the
pair are valid surrogates. If the pair are NOT valid surrogates, then the result is
indeterminate. The isSurrogatePair(char, char) method should be used prior to
this method to validate the pair.
Parameters:
high - The high surrogate unit.
low - The low surrogate unit.
Returns:
The decoded code point.
Since:
1.5
See Also:
isSurrogatePair(char, char)
codePointAt
public static int codePointAt(CharSequence seq,
int index)
Returns the code point at the index in the CharSequence. If char unit at the index is a
high-surrogate unit, the next index is less than the length of the sequence and the
char unit at the next index is a low surrogate unit, then the code point represented by
the pair is returned; otherwise the char unit at the index is returned.
Parameters:
seq - The sequence of char units.
index - The index into the seq to retrieve and convert.
Returns:
The Unicode code point.
Method Detail
559
Since:
1.5
codePointAt
public static int codePointAt(char[] seq,
int index)
Returns the code point at the index in the char[]. If char unit at the index is a
high-surrogate unit, the next index is less than the length of the sequence and the
char unit at the next index is a low surrogate unit, then the code point represented by
the pair is returned; otherwise the char unit at the index is returned.
Parameters:
seq - The sequence of char units.
index - The index into the seq to retrieve and convert.
Returns:
The Unicode code point.
Throws:
NullPointerException - if seq is null.
IndexOutOfBoundsException - if the index is negative or greater than or equal
to seq.length().
Since:
1.5
codePointAt
public static int codePointAt(char[] seq,
int index,
int limit)
Returns the code point at the index in the char[] that's within the limit. If char unit at
the index is a high-surrogate unit, the next index is less than the limit and the char
unit at the next index is a low surrogate unit, then the code point represented by the
pair is returned; otherwise the char unit at the index is returned.
Parameters:
seq - The sequence of char units.
index - The index into the seq to retrieve and convert.
limit - The exclusive index into the seq that marks the end of the units that
can be used.
Returns:
The Unicode code point.
Throws:
NullPointerException - if seq is null.
IndexOutOfBoundsException - if the index is negative, greater than or equal
to limit, limit is negative or limit is greater than the length of seq.
Since:
1.5
codePointBefore
public static int codePointBefore(CharSequence seq,
int index)
Returns the Unicode code point that proceeds the index in the CharSequence. If the
char unit at index - 1 is within the low surrogate range, the value index - 2 isn't
negative and the char unit at index - 2 is within the high surrogate range, then the
supplementary code point made up of the surrogate pair is returned; otherwise, the
char value at index - 1 is returned.
Parameters:
seq - The CharSequence to search.
index - The index into the seq.
Returns:
A Unicode code point.
Method Detail
560
Since:
1.5
codePointBefore
public static int codePointBefore(char[] seq,
int index)
Returns the Unicode code point that proceeds the index in the char[]. If the char unit
at index - 1 is within the low surrogate range, the value index - 2 isn't negative and
the char unit at index - 2 is within the high surrogate range, then the supplementary
code point made up of the surrogate pair is returned; otherwise, the char value at
index - 1 is returned.
Parameters:
seq - The char[] to search.
index - The index into the seq.
Returns:
A Unicode code point.
Throws:
NullPointerException - if seq is null.
IndexOutOfBoundsException - if index is less than 1 or greater than
seq.length.
Since:
1.5
codePointBefore
public static int codePointBefore(char[] seq,
int index,
int start)
Returns the Unicode code point that proceeds the index in the char[] and isn't less
than start. If the char unit at index - 1 is within the low surrogate range, the value
index - 2 isn't less than start and the char unit at index - 2 is within the high
surrogate range, then the supplementary code point made up of the surrogate pair is
returned; otherwise, the char value at index - 1 is returned.
Parameters:
seq - The char[] to search.
index - The index into the seq.
Returns:
A Unicode code point.
Throws:
NullPointerException - if seq is null.
IndexOutOfBoundsException - if index is less than or equal to start, index is
greater than seq.length, start is not negative and start is greater than
seq.length.
Since:
1.5
toChars
public static int toChars(int codePoint,
char[] dst,
int dstIndex)
Converts the Unicode code point, codePoint, into a UTF-16 encoded sequence and
copies the value(s) into the char[] dst, starting at the index dstIndex.
Parameters:
codePoint - The Unicode code point to encode.
dst - The char[] to copy the encoded value into.
dstIndex - The index to start copying into dst.
Returns:
The number of char value units copied into dst.
Method Detail
561
Since:
1.5
toChars
public static char[] toChars(int codePoint)
Converts the Unicode code point, codePoint, into a UTF-16 encoded sequence that
is returned as a char[].
Parameters:
codePoint - The Unicode code point to encode.
Returns:
The UTF-16 encoded char sequence; if code point is a supplementary code
point, then a 2 char array is returned, otherwise a 1 char array is returned.
Throws:
IllegalArgumentException - if codePoint is not a valid Unicode code point.
Since:
1.5
codePointCount
public static int codePointCount(CharSequence seq,
int beginIndex,
int endIndex)
Counts the number of Unicode code points in the subsequence of the CharSequence,
as delineated by the beginIndex and endIndex. Any surrogate values with missing
pair values will be counted as 1 code point.
Parameters:
seq - The CharSequence to look through.
beginIndex - The inclusive index to begin counting at.
endIndex - The exclusive index to stop counting at.
Returns:
The number of Unicode code points.
Throws:
NullPointerException - if seq is null.
IndexOutOfBoundsException - if beginIndex is negative, greater than
seq.length() or greater than endIndex.
Since:
1.5
codePointCount
public static int codePointCount(char[] seq,
int offset,
int count)
Counts the number of Unicode code points in the subsequence of the char[], as
delineated by the offset and count. Any surrogate values with missing pair values
will be counted as 1 code point.
Parameters:
seq - The char[] to look through.
offset - The inclusive index to begin counting at.
count - The number of char values to look through in seq.
Returns:
The number of Unicode code points.
Throws:
NullPointerException - if seq is null.
IndexOutOfBoundsException - if offset or count is negative or if endIndex is
greater than seq.length.
Since:
Method Detail
562
Determines the index into the CharSequence that is offset (measured in code points
and specified by codePointOffset), from the index argument.
Parameters:
seq - The CharSequence to find the index within.
index - The index to begin from, within the CharSequence.
codePointOffset - The number of code points to look back or forwards; may
be a negative or positive value.
Returns:
The calculated index that is codePointOffset code points from index.
Throws:
NullPointerException - if seq is null.
IndexOutOfBoundsException - if index is negative, greater than seq.length(),
there aren't enough values in seq after index or before index if
codePointOffset is negative.
Since:
1.5
offsetByCodePoints
public static int offsetByCodePoints(char[] seq,
int start,
int count,
int index,
int codePointOffset)
Determines the index into the char[] that is offset (measured in code points and
specified by codePointOffset), from the index argument and is within the
subsequence as delineated by start and count.
Parameters:
seq - The char[] to find the index within.
index - The index to begin from, within the char[].
codePointOffset - The number of code points to look back or forwards; may
be a negative or positive value.
start - The inclusive index that marks the beginning of the subsequence.
count - The number of char values to include within the subsequence.
Returns:
The calculated index that is codePointOffset code points from index.
Throws:
NullPointerException - if seq is null.
IndexOutOfBoundsException - if start or count is negative, start + count
greater than seq.length, index is less than start, index is greater than start
+ count or there aren't enough values in seq after index or before index if
codePointOffset is negative.
Since:
1.5
reverseBytes
public static char reverseBytes(char c)
Method Detail
563
See isWhitespace(int).
isWhitespace
public static boolean isWhitespace(int codePoint)
Returns true if the given code point is a Unicode whitespace character. The exact set
of characters considered as whitespace varies with Unicode version. Note that
non-breaking spaces are not considered whitespace. Note also that line separators
are considered whitespace; see #isSpaceChar for an alternative.
Method Detail
564
Interface CharSequence
public interface
This interface represents an ordered set of characters and defines the methods to probe them.
Method Summary
Modifier and
Type
Returns the character at the specified index, with the first character
having index zero.
char
length()
int
CharSequence
Returns a string with the same characters in the same order as in this
sequence.
String
Method Detail
length
int length()
Returns the character at the specified index, with the first character having index
zero.
Parameters:
index - the index of the character to return.
Returns:
the requested character.
Throws:
IndexOutOfBoundsException - if index < 0 or index is greater than the length
of this sequence.
subSequence
CharSequence subSequence(int start,
int end)
Returns a CharSequence from the start index (inclusive) to the end index (exclusive)
of this sequence.
Parameters:
start - the start offset of the sub-sequence. It is inclusive, that is, the index of
the first character that is included in the sub-sequence.
end - the end offset of the sub-sequence. It is exclusive, that is, the index of
the first character after those that are included in the sub-sequence
Interface CharSequence
565
Returns a string with the same characters in the same order as in this sequence.
Overrides:
toString in class Object
Returns:
a string based on this sequence.
Method Detail
566
Class Byte
java.lang.Object
java.lang.Byte
The Byte class is the standard wrapper for byte values. Since: JDK1.1, CLDC 1.0
Field Summary
Modifier and Type
static byte
static byte
Constructor Summary
Constructor and Description
Byte(byte value)
Method Summary
Modifier and
Type
byte
boolean
equals(Object obj)
int
static byte
static byte
String
static Byte
valueOf(byte i)
Class Byte
567
Detail
MAX_VALUE
public static final byte MAX_VALUE
The maximum value a Byte can have. See Also:Constant Field Values
See Also:
Constant Field Values
MIN_VALUE
public static final byte MIN_VALUE
The minimum value a Byte can have. See Also:Constant Field Values
See Also:
Constant Field Values
Constructor Detail
Byte
public Byte(byte value)
Constructs a Byte object initialized to the specified byte value. value - the initial value
of the Byte
Method Detail
byteValue
public byte byteValue()
Assuming the specified String represents a byte, returns that byte's value. Throws an
exception if the String cannot be parsed as a byte. The radix is assumed to be 10.
Throws:
NumberFormatException
parseByte
public static byte parseByte(String s,
int radix)
throws NumberFormatException
Assuming the specified String represents a byte, returns that byte's value. Throws an
exception if the String cannot be parsed as a byte.
Field Detail
568
Throws:
NumberFormatException
toString
public String toString()
Method Detail
569
Class Boolean
java.lang.Object
java.lang.Boolean
The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean
contains a single field whose type is boolean. Since: JDK1.0, CLDC 1.0
Field Summary
Modifier and Type
static Boolean
static Boolean
Constructor Summary
Constructor and Description
Boolean(boolean value)
Method Summary
Modifier and
Type
boolean
int
boolean
Returns true if and only if the argument is not null and is a Boolean object
that represents the same boolean value as this object.
hashCode()
int
static
boolean
parseBoolean(String s)
toString()
String
static
Boolean
static
Boolean
valueOf(boolean b)
Class Boolean
570
Detail
FALSE
public static final Boolean FALSE
Constructor Detail
Boolean
public Boolean(boolean value)
Allocates a Boolean object representing the value argument. value - the value of the
Boolean.
Method Detail
booleanValue
public boolean booleanValue()
Returns true if and only if the argument is not null and is a Boolean object that
represents the same boolean value as this object.
Overrides:
equals in class Object
hashCode
public int hashCode()
Returns a String object representing this Boolean's value. If this object represents the
value true, a string equal to "true" is returned. Otherwise, a string equal to "false" is
returned.
Overrides:
toString in class Object
valueOf
public static Boolean valueOf(boolean b)
Field Detail
571
valueOf
public static Boolean valueOf(String b)
parseBoolean
public static boolean parseBoolean(String s)
compareTo
public int compareTo(Boolean b2)
Method Detail
572
Interface AutoCloseable
All Known Subinterfaces:
DataInput, DataOutput
All Known Implementing Classes:
BufferedInputStream, BufferedOutputStream, ByteArrayInputStream,
ByteArrayOutputStream, CharArrayReader, DataInputStream, DataOutputStream,
DeflaterOutputStream, FilterInputStream, FilterOutputStream, GZIPInputStream,
GZIPOutputStream, InflaterInputStream, InputStream, InputStreamReader, OutputStream,
OutputStreamWriter, PrintStream, Reader, StringReader, TarInputStream, TarOutputStream,
Writer
public interface
Method Summary
Modifier and Type Method and Description
void
close()
Method Detail
close
void close()
throws Exception
Throws:
Exception
Interface AutoCloseable
573
Class AssertionError
java.lang.Object
java.lang.Throwable
java.lang.Error
java.lang.AssertionError
public class
extends Error
Constructor Summary
Constructor and Description
AssertionError()
AssertionError(boolean detailMessage)
AssertionError(char detailMessage)
AssertionError(double detailMessage)
AssertionError(float detailMessage)
AssertionError(int detailMessage)
AssertionError(long detailMessage)
AssertionError(Object detailMessage)
AssertionError(String detailMessage)
AssertionError(String message, Throwable cause)
Method Summary
Constructor Detail
AssertionError
public AssertionError()
AssertionError
public AssertionError(String detailMessage)
AssertionError
public AssertionError(Object detailMessage)
AssertionError
public AssertionError(boolean detailMessage)
Method Detail
574
AssertionError
public AssertionError(int detailMessage)
AssertionError
public AssertionError(long detailMessage)
AssertionError
public AssertionError(float detailMessage)
AssertionError
public AssertionError(double detailMessage)
AssertionError
public AssertionError(String message,
Throwable cause)
Constructor Detail
575
Class ArrayStoreException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.ArrayStoreException
public class
extends RuntimeException
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of
objects. For example, the following code generates an ArrayStoreException: Since: JDK1.0, CLDC
1.0
Constructor Summary
Constructor and Description
ArrayStoreException()
Method Summary
Constructor Detail
ArrayStoreException
public ArrayStoreException()
Class ArrayStoreException
576
Class ArrayIndexOutOfBoundsException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IndexOutOfBoundsException
java.lang.ArrayIndexOutOfBoundsException
public class
extends IndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative
or greater than or equal to the size of the array. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
ArrayIndexOutOfBoundsException()
Method Summary
Constructor Detail
ArrayIndexOutOfBoundsException
public ArrayIndexOutOfBoundsException()
Constructor Detail
577
Class ArithmeticException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.ArithmeticException
public class
extends RuntimeException
Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by
zero" throws an instance of this class. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
ArithmeticException()
Method Summary
Constructor Detail
ArithmeticException
public ArithmeticException()
Constructor Detail
578
Interface Appendable
public interface
Declares methods to append characters or character sequences. Any class that implements this
interface can receive data formatted by a java.util.Formatter. The appended character or character
sequence should be valid according to the rules described in Unicode Character Representation.
Appendable
itself does not guarantee thread safety. This responsibility is up to the implementing class.
Implementing classes can choose different exception handling mechanism. They can choose to throw
exceptions other than IOException or they do not throw any exceptions at all and use error codes
instead.
Method Summary
Modifier and Type
Appendable
Appendable
Appendable
Method Detail
append
Appendable append(char c)
throws IOException
Appends the character sequence csq. Implementation classes may not append the
whole sequence, for example if the target is a buffer with limited size.
If csq is null, the characters "null" are appended.
Parameters:
csq - the character sequence to append.
Returns:
this Appendable.
Throws:
IOException - if an I/O error occurs.
Constructor Detail
579
Method Detail
580
Class Writer
java.lang.Object
java.io.Writer
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
OutputStreamWriter
Abstract class for writing to character streams. The only methods that a subclass must implement are
write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods
defined here in order to provide higher efficiency, additional functionality, or both. Since: JDK1.1,
CLDC 1.0 See Also:OutputStreamWriter, Reader
Field Summary
Modifier and Type
protected Object
Constructor Summary
Modifier
protected
protected
Method Summary
Modifier and Type
abstract void
abstract void
void
abstract void
void
void
void
Class Writer
Write a string.
write(String str, int off, int len)
581
Field Detail
lock
protected Object lock
Constructor Detail
Writer
protected Writer()
Create a new character-stream writer whose critical sections will synchronize on the
writer itself.
Writer
protected Writer(Object lock)
Create a new character-stream writer whose critical sections will synchronize on the
given object. lock - Object to synchronize on.
Method Detail
close
public abstract void close()
throws IOException
Close the stream, flushing it first. Once a stream has been closed, further write() or
flush() invocations will cause an IOException to be thrown. Closing a
previously-closed stream, however, has no effect.
Specified by:
close in interface AutoCloseable
Throws:
IOException
flush
public abstract void flush()
throws IOException
Flush the stream. If the stream has saved any characters from the various write()
methods in a buffer, write them immediately to their intended destination. Then, if that
destination is another character or byte stream, flush it. Thus one flush() invocation
will flush all the buffers in a chain of Writers and OutputStreams.
Throws:
IOException
write
public void write(char[] cbuf)
throws IOException
582
write
public void write(int c)
throws IOException
write
public void write(String str)
throws IOException
Write a string.
Throws:
IOException
write
public void write(String str,
int off,
int len)
throws IOException
Method Detail
583
Class UnsupportedEncodingException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.UnsupportedEncodingException
public class
extends IOException
Constructor Summary
Constructor and Description
UnsupportedEncodingException()
Method Summary
Constructor Detail
UnsupportedEncodingException
public UnsupportedEncodingException()
Class UnsupportedEncodingException
584
Class UTFDataFormatException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.UTFDataFormatException
public class
extends IOException
Signals that a malformed UTF-8 string has been read in a data input stream or by any class that
implements the data input interface. See the writeUTF method for the format in which UTF-8 strings
are read and written. Since: JDK1.0, CLDC 1.0 See Also:DataInput,
DataInputStream.readUTF(java.io.DataInput), IOException
Constructor Summary
Constructor and Description
UTFDataFormatException()
Method Summary
Constructor Detail
UTFDataFormatException
public UTFDataFormatException()
Constructor Detail
585
Interface Serializable
public interface
Constructor Detail
586
Class Reader
java.lang.Object
java.io.Reader
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
CharArrayReader, InputStreamReader, StringReader
Abstract class for reading character streams. The only methods that a subclass must implement are
read(char[], int, int) and close(). Most subclasses, however, will override some of the methods defined
here in order to provide higher efficiency, additional functionality, or both. Since: JDK1.1, CLDC 1.0
See Also:InputStreamReader, Writer
Field Summary
Modifier and Type
protected Object
Constructor Summary
Modifier
protected
protected
Method Summary
Modifier and Type
abstract void
void
boolean
int
int
abstract int
boolean
void
Interface Serializable
587
long
Skip characters.
Field Detail
lock
protected Object lock
Constructor Detail
Reader
protected Reader()
Create a new character-stream reader whose critical sections will synchronize on the
reader itself.
Reader
protected Reader(Object lock)
Create a new character-stream reader whose critical sections will synchronize on the
given object. lock - The Object to synchronize on.
Method Detail
close
public abstract void close()
throws IOException
Close the stream. Once a stream has been closed, further read(), ready(), mark(), or
reset() invocations will throw an IOException. Closing a previously-closed stream,
however, has no effect.
Specified by:
close in interface AutoCloseable
Throws:
IOException
mark
public void mark(int readAheadLimit)
throws IOException
Mark the present position in the stream. Subsequent calls to reset() will attempt to
reposition the stream to this point. Not all character-input streams support the mark()
operation.
Throws:
IOException
markSupported
public boolean markSupported()
Method Summary
588
Read a single character. This method will block until a character is available, an I/O
error occurs, or the end of the stream is reached. Subclasses that intend to support
efficient single-character input should override this method.
Throws:
IOException
read
public int read(char[] cbuf)
throws IOException
Read characters into an array. This method will block until some input is available, an
I/O error occurs, or the end of the stream is reached.
Throws:
IOException
read
public abstract int read(char[] cbuf,
int off,
int len)
throws IOException
Read characters into a portion of an array. This method will block until some input is
available, an I/O error occurs, or the end of the stream is reached.
Throws:
IOException
ready
public boolean ready()
throws IOException
reset
public void reset()
throws IOException
Reset the stream. If the stream has been marked, then attempt to reposition it at the
mark. If the stream has not been marked, then attempt to reset it in some way
appropriate to the particular stream, for example by repositioning it to its starting
point. Not all character-input streams support the reset() operation, and some support
reset() without supporting mark().
Throws:
IOException
skip
public long skip(long n)
throws IOException
Skip characters. This method will block until some characters are available, an I/O
error occurs, or the end of the stream is reached.
Throws:
IOException
Method Detail
589
Class PrintStream
java.lang.Object
java.io.OutputStream
java.io.PrintStream
All Implemented Interfaces:
AutoCloseable
public class
extends OutputStream
A PrintStream adds functionality to another output stream, namely the ability to print representations
of various data values conveniently. Two other features are provided as well. Unlike other output
streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an
internal flag that can be tested via the checkError method. All characters printed by a PrintStream are
converted into bytes using the platform's default character encoding. Since: JDK1.0, CLDC 1.0
Constructor Summary
Constructor and Description
PrintStream(OutputStream out)
Method Summary
Modifier and
Type
boolean
void
void
void
void
void
void
void
void
void
void
void
void
Class PrintStream
Print an integer.
print(long l)
Print an object.
print(String s)
Print a string.
println()
590
void
void
void
void
void
void
void
protected void
setError()
Write len bytes from the specified byte array starting at offset off to this
stream.
void
write(int b)
void
Constructor Detail
PrintStream
public PrintStream(OutputStream out)
Create a new print stream. This stream will not flush automatically. out - The output
stream to which values and objects will be printed
Method Detail
checkError
public boolean checkError()
Flush the stream and check its error state. The internal error state is set to true when
the underlying output stream throws an IOException, and when the setError method
is invoked.
close
public void close()
Close the stream. This is done by flushing the stream and then closing the underlying
output stream.
Specified by:
close in interface AutoCloseable
Overrides:
close in class OutputStream
Method Summary
591
Flush the stream. This is done by writing any buffered output bytes to the underlying
output stream and then flushing that stream.
Overrides:
flush in class OutputStream
print
public void print(boolean b)
Print a boolean value. The string produced by is translated into bytes according to the
platform's default character encoding, and these bytes are written in exactly the
manner of the method.
print
public void print(char c)
Print an array of characters. The characters are converted into bytes according to the
platform's default character encoding, and these bytes are written in exactly the
manner of the method.
print
public void print(double d)
Print a floating point number. The string produced by is translated into bytes
according to the platform's default character encoding, and these bytes are written in
exactly the manner of the method.
print
public void print(int i)
Print an integer. The string produced by is translated into bytes according to the
platform's default character encoding, and these bytes are written in exactly the
manner of the method.
print
public void print(long l)
Print a long integer. The string produced by is translated into bytes according to the
platform's default character encoding, and these bytes are written in exactly the
manner of the method.
print
public void print(Object obj)
Print an object. The string produced by the method is translated into bytes according
to the platform's default character encoding, and these bytes are written in exactly the
manner of the method.
print
public void print(String s)
Print a string. If the argument is null then the string "null" is printed. Otherwise, the
string's characters are converted into bytes according to the platform's default
character encoding, and these bytes are written in exactly the manner of the method.
Method Detail
592
Terminate the current line by writing the line separator string. The line separator
string is defined by the system property line.separator, and is not necessarily a single
newline character ('\n').
println
public void println(boolean x)
Print a boolean and then terminate the line. This method behaves as though it
invokes and then .
println
public void println(char x)
Print an array of characters and then terminate the line. This method behaves as
though it invokes and then .
println
public void println(double x)
Print a double and then terminate the line. This method behaves as though it invokes
and then .
println
public void println(float x)
Print a float and then terminate the line. This method behaves as though it invokes
and then .
println
public void println(int x)
Print an integer and then terminate the line. This method behaves as though it
invokes and then .
println
public void println(long x)
Print a long and then terminate the line. This method behaves as though it invokes
and then .
println
public void println(Object x)
Print an Object and then terminate the line. This method behaves as though it
invokes and then .
println
public void println(String x)
Print a String and then terminate the line. This method behaves as though it invokes
and then .
setError
protected void setError()
Write len bytes from the specified byte array starting at offset off to this stream. Note
that the bytes will be written as given; to write characters that will be translated
Method Detail
593
Write the specified byte to this stream. Note that the byte is written as given; to write
a character that will be translated according to the platform's default character
encoding, use the print(char) or println(char) methods.
Specified by:
write in class OutputStream
Method Detail
594
Class OutputStreamWriter
java.lang.Object
java.io.Writer
java.io.OutputStreamWriter
All Implemented Interfaces:
AutoCloseable
public class
extends Writer
Field Summary
Constructor Summary
Constructor and Description
OutputStreamWriter(OutputStream os)
Method Summary
Modifier and Type
void
void
void
void
void
Class OutputStreamWriter
595
Constructor Detail
OutputStreamWriter
public OutputStreamWriter(OutputStream os)
Method Detail
close
public void close()
throws IOException
flush
public void flush()
throws IOException
write
public void write(char[] cbuf,
int off,
int len)
throws IOException
write
public void write(int c)
throws IOException
596
write
public void write(String str,
int off,
int len)
throws IOException
Method Detail
597
Class OutputStream
java.lang.Object
java.io.OutputStream
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
BufferedOutputStream, ByteArrayOutputStream, DataOutputStream, FilterOutputStream,
PrintStream
This abstract class is the superclass of all classes representing an output stream of bytes. An output
stream accepts output bytes and sends them to some sink. Applications that need to define a
subclass of OutputStream must always provide at least a method that writes one byte of output.
Since: JDK1.0, CLDC 1.0 See Also:ByteArrayOutputStream, DataOutputStream, InputStream,
write(int)
Constructor Summary
Constructor and Description
OutputStream()
Method Summary
Modifier and
Type
Closes this output stream and releases any system resources associated
with this stream.
void
flush()
Flushes this output stream and forces any buffered output bytes to be
written out.
void
write(byte[] b)
void
Writes b.length bytes from the specified byte array to this output stream.
write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this
output stream.
void
abstract void
write(int b)
Constructor Detail
Class OutputStream
598
Method Detail
close
public void close()
throws IOException
Closes this output stream and releases any system resources associated with this
stream. The general contract of close is that it closes the output stream. A closed
stream cannot perform output operations and cannot be reopened. The close method
of OutputStream does nothing.
Specified by:
close in interface AutoCloseable
Throws:
IOException
flush
public void flush()
throws IOException
Flushes this output stream and forces any buffered output bytes to be written out.
The general contract of flush is that calling it is an indication that, if any bytes
previously written have been buffered by the implementation of the output stream,
such bytes should immediately be written to their intended destination. The flush
method of OutputStream does nothing.
Throws:
IOException
write
public void write(byte[] b)
throws IOException
Writes b.length bytes from the specified byte array to this output stream. The general
contract for write(b) is that it should have exactly the same effect as the call write(b,
0, b.length).
Throws:
IOException
write
public void write(byte[] b,
int off,
int len)
throws IOException
Writes len bytes from the specified byte array starting at offset off to this output
stream. The general contract for write(b, off, len) is that some of the bytes in the array
b are written to the output stream in order; element b[off] is the first byte written and
b[off+len-1] is the last byte written by this operation. The write method of
OutputStream calls the write method of one argument on each of the bytes to be
written out. Subclasses are encouraged to override this method and provide a more
efficient implementation. If b is null, a NullPointerException is thrown. If off is
negative, or len is negative, or off+len is greater than the length of the array b, then
an IndexOutOfBoundsException is thrown.
Throws:
IOException
write
public abstract void write(int b)
throws IOException
Writes the specified byte to this output stream. The general contract for write is that
one byte is written to the output stream. The byte to be written is the eight low-order
bits of the argument b. The 24 high-order bits of b are ignored. Subclasses of
Constructor Detail
599
Method Detail
600
Class InterruptedIOException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.InterruptedIOException
public class
extends IOException
Signals that an I/O operation has been interrupted. An InterruptedIOException is thrown to indicate
that an input or output transfer has been terminated because the thread performing it was terminated.
The field bytesTransferred indicates how many bytes were successfully transferred before the
interruption occurred. Since: JDK1.0, CLDC 1.0 See Also:InputStream, OutputStream
Field Summary
Modifier and
Type
Reports how many bytes had been transferred as part of the I/O operation
before it was interrupted.
int
Constructor Summary
Constructor and Description
InterruptedIOException()
Method Summary
Field Detail
bytesTransferred
public int bytesTransferred
Reports how many bytes had been transferred as part of the I/O operation before it
was interrupted.
Class InterruptedIOException
601
Detail
InterruptedIOException
public InterruptedIOException()
Constructor Detail
602
Class InputStreamReader
java.lang.Object
java.io.Reader
java.io.InputStreamReader
All Implemented Interfaces:
AutoCloseable
public class
extends Reader
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and
translates them into characters. The encoding that it uses may be specified by name, or the platform's
default encoding may be accepted. Each invocation of one of an InputStreamReader's read()
methods may cause one or more bytes to be read from the underlying byte input stream. To enable
the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying
stream than are necessary to satisfy the current read operation. Since: CLDC 1.0 See Also:Reader,
UnsupportedEncodingException
Field Summary
Constructor Summary
Constructor and Description
InputStreamReader(InputStream is)
Method Summary
Modifier and Type
void
void
boolean
int
int
boolean
void
long
Class InputStreamReader
Skip characters.
603
read
Constructor Detail
InputStreamReader
public InputStreamReader(InputStream is)
Method Detail
close
public void close()
throws IOException
mark
public void mark(int readAheadLimit)
throws IOException
markSupported
public boolean markSupported()
604
read
public int read(char[] cbuf,
int off,
int len)
throws IOException
ready
public boolean ready()
throws IOException
reset
public void reset()
throws IOException
skip
public long skip(long n)
throws IOException
Skip characters.
Overrides:
skip in class Reader
Throws:
IOException
Method Detail
605
Class InputStream
java.lang.Object
java.io.InputStream
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
BufferedInputStream, ByteArrayInputStream, DataInputStream, FilterInputStream
This abstract class is the superclass of all classes representing an input stream of bytes. Applications
that need to define a subclass of InputStream must always provide a method that returns the next
byte of input. Since: JDK1.0, CLDC 1.0 See Also:ByteArrayInputStream, DataInputStream, read(),
OutputStream
Constructor Summary
Constructor and Description
InputStream()
Method Summary
Modifier and
Type
Returns the number of bytes that can be read (or skipped over) from this input
stream without blocking by the next caller of a method for this input stream.
int
close()
Closes this input stream and releases any system resources associated with
the stream.
void
mark(int readlimit)
void
boolean
abstract
int
markSupported()
Tests if this input stream supports the mark and reset methods.
read()
Reads some number of bytes from the input stream and stores them into the
buffer array b.
int
int
Reads up to len bytes of data from the input stream into an array of bytes.
reset()
Repositions this stream to the position at the time the mark method was last
called on this input stream.
void
skip(long n)
long
Skips over and discards n bytes of data from this input stream.
Class InputStream
606
Detail
InputStream
public InputStream()
Method Detail
available
public int available()
throws IOException
Returns the number of bytes that can be read (or skipped over) from this input stream
without blocking by the next caller of a method for this input stream. The next caller
might be the same thread or another thread. The available method for class
InputStream always returns 0. This method should be overridden by subclasses.
Throws:
IOException
close
public void close()
throws IOException
Closes this input stream and releases any system resources associated with the
stream. The close method of InputStream does nothing.
Specified by:
close in interface AutoCloseable
Throws:
IOException
mark
public void mark(int readlimit)
Marks the current position in this input stream. A subsequent call to the reset method
repositions this stream at the last marked position so that subsequent reads re-read
the same bytes. The readlimit arguments tells this input stream to allow that many
bytes to be read before the mark position gets invalidated. The general contract of
mark is that, if the method markSupported returns true, the stream somehow
remembers all the bytes read after the call to mark and stands ready to supply those
same bytes again if and whenever the method reset is called. However, the stream is
not required to remember any data at all if more than readlimit bytes are read from
the stream before reset is called. The mark method of InputStream does nothing.
markSupported
public boolean markSupported()
Tests if this input stream supports the mark and reset methods. The markSupported
method of InputStream returns false.
read
public abstract int read()
throws IOException
Reads the next byte of data from the input stream. The value byte is returned as an
int in the range 0 to 255. If no byte is available because the end of the stream has
been reached, the value -1 is returned. This method blocks until input data is
available, the end of the stream is detected, or an exception is thrown. A subclass
must provide an implementation of this method.
Throws:
IOException
Constructor Detail
607
Reads some number of bytes from the input stream and stores them into the buffer
array b. The number of bytes actually read is returned as an integer. This method
blocks until input data is available, end of file is detected, or an exception is thrown. If
b is null, a NullPointerException is thrown. If the length of b is zero, then no bytes are
read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no
byte is available because the stream is at end of file, the value -1 is returned;
otherwise, at least one byte is read and stored into b. The first byte read is stored into
element b[0], the next one into b[1], and so on. The number of bytes read is, at most,
equal to the length of b. Let k be the number of bytes actually read; these bytes will
be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1]
unaffected. If the first byte cannot be read for any reason other than end of file, then
an IOException is thrown. In particular, an IOException is thrown if the input stream
has been closed. The read(b) method for class InputStream has the same effect as:
read(b, 0, b.length)
Throws:
IOException
read
public int read(byte[] b,
int off,
int len)
throws IOException
Reads up to len bytes of data from the input stream into an array of bytes. An attempt
is made to read as many as len bytes, but a smaller number may be read, possibly
zero. The number of bytes actually read is returned as an integer. This method blocks
until input data is available, end of file is detected, or an exception is thrown. If b is
null, a NullPointerException is thrown. If off is negative, or len is negative, or off+len
is greater than the length of the array b, then an IndexOutOfBoundsException is
thrown. If len is zero, then no bytes are read and 0 is returned; otherwise, there is an
attempt to read at least one byte. If no byte is available because the stream is at end
of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.
The first byte read is stored into element b[off], the next one into b[off+1], and so on.
The number of bytes read is, at most, equal to len. Let k be the number of bytes
actually read; these bytes will be stored in elements b[off] through b[off+k-1], leaving
elements b[off+k] through b[off+len-1] unaffected. In every case, elements b[0]
through b[off] and elements b[off+len] through b[b.length-1] are unaffected. If the first
byte cannot be read for any reason other than end of file, then an IOException is
thrown. In particular, an IOException is thrown if the input stream has been closed.
The read(b, off, len) method for class InputStream simply calls the method read()
repeatedly. If the first such call results in an IOException, that exception is returned
from the call to the read(b, off, len) method. If any subsequent call to read() results in
a IOException, the exception is caught and treated as if it were end of file; the bytes
read up to that point are stored into b and the number of bytes read before the
exception occurred is returned. Subclasses are encouraged to provide a more
efficient implementation of this method.
Throws:
IOException
reset
public void reset()
throws IOException
Repositions this stream to the position at the time the mark method was last called on
this input stream. The general contract of reset is: If the method markSupported
returns true, then: If the method mark has not been called since the stream was
created, or the number of bytes read from the stream since mark was last called is
larger than the argument to mark at that last call, then an IOException might be
thrown. If such an IOException is not thrown, then the stream is reset to a state such
that all the bytes read since the most recent call to mark (or since the start of the file,
if mark has not been called) will be resupplied to subsequent callers of the read
method, followed by any bytes that otherwise would have been the next input data as
Method Detail
608
of the time of the call to reset. If the method markSupported returns false, then: The
call to reset may throw an IOException. If an IOException is not thrown, then the
stream is reset to a fixed state that depends on the particular type of the input stream
and how it was created. The bytes that will be supplied to subsequent callers of the
read method depend on the particular type of the input stream. The method reset for
class InputStream does nothing and always throws an IOException.
Throws:
IOException
skip
public long skip(long n)
throws IOException
Skips over and discards n bytes of data from this input stream. The skip method may,
for a variety of reasons, end up skipping over some smaller number of bytes, possibly
0. This may result from any of a number of conditions; reaching end of file before n
bytes have been skipped is only one possibility. The actual number of bytes skipped
is returned. If n is negative, no bytes are skipped. The skip method of InputStream
creates a byte array and then repeatedly reads into it until n bytes have been read or
the end of the stream has been reached. Subclasses are encouraged to provide a
more efficient implementation of this method.
Throws:
IOException
Method Detail
609
Class IOException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
Direct Known Subclasses:
EOFException, GZIPException, InterruptedIOException, UnsupportedEncodingException,
UTFDataFormatException
public class
extends Exception
Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions
produced by failed or interrupted I/O operations. Since: JDK1.0, CLDC 1.0 See Also:InputStream,
OutputStream
Constructor Summary
Constructor and Description
IOException()
Method Summary
Constructor Detail
IOException
public IOException()
Constructs an IOException with the specified detail message. The error message
string s can later be retrieved by the method of class java.lang.Throwable. s - the
detail message.
Class IOException
610
Interface Flushable
public interface
Method Summary
Modifier and
Type
Flushes the object by writing out any buffered data to the underlying
output.
void
Method Detail
flush
void flush()
throws IOException
Flushes the object by writing out any buffered data to the underlying output.
Throws:
IOException
Constructor Detail
611
Class EOFException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.EOFException
public class
extends IOException
Signals that an end of file or end of stream has been reached unexpectedly during input. This
exception is mainly used by data input streams, which generally expect a binary file in a specific
format, and for which an end of stream is an unusual condition. Most other input streams return a
special value on end of stream. Note that some input operations react to end-of-file by returning a
distinguished value (such as -1) rather than by throwing an exception. Since: JDK1.0, CLDC 1.0 See
Also:DataInputStream, IOException
Constructor Summary
Constructor and Description
EOFException()
Method Summary
Constructor Detail
EOFException
public EOFException()
Constructs an EOFException with the specified detail message. The string s may
later be retrieved by the method of class java.lang.Throwable. s - the detail message.
Method Detail
612
Class DataOutputStream
java.lang.Object
java.io.OutputStream
java.io.DataOutputStream
All Implemented Interfaces:
DataOutput, AutoCloseable
public class
extends OutputStream
implements DataOutput
A data output stream lets an application write primitive Java data types to an output stream in a
portable way. An application can then use a data input stream to read the data back in. Since:
JDK1.0, CLDC 1.0 See Also:DataInputStream
Field Summary
Modifier and Type
protected OutputStream
Constructor Summary
Constructor and Description
DataOutputStream(OutputStream out)
Creates a new data output stream to write data to the specified underlying output stream.
Method Summary
Modifier
and Type
void
void
Closes this output stream and releases any system resources associated with
the stream.
flush()
void
Writes len bytes from the specified byte array starting at offset off to the
underlying output stream.
write(int b)
void
void
void
void
void
void
Constructor Detail
Writes the specified byte (the low eight bits of the argument b) to the underlying
output stream.
writeBoolean(boolean v)
Writes a char to the underlying output stream as a 2-byte value, high byte first.
writeChars(String s)
613
Converts the float argument to an int using the floatToIntBits method in class
Float, and then writes that int value to the underlying output stream as a 4-byte
quantity, high byte first.
void
writeInt(int v)
void
Writes an int to the underlying output stream as four bytes, high byte first.
writeLong(long v)
void
Writes a long to the underlying output stream as eight bytes, high byte first.
writeShort(int v)
void
Writes a short to the underlying output stream as two bytes, high byte first.
writeUTF(String str)
void
Field Detail
out
protected OutputStream out
Constructor Detail
DataOutputStream
public DataOutputStream(OutputStream out)
Creates a new data output stream to write data to the specified underlying output
stream. out - the underlying output stream, to be saved for later use.
Method Detail
close
public void close()
throws IOException
Closes this output stream and releases any system resources associated with the
stream. The close method calls its flush method, and then calls the close method of
its underlying output stream.
Specified by:
close in interface AutoCloseable
Overrides:
close in class OutputStream
Method Summary
614
flush
public void flush()
throws IOException
Flushes this data output stream. This forces any buffered output bytes to be written
out to the stream. The flush method of DataOutputStream calls the flush method of its
underlying output stream.
Overrides:
flush in class OutputStream
Throws:
IOException
write
public void write(byte[] b,
int off,
int len)
throws IOException
Writes len bytes from the specified byte array starting at offset off to the underlying
output stream.
Specified by:
write in interface DataOutput
Overrides:
write in class OutputStream
Throws:
IOException
write
public void write(int b)
throws IOException
Writes the specified byte (the low eight bits of the argument b) to the underlying
output stream. Implements the write method of OutputStream.
Specified by:
write in interface DataOutput
Specified by:
write in class OutputStream
Throws:
IOException
writeBoolean
public final void writeBoolean(boolean v)
throws IOException
Writes a boolean to the underlying output stream as a 1-byte value. The value true is
written out as the value (byte)1; the value false is written out as the value (byte)0.
Specified by:
writeBoolean in interface DataOutput
Throws:
IOException
writeByte
public final void writeByte(int v)
throws IOException
writeChar
public final void writeChar(int v)
throws IOException
Writes a char to the underlying output stream as a 2-byte value, high byte first.
Method Detail
615
in interface DataOutput
Throws:
IOException
writeChars
public final void writeChars(String s)
throws IOException
writeDouble
public final void writeDouble(double v)
throws IOException
Converts the double argument to a long using the doubleToLongBits method in class
Double, and then writes that long value to the underlying output stream as an 8-byte
quantity, high byte first.
Specified by:
writeDouble in interface DataOutput
Throws:
IOException
writeFloat
public final void writeFloat(float v)
throws IOException
Converts the float argument to an int using the floatToIntBits method in class Float,
and then writes that int value to the underlying output stream as a 4-byte quantity,
high byte first.
Specified by:
writeFloat in interface DataOutput
Throws:
IOException
writeInt
public final void writeInt(int v)
throws IOException
Writes an int to the underlying output stream as four bytes, high byte first.
Specified by:
writeInt in interface DataOutput
Throws:
IOException
writeLong
public final void writeLong(long v)
throws IOException
Writes a long to the underlying output stream as eight bytes, high byte first.
Specified by:
writeLong in interface DataOutput
Throws:
IOException
writeShort
public final void writeShort(int v)
throws IOException
Writes a short to the underlying output stream as two bytes, high byte first.
Specified by:
writeShort in interface DataOutput
Throws:
IOException
Method Detail
616
Method Detail
617
Interface DataOutput
All Superinterfaces:
AutoCloseable
All Known Implementing Classes:
DataOutputStream
public interface
extends AutoCloseable
The DataOutput interface provides for converting data from any of the Java primitive types to a series
of bytes and writing these bytes to a binary stream. There is also a facility for converting a String into
Java modified UTF-8 format and writing the resulting series of bytes. For all the methods in this
interface that write bytes, it is generally true that if a byte cannot be written for any reason, an
IOException is thrown. Since: JDK1.0, CLDC 1.0 See Also:DataInput, DataOutputStream
Method Summary
Modifier and
Type
void
void
void
Writes to the output stream the eight low-order bits of the argument b.
writeBoolean(boolean v)
void
void
Writes to the output stream the eight low- order bits of the argument v.
writeChar(int v)
void
Writes a char value, which is comprised of two bytes, to the output stream.
writeChars(String s)
Writes every character in the string s, to the output stream, in order, two bytes
per character.
void
writeDouble(double v)
void
writeFloat(float v)
void
Writes a float value, which is comprised of four bytes, to the output stream.
writeInt(int v)
void
Writes an int value, which is comprised of four bytes, to the output stream.
writeLong(long v)
void
Writes an long value, which is comprised of four bytes, to the output stream.
writeShort(int v)
void
Writes two bytes to the output stream to represent the value of the argument.
writeUTF(String s)
Writes two bytes of length information to the output stream, followed by the
Java modified UTF representation of every character in the string s.
void
Interface DataOutput
618
Method Detail
write
void write(byte[] b)
throws IOException
Writes to the output stream all the bytes in array b. If b is null, a NullPointerException
is thrown. If b.length is zero, then no bytes are written. Otherwise, the byte b[0] is
written first, then b[1], and so on; the last byte written is b[b.length-1].
Throws:
IOException
write
void write(byte[] b,
int off,
int len)
throws IOException
Writes len bytes from array b, in order, to the output stream. If b is null, a
NullPointerException is thrown. If off is negative, or len is negative, or off+len is
greater than the length of the array b, then an IndexOutOfBoundsException is thrown.
If len is zero, then no bytes are written. Otherwise, the byte b[off] is written first, then
b[off+1], and so on; the last byte written is b[off+len-1].
Throws:
IOException
write
void write(int b)
throws IOException
Writes to the output stream the eight low-order bits of the argument b. The 24
high-order bits of b are ignored.
Throws:
IOException
writeBoolean
void writeBoolean(boolean v)
throws IOException
Writes a boolean value to this output stream. If the argument v is true, the value
(byte)1 is written; if v is false, the value (byte)0 is written. The byte written by this
method may be read by the readBoolean method of interface DataInput, which will
then return a boolean equal to v.
Throws:
IOException
writeByte
void writeByte(int v)
throws IOException
Writes to the output stream the eight low- order bits of the argument v. The 24
high-order bits of v are ignored. (This means that writeByte does exactly the same
thing as write for an integer argument.) The byte written by this method may be read
by the readByte method of interface DataInput, which will then return a byte equal to
(byte)v.
Throws:
IOException
writeChar
void writeChar(int v)
throws IOException
Writes a char value, which is comprised of two bytes, to the output stream. The byte
values to be written, in the order shown, are: (byte)(0xff (v 8)) (byte)(0xff v) The bytes
written by this method may be read by the readChar method of interface DataInput,
which will then return a char equal to (char)v.
Method Detail
619
writeChars
void writeChars(String s)
throws IOException
Writes every character in the string s, to the output stream, in order, two bytes per
character. If s is null, a NullPointerException is thrown. If s.length is zero, then no
characters are written. Otherwise, the character s[0] is written first, then s[1], and so
on; the last character written is s[s.length-1]. For each character, two bytes are
actually written, high-order byte first, in exactly the manner of the writeChar method.
Throws:
IOException
writeDouble
void writeDouble(double v)
throws IOException
Writes a double value, which is comprised of eight bytes, to the output stream. It does
this as if it first converts this double value to a long in exactly the manner of the
Double.doubleToLongBits method and then writes the long value in exactly the
manner of the writeLong method. The bytes written by this method may be read by
the readDouble method of interface DataInput, which will then return a double equal
to v.
Throws:
IOException
writeFloat
void writeFloat(float v)
throws IOException
Writes a float value, which is comprised of four bytes, to the output stream. It does
this as if it first converts this float value to an int in exactly the manner of the
Float.floatToIntBits method and then writes the int value in exactly the manner of the
writeInt method. The bytes written by this method may be read by the readFloat
method of interface DataInput, which will then return a float equal to v.
Throws:
IOException
writeInt
void writeInt(int v)
throws IOException
Writes an int value, which is comprised of four bytes, to the output stream. The byte
values to be written, in the order shown, are: (byte)(0xff (v 24)) (byte)(0xff (v 16))
(byte)(0xff (v 8)) (byte)(0xff v) The bytes written by this method may be read by the
readInt method of interface DataInput, which will then return an int equal to v.
Throws:
IOException
writeLong
void writeLong(long v)
throws IOException
Writes an long value, which is comprised of four bytes, to the output stream. The byte
values to be written, in the order shown, are: (byte)(0xff (v 56)) (byte)(0xff (v 48))
(byte)(0xff (v 40)) (byte)(0xff (v 32)) (byte)(0xff (v 24)) (byte)(0xff (v 16)) (byte)(0xff (v
8)) (byte)(0xff v) The bytes written by this method may be read by the readLong
method of interface DataInput, which will then return a long equal to v.
Throws:
IOException
writeShort
void writeShort(int v)
throws IOException
Writes two bytes to the output stream to represent the value of the argument. The
byte values to be written, in the order shown, are: (byte)(0xff (v 8)) (byte)(0xff v) The
Method Detail
620
bytes written by this method may be read by the readShort method of interface
DataInput, which will then return a short equal to (short)v.
Throws:
IOException
writeUTF
void writeUTF(String s)
throws IOException
Writes two bytes of length information to the output stream, followed by the Java
modified UTF representation of every character in the string s. If s is null, a
NullPointerException is thrown. Each character in the string s is converted to a group
of one, two, or three bytes, depending on the value of the character. If a character c
is in the range u0001 through u007f, it is represented by one byte: (byte)c If a
character c is u0000 or is in the range u0080 through u07ff, then it is represented by
two bytes, to be written in the order shown: (byte)(0xc0 | (0x1f (c 6))) (byte)(0x80 |
(0x3f c)) If a character c is in the range u0800 through uffff, then it is represented by
three bytes, to be written in the order shown: (byte)(0xe0 | (0x0f (c 12))) (byte)(0x80 |
(0x3f (c 6))) (byte)(0x80 | (0x3f c)) First, the total number of bytes needed to
represent all the characters of s is calculated. If this number is larger than 65535,
then a UTFDataFormatError is thrown. Otherwise, this length is written to the output
stream in exactly the manner of the writeShort method; after this, the one-, two-, or
three-byte representation of each character in the string s is written. The bytes written
by this method may be read by the readUTF method of interface DataInput, which will
then return a String equal to s.
Throws:
IOException
Method Detail
621
Class DataInputStream
java.lang.Object
java.io.InputStream
java.io.DataInputStream
All Implemented Interfaces:
DataInput, AutoCloseable
public class
extends InputStream
implements DataInput
A data input stream lets an application read primitive Java data types from an underlying input stream
in a machine-independent way. An application uses a data output stream to write data that can later
be read by a data input stream. Since: JDK1.0, CLDC 1.0 See Also:DataOutputStream
Field Summary
Modifier and Type
protected InputStream
Constructor Summary
Constructor and Description
DataInputStream(InputStream in)
Creates a DataInputStream and saves its argument, the input stream in, for later use.
Method Summary
Modifier
and Type
int
Returns the number of bytes that can be read from this input stream without
blocking.
close()
void
void
boolean
int
int
int
boolean
byte
Class DataInputStream
Closes this input stream and releases any system resources associated with
the stream.
mark(int readlimit)
Tests if this input stream supports the mark and reset methods.
read()
Reads up to len bytes of data from this input stream into an array of bytes.
readBoolean()
622
char
double
float
void
void
int
long
short
int
int
String
static
String
reset()
Repositions this stream to the position at the time the mark method was last
called on this input stream.
void
skip(long n)
long
Skips over and discards n bytes of data from the input stream.
skipBytes(int n)
int
Field Detail
in
protected InputStream in
Constructor Detail
DataInputStream
public DataInputStream(InputStream in)
Creates a DataInputStream and saves its argument, the input stream in, for later use.
in - the input stream.
Method Summary
623
Method Detail
available
public int available()
throws IOException
Returns the number of bytes that can be read from this input stream without blocking.
This method simply performs in.available() and returns the result.
Overrides:
available in class InputStream
Throws:
IOException
close
public void close()
throws IOException
Closes this input stream and releases any system resources associated with the
stream. This method simply performs in.close().
Specified by:
close in interface AutoCloseable
Overrides:
close in class InputStream
Throws:
IOException
mark
public void mark(int readlimit)
Marks the current position in this input stream. A subsequent call to the reset method
repositions this stream at the last marked position so that subsequent reads re-read
the same bytes. The readlimit argument tells this input stream to allow that many
bytes to be read before the mark position gets invalidated. This method simply
performs in.mark(readlimit).
Overrides:
mark in class InputStream
markSupported
public boolean markSupported()
Tests if this input stream supports the mark and reset methods. This method simply
performs in.markSupported().
Overrides:
markSupported in class InputStream
read
public int read()
throws IOException
Reads the next byte of data from this input stream. The value byte is returned as an
int in the range 0 to 255. If no byte is available because the end of the stream has
been reached, the value -1 is returned. This method blocks until input data is
available, the end of the stream is detected, or an exception is thrown. This method
simply performs in.read() and returns the result.
Specified by:
read in class InputStream
Throws:
IOException
read
public final int read(byte[] b)
throws IOException
See the general contract of the read method of DataInput. Bytes for this operation are
read from the contained input stream.
Method Detail
624
in class InputStream
Throws:
IOException
read
public final int read(byte[] b,
int off,
int len)
throws IOException
Reads up to len bytes of data from this input stream into an array of bytes. This
method blocks until some input is available. This method simply performs in.read(b,
off, len) and returns the result.
Overrides:
read in class InputStream
Throws:
IOException
readBoolean
public final boolean readBoolean()
throws IOException
See the general contract of the readBoolean method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
readBoolean in interface DataInput
Throws:
IOException
readByte
public final byte readByte()
throws IOException
See the general contract of the readByte method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
readByte in interface DataInput
Throws:
IOException
readChar
public final char readChar()
throws IOException
See the general contract of the readChar method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
readChar in interface DataInput
Throws:
IOException
readDouble
public final double readDouble()
throws IOException
See the general contract of the readDouble method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
readDouble in interface DataInput
Throws:
IOException
readFloat
public final float readFloat()
throws IOException
See the general contract of the readFloat method of DataInput. Bytes for this
operation are read from the contained input stream.
Method Detail
625
in interface DataInput
Throws:
IOException
readFully
public final void readFully(byte[] b)
throws IOException
See the general contract of the readFully method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
readFully in interface DataInput
Throws:
IOException
readFully
public final void readFully(byte[] b,
int off,
int len)
throws IOException
See the general contract of the readFully method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
readFully in interface DataInput
Throws:
IOException
readInt
public final int readInt()
throws IOException
See the general contract of the readInt method of DataInput. Bytes for this operation
are read from the contained input stream.
Specified by:
readInt in interface DataInput
Throws:
IOException
readLong
public final long readLong()
throws IOException
See the general contract of the readLong method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
readLong in interface DataInput
Throws:
IOException
readShort
public final short readShort()
throws IOException
See the general contract of the readShort method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
readShort in interface DataInput
Throws:
IOException
readUnsignedByte
public final int readUnsignedByte()
throws IOException
See the general contract of the readUnsignedByte method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
Method Detail
626
in interface DataInput
Throws:
IOException
readUnsignedShort
public final int readUnsignedShort()
throws IOException
See the general contract of the readUnsignedShort method of DataInput. Bytes for
this operation are read from the contained input stream.
Specified by:
readUnsignedShort in interface DataInput
Throws:
IOException
readUTF
public final String readUTF()
throws IOException
See the general contract of the readUTF method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
readUTF in interface DataInput
Throws:
IOException
readUTF
public static final String readUTF(DataInput in)
throws IOException
reset
public void reset()
throws IOException
Repositions this stream to the position at the time the mark method was last called on
this input stream. This method simply performs in.reset(). Stream marks are intended
to be used in situations where you need to read ahead a little to see what's in the
stream. Often this is most easily done by invoking some general parser. If the stream
is of the type handled by the parse, it just chugs along happily. If the stream is not of
that type, the parser should toss an exception when it fails. If this happens within
readlimit bytes, it allows the outer code to reset the stream and try another parser.
Overrides:
reset in class InputStream
Throws:
IOException
skip
public long skip(long n)
throws IOException
Skips over and discards n bytes of data from the input stream. The skip method may,
for a variety of reasons, end up skipping over some smaller number of bytes, possibly
0. The actual number of bytes skipped is returned. This method simply performs
in.skip(n).
Overrides:
skip in class InputStream
Throws:
IOException
Method Detail
627
skipBytes
public final int skipBytes(int n)
throws IOException
See the general contract of the skipBytes method of DataInput. Bytes for this
operation are read from the contained input stream.
Specified by:
skipBytes in interface DataInput
Throws:
IOException
Method Detail
628
Interface DataInput
All Superinterfaces:
AutoCloseable
All Known Implementing Classes:
DataInputStream
public interface
extends AutoCloseable
The DataInput interface provides for reading bytes from a binary stream and reconstructing from them
data in any of the Java primitive types. There is also a facility for reconstructing a String from data in
Java modified UTF-8 format. It is generally true of all the reading routines in this interface that if end
of file is reached before the desired number of bytes has been read, an EOFException (which is a
kind of IOException) is thrown. If any byte cannot be read for any reason other than end of file, an
IOException other than EOFException is thrown. In particular, an IOException may be thrown if the
input stream has been closed. Since: JDK1.0, CLDC 1.0 See Also:DataInputStream, DataOutput
Method Summary
Modifier and
Type
boolean
byte
char
double
float
Reads one input byte and returns true if that byte is nonzero, false if that
byte is zero.
readByte()
void
void
int
long
short
Reads some bytes from an input stream and stores them into the buffer
array b.
readFully(byte[] b, int off, int len)
int
Reads one input byte, zero-extends it to type int, and returns the result,
which is therefore in the range 0 through 255.
readUnsignedShort()
int
String
Reads two input bytes, zero-extends it to type int, and returns an int value in
the range 0 through 65535.
readUTF()
Reads in a string that has been encoded using a modified UTF-8 format.
skipBytes(int n)
int
Interface DataInput
Makes an attempt to skip over n bytes of data from the input stream,
discarding the skipped bytes.
629
close
Method Detail
readBoolean
boolean readBoolean()
throws IOException
Reads one input byte and returns true if that byte is nonzero, false if that byte is zero.
This method is suitable for reading the byte written by the writeBoolean method of
interface DataOutput.
Throws:
IOException
readByte
byte readByte()
throws IOException
Reads and returns one input byte. The byte is treated as a signed value in the range
-128 through 127, inclusive. This method is suitable for reading the byte written by
the writeByte method of interface DataOutput.
Throws:
IOException
readChar
char readChar()
throws IOException
Reads an input char and returns the char value. A Unicode char is made up of two
bytes. Let a be the first byte read and b be the second byte. The value returned is:
(char)((a 8) | (b 0xff)) This method is suitable for reading bytes written by the
writeChar method of interface DataOutput.
Throws:
IOException
readDouble
double readDouble()
throws IOException
Reads eight input bytes and returns a double value. It does this by first constructing a
long value in exactly the manner of the readlong method, then converting this long
value to a double in exactly the manner of the method Double.longBitsToDouble. This
method is suitable for reading bytes written by the writeDouble method of interface
DataOutput.
Throws:
IOException
readFloat
float readFloat()
throws IOException
Reads four input bytes and returns a float value. It does this by first constructing an
int value in exactly the manner of the readInt method, then converting this int value to
a float in exactly the manner of the method Float.intBitsToFloat. This method is
suitable for reading bytes written by the writeFloat method of interface DataOutput.
Throws:
IOException
readFully
void readFully(byte[] b)
throws IOException
630
readFully
void readFully(byte[] b,
int off,
int len)
throws IOException
Reads len bytes from an input stream. This method blocks until one of the following
conditions occurs: len bytes of input data are available, in which case a normal return
is made. End of file is detected, in which case an EOFException is thrown. An I/O
error occurs, in which case an IOException other than EOFException is thrown. If b is
null, a NullPointerException is thrown. If off is negative, or len is negative, or off+len
is greater than the length of the array b, then an IndexOutOfBoundsException is
thrown. If len is zero, then no bytes are read. Otherwise, the first byte read is stored
into element b[off], the next one into b[off+1], and so on. The number of bytes read is,
at most, equal to len.
Throws:
IOException
readInt
int readInt()
throws IOException
Reads four input bytes and returns an int value. Let a be the first byte read, b be the
second byte, c be the third byte, and d be the fourth byte. The value returned is: (((a
0xff) 24) | ((b 0xff) 16) | ((c 0xff) 8) | (d 0xff)) This method is suitable for reading bytes
written by the writeInt method of interface DataOutput.
Throws:
IOException
readLong
long readLong()
throws IOException
Reads eight input bytes and returns a long value. Let a be the first byte read, b be the
second byte, c be the third byte, d be the fourth byte, e be the fifth byte, f be the sixth
byte, g be the seventh byte, and h be the eighth byte. The value returned is:
(((long)(a 0xff) 56) | ((long)(b 0xff) 48) | ((long)(c 0xff) 40) | ((long)(d 0xff) 32) |
((long)(e 0xff) 24) | ((long)(f 0xff) 16) | ((long)(g 0xff) 8) | ((long)(h 0xff))) This method
is suitable for reading bytes written by the writeLong method of interface DataOutput.
Throws:
IOException
readShort
short readShort()
throws IOException
Reads two input bytes and returns a short value. Let a be the first byte read and b be
the second byte. The value returned is: (short)((a 8) | (b 0xff)) This method is suitable
for reading the bytes written by the writeShort method of interface DataOutput.
Throws:
IOException
readUnsignedByte
int readUnsignedByte()
throws IOException
Method Detail
631
readUnsignedShort
int readUnsignedShort()
throws IOException
Reads two input bytes, zero-extends it to type int, and returns an int value in the
range 0 through 65535. Let a be the first byte read and b be the second byte. The
value returned is: (((a 0xff) 8) | (b 0xff)) This method is suitable for reading the bytes
written by the writeShort method of interface DataOutput if the argument to writeShort
was intended to be a value in the range 0 through 65535.
Throws:
IOException
readUTF
String readUTF()
throws IOException
Reads in a string that has been encoded using a modified UTF-8 format. The general
contract of readUTF is that it reads a representation of a Unicode character string
encoded in Java modified UTF-8 format; this string of characters is then returned as a
String. First, two bytes are read and used to construct an unsigned 16-bit integer in
exactly the manner of the readUnsignedShort method . This integer value is called
the UTF length and specifies the number of additional bytes to be read. These bytes
are then converted to characters by considering them in groups. The length of each
group is computed from the value of the first byte of the group. The byte following a
group, if any, is the first byte of the next group. If the first byte of a group matches the
bit pattern 0xxxxxxx (where x means "may be 0 or 1"), then the group consists of just
that byte. The byte is zero-extended to form a character. If the first byte of a group
matches the bit pattern 110xxxxx, then the group consists of that byte a and a second
byte b. If there is no byte b (because byte a was the last of the bytes to be read), or if
byte b does not match the bit pattern 10xxxxxx, then a UTFDataFormatException is
thrown. Otherwise, the group is converted to the character: (char)(((a 0x1F) 6) | (b
0x3F)) If the first byte of a group matches the bit pattern 1110xxxx, then the group
consists of that byte a and two more bytes b and c. If there is no byte c (because byte
a was one of the last two of the bytes to be read), or either byte b or byte c does not
match the bit pattern 10xxxxxx, then a UTFDataFormatException is thrown.
Otherwise, the group is converted to the character: (char)(((a 0x0F) 12) | ((b 0x3F) 6)
| (c 0x3F)) If the first byte of a group matches the pattern 1111xxxx or the pattern
10xxxxxx, then a UTFDataFormatException is thrown. If end of file is encountered at
any time during this entire process, then an EOFException is thrown. After every
group has been converted to a character by this process, the characters are
gathered, in the same order in which their corresponding groups were read from the
input stream, to form a String, which is returned. The writeUTF method of interface
DataOutput may be used to write data that is suitable for reading by this method.
Throws:
IOException
skipBytes
int skipBytes(int n)
throws IOException
Makes an attempt to skip over n bytes of data from the input stream, discarding the
skipped bytes. However, it may skip over some smaller number of bytes, possibly
zero. This may result from any of a number of conditions; reaching end of file before
n bytes have been skipped is only one possibility. This method never throws an
EOFException. The actual number of bytes skipped is returned.
Throws:
IOException
Method Detail
632
Class ByteArrayOutputStream
java.lang.Object
java.io.OutputStream
java.io.ByteArrayOutputStream
All Implemented Interfaces:
AutoCloseable
public class
extends OutputStream
This class implements an output stream in which the data is written into a byte array. The buffer
automatically grows as data is written to it. The data can be retrieved using toByteArray() and
toString(). Since: JDK1.0, CLDC 1.0
Field Summary
Modifier and Type
protected byte[]
protected int
Constructor Summary
Constructor and Description
ByteArrayOutputStream()
Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
Method Summary
Modifier and
Type
void
Closes this output stream and releases any system resources associated
with this stream.
reset()
void
int
byte[]
Resets the count field of this byte array output stream to zero, so that all
currently accumulated output in the output stream is discarded.
size()
String
Converts the buffer's contents into a string, translating bytes into characters
according to the platform's default character encoding.
write(byte[] b, int off, int len)
void
Writes len bytes from the specified byte array starting at offset off to this byte
array output stream.
void
write(int b)
Class ByteArrayOutputStream
633
Field Detail
buf
protected byte[] buf
Constructor Detail
ByteArrayOutputStream
public ByteArrayOutputStream()
Creates a new byte array output stream. The buffer capacity is initially 32 bytes,
though its size increases if necessary.
ByteArrayOutputStream
public ByteArrayOutputStream(int size)
Creates a new byte array output stream, with a buffer capacity of the specified size,
in bytes. size - the initial size. - if size is negative.
Method Detail
close
public void close()
throws IOException
Closes this output stream and releases any system resources associated with this
stream. A closed stream cannot perform output operations and cannot be reopened.
Specified by:
close in interface AutoCloseable
Overrides:
close in class OutputStream
Throws:
IOException
reset
public void reset()
Resets the count field of this byte array output stream to zero, so that all currently
accumulated output in the output stream is discarded. The output stream can be used
again, reusing the already allocated buffer space.
Method Summary
634
Creates a newly allocated byte array. Its size is the current size of this output stream
and the valid contents of the buffer have been copied into it.
toString
public String toString()
Converts the buffer's contents into a string, translating bytes into characters
according to the platform's default character encoding.
Overrides:
toString in class Object
write
public void write(byte[] b,
int off,
int len)
Writes len bytes from the specified byte array starting at offset off to this byte array
output stream.
Overrides:
write in class OutputStream
write
public void write(int b)
Method Detail
635
Class ByteArrayInputStream
java.lang.Object
java.io.InputStream
java.io.ByteArrayInputStream
All Implemented Interfaces:
AutoCloseable
public class
extends InputStream
A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the
stream. An internal counter keeps track of the next byte to be supplied by the read method. Since:
JDK1.0, CLDC 1.0
Field Summary
Modifier and
Type
protected byte[]
protected int
protected int
protected int
The index one greater than the last valid character in the input stream
buffer.
mark
The index of the next character to read from the input stream buffer.
Constructor Summary
Constructor and Description
ByteArrayInputStream(byte[] buf)
Method Summary
Modifier and
Type
int
Returns the number of bytes that can be read from this input stream
without blocking.
close()
void
void
boolean
int
Class ByteArrayInputStream
Closes this input stream and releases any system resources associated
with the stream.
mark(int readAheadLimit)
636
int
Reads up to len bytes of data into an array of bytes from this input stream.
reset()
void
long
Field Detail
buf
protected byte[] buf
An array of bytes that was provided by the creator of the stream. Elements buf[0]
through buf[count-1] are the only bytes that can ever be read from the stream;
element buf[pos] is the next byte to be read.
count
protected int count
The index one greater than the last valid character in the input stream buffer. This
value should always be nonnegative and not larger than the length of buf. It is one
greater than the position of the last byte within buf that can ever be read from the
input stream buffer.
mark
protected int mark
The index of the next character to read from the input stream buffer. This value
should always be nonnegative and not larger than the value of count. The next byte
to be read from the input stream buffer will be buf[pos].
Constructor Detail
ByteArrayInputStream
public ByteArrayInputStream(byte[] buf)
Creates a ByteArrayInputStream so that it uses buf as its buffer array. The buffer
array is not copied. The initial value of pos is 0 and the initial value of count is the
length of buf. buf - the input buffer.
Method Summary
637
Creates ByteArrayInputStream that uses buf as its buffer array. The initial value of
pos is offset and the initial value of count is offset+length. The buffer array is not
copied. Note that if bytes are simply read from the resulting input stream, elements
buf[pos] through buf[pos+len-1] will be read; however, if a reset operation is
performed, then bytes buf[0] through buf[pos-1] will then become available for input.
buf - the input buffer.offset - the offset in the buffer of the first byte to read.length - the
maximum number of bytes to read from the buffer.
Method Detail
available
public int available()
Returns the number of bytes that can be read from this input stream without blocking.
The value returned is count - pos, which is the number of bytes remaining to be read
from the input buffer.
Overrides:
available in class InputStream
close
public void close()
throws IOException
Closes this input stream and releases any system resources associated with the
stream.
Specified by:
close in interface AutoCloseable
Overrides:
close in class InputStream
Throws:
IOException
mark
public void mark(int readAheadLimit)
Set the current marked position in the stream. ByteArrayInputStream objects are
marked at position zero by default when constructed. They may be marked at another
position within the buffer by this method.
Overrides:
mark in class InputStream
markSupported
public boolean markSupported()
Reads the next byte of data from this input stream. The value byte is returned as an
int in the range 0 to 255. If no byte is available because the end of the stream has
been reached, the value -1 is returned. This read method cannot block.
Specified by:
read in class InputStream
Constructor Detail
638
Reads up to len bytes of data into an array of bytes from this input stream. If pos
equals count, then -1 is returned to indicate end of file. Otherwise, the number k of
bytes read is equal to the smaller of len and count-pos. If k is positive, then bytes
buf[pos] through buf[pos+k-1] are copied into b[off] through b[off+k-1] in the manner
performed by System.arraycopy. The value k is added into pos and k is returned.
This read method cannot block.
Overrides:
read in class InputStream
reset
public void reset()
Resets the buffer to the marked position. The marked position is the beginning unless
another position was marked. The value of pos is set to 0.
Overrides:
reset in class InputStream
skip
public long skip(long n)
Skips n bytes of input from this input stream. Fewer bytes might be skipped if the end
of the input stream is reached. The actual number k of bytes to be skipped is equal to
the smaller of n and count-pos. The value k is added into pos and k is returned.
Overrides:
skip in class InputStream
Method Detail
639
Class XMLWriter
java.lang.Object
com.codename1.xml.XMLWriter
public class
extends Object
Constructor Summary
Constructor and Description
XMLWriter(boolean encodeText)
Method Summary
Modifier and Type
void
Constructor Detail
XMLWriter
public XMLWriter(boolean encodeText)
Method Detail
writeXML
public void writeXML(Writer writer,
Element element)
throws IOException
Writes the XML of an Element to a Writer. Note: may output invalid XML if you
created text Elements using un-escaped Strings.
Parameters:
writer - The Writer to which the XML will be written.
element - The element whose XML will be written.
Throws:
IOException - if a write operation fails.
Class XMLWriter
640
Class XMLParser
java.lang.Object
com.codename1.xml.XMLParser
Direct Known Subclasses:
HTMLParser
public class
extends Object
Parser class used to parse an XML document into a DOM object (Element). This code was originally
developed to parse HTML and as a result isn't as strict as most XML parsers and can parse many
HTML documents out of the box. The parser is mostly stateful (although it does have an event
callback API as well), its modeled closely to the Java DOM API's.
In this sample an XML hierarchy is displayed using a Tree:
Constructor Summary
Constructor and Description
XMLParser()
Method Summary
Modifier
and Type
void
Method Detail
Adds the given symbols array to the user defined char entities table with the
startcode provided as the code of the first string, startcode+1 for the second etc.
641
protected
void
Adds the given symbol and code to the user defined char entities table
http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
attribute(String tag, String attributeName, String value)
Invoked for every attribute value of the givne tag This callback method is invoked
only on the eventParser.
endTag(String tag)
Invoked when a tag ends This callback method is invoked only on the
eventParser.
eventParser(Reader r)
void
The event parser requires deriving this class and overriding callback methods to
work effectively.
protected getSupportedStandardName()
String
Returns a string identifying the
isCaseSensitive()
boolean
Sets the parser to be case sensitive and retain case, otherwise it will convert all
data to lower case
isSupported(Element element)
protected
boolean
This is the entry point for parsing a document and the only non-private member
method in this class
in the XML.
elements .
setCaseSensitive(boolean caseSensitive)
void
Sets the parser to be case sensitive and retain case, otherwise it will convert all
data to lower case
void
setIncludeWhitespacesBetweenTags(boolean include)
void
protected
boolean
protected
boolean
setParserCallback(ParserCallback parserCallback)
Sets the specified callback to serve as the callback for parsing errors
shouldEvaluate(Element element)
Checks if this element should be evaluated by the parser This can be overriden
by subclasses to skip certain elements
startTag(String tag)
Invoked when a tag is opened, this method should return true to process the tag
or return false to skip the tag.
Method Summary
642
Constructor Detail
XMLParser
public XMLParser()
Method Detail
getSupportedStandardName
protected String getSupportedStandardName()
Returns a string identifying the document type this parser supports. This should be
overriden by subclassing parsers.
Returns:
a string identifying the document type this parser supports.
addCharEntity
public void addCharEntity(String symbol,
int code)
Adds the given symbol and code to the user defined char entities table
http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
Parameters:
symbol - The symbol to add
code - The symbol's code
addCharEntitiesRange
public void addCharEntitiesRange(String[] symbols,
int startcode)
Adds the given symbols array to the user defined char entities table with the
startcode provided as the code of the first string, startcode+1 for the second etc.
Some strings in the symbols array may be null thus skipping code numbers.
Parameters:
symbols - The symbols to add
startcode - The symbol's code
convertCharEntity
protected String convertCharEntity(String charEntity)
Converts a char entity to the matching character. This handles both numbered and
symbol char entities (The latter is done via getCharEntityCode)
Parameters:
charEntity - The char entity to convert
Returns:
A string containing a single char, or the original char entity string (with & and
;) if the char entity couldn't be resolved
parse
public Element parse(Reader is)
This is the entry point for parsing a document and the only non-private member
method in this class
Parameters:
is - The InputStream containing the XML
Returns:
643
Creates a new element. This should be overriden by parsers that use a subclass of
Element.
Parameters:
name - The new element's name
Returns:
a new instance of the element
createNewTextElement
protected Element createNewTextElement(String text)
Creates a new text element. This should be overriden by parsers that use a subclass
of Element.
Parameters:
text - The new element's text
Returns:
a new instance of the element
setIncludeWhitespacesBetweenTags
public void setIncludeWhitespacesBetweenTags(boolean include)
eventParser
public void eventParser(Reader r)
throws IOException
The event parser requires deriving this class and overriding callback methods to work
effectively. To stop the event parser in mid way a callback can simply throw an
IOException on purpose.
Parameters:
r - the reader from which the data should be parsed
Throws:
IOException - if an exception is thrown by the reader
textElement
protected void textElement(String text)
Invoked when the event parser encounters a text element. This callback method is
invoked only on the eventParser.
Parameters:
text - the text encountered
startTag
protected boolean startTag(String tag)
Invoked when a tag is opened, this method should return true to process the tag or
return false to skip the tag. This callback method is invoked only on the eventParser.
Parameters:
tag - the tag name
Returns:
true to process the tag, false to skip the tag
endTag
protected void endTag(String tag)
Invoked when a tag ends This callback method is invoked only on the eventParser.
Parameters:
tag - the tag name
attribute
protected void attribute(String tag,
String attributeName,
String value)
Method Detail
644
Parses tags content, accumulating text and child elements . Upon bumping a start tag
character it calls the parseTag method. This method is called at first from the parse
method, and later on from parseTag (which creates the recursion).
Parameters:
element - The current parent element
is - The InputStream containing the XML
Throws:
IOException - if an I/O error in the stream is encountered
isWhiteSpace
protected boolean isWhiteSpace(char ch)
Checks if the specified character is a white space or not. Exposed to packaage since
used by HTMLComponent as well
Parameters:
ch - The character to check
Returns:
true if the character is a white space, false otherwise
parseTag
protected Element parseTag(Reader is)
throws IOException
This method collects the tag name and all of its attributes. For comments and XML
declarations this will call the parseCommentOrXMLDeclaration method. Note that this
method returns an Element with a name and attrbutes, but not its content/children
which will be done by parseTagContent
Parameters:
is - The InputStream containing the XML
Returns:
The parsed element
Throws:
IOException - if an I/O error in the stream is encountered
parseCommentOrXMLDeclaration
protected Element parseCommentOrXMLDeclaration(Reader is,
String endTag)
throws IOException
This utility method is used to parse comments and XML declarations in the XML. The
comment/declaration is returned as an Element, but is flagged as a comment since
both comments and XML declarations are not part of the XML DOM. This method can
be overridden to process specific XML declarations
Parameters:
is - The inputstream
endTag - The endtag to look for
Returns:
An Element representing the comment or XML declartaion
Throws:
IOException
isEmptyTag
protected boolean isEmptyTag(String tagName)
Method Detail
645
Returns true if this element is supported, false otherwise In XMLParser this always
returns true, but subclasses can determine if an element is supported in their context
according to its name etc. Unsupported elements will be skipped by the parser and
excluded from the resulting DOM object
Parameters:
element - The element to check
Returns:
true if the element is supported, false otherwise
shouldEvaluate
protected boolean shouldEvaluate(Element element)
Checks if this element should be evaluated by the parser This can be overriden by
subclasses to skip certain elements
Parameters:
element - The element to check
Returns:
true if this element should be evaluated by the parser, false to skip it
completely
setParserCallback
public void setParserCallback(ParserCallback parserCallback)
Sets the specified callback to serve as the callback for parsing errors
Parameters:
parserCallback - The callback to use for parsing errors
isCaseSensitive
public boolean isCaseSensitive()
Sets the parser to be case sensitive and retain case, otherwise it will convert all data
to lower case
Returns:
the caseSensitive
setCaseSensitive
public void setCaseSensitive(boolean caseSensitive)
Sets the parser to be case sensitive and retain case, otherwise it will convert all data
to lower case
Method Detail
646
Method Detail
647
Interface ParserCallback
All Known Subinterfaces:
HTMLCallback
All Known Implementing Classes:
Ads, DefaultHTMLCallback, RSSService
public interface
Field Summary
Modifier
and Type
static int
static int
Error code denoting that an invalid attribute value was found in the XML
ERROR_ATTRIBUTE_NOT_SUPPORTED
Error code denoting that an unsupported attribute was found in the XML
ERROR_ENCODING
static int
static int
static int
Error code denoting that the encoding the page needed according to its charset
(usually specified in the content-type response header) is unsupported in the
device
ERROR_MULTIPLE_ROOTS
Error code denoting that the document had more than one root element
ERROR_NO_CLOSE_TAG
Error code denoting that a tag was not closed properly in the XML
ERROR_NO_ROOTS
static int
static int
static int
static int
Error code denoting that the document had no root element at all (empty
document or seriously malformed XML)
ERROR_TAG_NOT_SUPPORTED
Error code denoting that an unsupported tag was found in the XML
ERROR_UNEXPECTED_CHARACTER
Error code denoting that the parser bumped into an unexpected character
ERROR_UNEXPECTED_TAG_CLOSING
static int
Error code denoting that an invalid character entity was found A character
entity is XML codes that start with an ampersand and end with semicolon and
denote special/reserved chars
Method Summary
Modifier and
Type
boolean
Field Detail
Interface ParserCallback
648
Error code denoting that an unsupported tag was found in the XML
See Also:
Constant Field Values
ERROR_ATTRIBUTE_NOT_SUPPORTED
static final int ERROR_ATTRIBUTE_NOT_SUPPORTED
Error code denoting that an unsupported attribute was found in the XML
See Also:
Constant Field Values
ERROR_ATTIBUTE_VALUE_INVALID
static final int ERROR_ATTIBUTE_VALUE_INVALID
Error code denoting that an invalid attribute value was found in the XML
See Also:
Constant Field Values
ERROR_NO_CLOSE_TAG
static final int ERROR_NO_CLOSE_TAG
Error code denoting that a tag was not closed properly in the XML
See Also:
Constant Field Values
ERROR_UNRECOGNIZED_CHAR_ENTITY
static final int ERROR_UNRECOGNIZED_CHAR_ENTITY
Error code denoting that an invalid character entity was found A character entity is
XML codes that start with an ampersand and end with semicolon and denote
special/reserved chars
See Also:
Constant Field Values
ERROR_UNEXPECTED_TAG_CLOSING
static final int ERROR_UNEXPECTED_TAG_CLOSING
Error code denoting that the parser bumped into an unexpected character
See Also:
Constant Field Values
ERROR_MULTIPLE_ROOTS
static final int ERROR_MULTIPLE_ROOTS
Error code denoting that the document had more than one root element
See Also:
Constant Field Values
ERROR_NO_ROOTS
static final int ERROR_NO_ROOTS
Error code denoting that the document had no root element at all (empty document or
seriously malformed XML)
See Also:
Constant Field Values
Field Detail
649
Error code denoting that the encoding the page needed according to its charset
(usually specified in the content-type response header) is unsupported in the device
See Also:
Constant Field Values
Method Detail
parsingError
boolean parsingError(int errorId,
String tag,
String attribute,
String value,
String description)
Called when encountering an error while parsing the XML document. When
implementing this, the developer should return true if the error should be ignored and
the document needs to be further parsed, or false to stop parsing and issue an error
to the user Note that this method is always called NOT on the EDT thread.
Parameters:
errorId - The error ID, one of the ERROR_* constants
tag - The tag in which the error occured (Can be null for non-tag related
errors)
attribute - The attribute in which the error occured (Can be null for
non-attribute related errors)
value - The value in which the error occured (Can be null for non-value
related errors)
description - A verbal description of the error
Returns:
true to continue parsing, false to stop
Field Detail
650
Class Element
java.lang.Object
com.codename1.xml.Element
All Implemented Interfaces:
Iterable<Element>
Direct Known Subclasses:
HTMLElement
public class
extends Object
implements Iterable<Element>
The Element class defines a single XML element with its attributes and children. Due to its hierarchial
nature, this class can be used for a single "leaf" Element, for more complex elements (with child
elements), and up to describing the entire document.
Field Summary
Modifier and
Type
static int
A constant that can be used for the get descendants methods to denote
infinite recursion
Constructor Summary
Modifier
protected
Constructs an Element (or a text element) with the specified name or text.
Method Summary
Modifier and Type
void
boolean
String
int
Hashtable
Element
Method Detail
Returns the attribute value by its name (or null if it wasn't defined for
this element)
getAttributeAsInt(String name, int def)
651
getChildIndex(Element child)
protected Vector
Vector
Vector
Vector
Vector
Element
Element
int
Element
String
String
Vector
Vector
Vector
Deprecated.
this uses the old vector API instead of the more modern Collection/List
getChildrenByTagName(String name)
Returns all descendants with the specified tag name and the none
empty attribute
getElementById(String id)
hasTextChild()
Iterator<Element>
Iterable for children of this entry making tree walking easier, this makes
for(Element child : base) {} possible
removeAttribute(Object id)
protected void
void
void
void
protected void
int
Method Summary
652
protected void
protected void
Deprecated.
this uses the old vector API instead of the more modern Collection/List
setParent(Element parent)
Sets the text of this element to the specified string (For text elements
only)
void
protected void
setTextElement(boolean textElement)
String
Field Detail
DEPTH_INFINITE
public static final int DEPTH_INFINITE
A constant that can be used for the get descendants methods to denote infinite
recursion
See Also:
Constant Field Values
Constructor Detail
Element
protected Element()
Constructs and Element without specifying a name This can be used by subclasses
that do not require name assigments.
Element
public Element(String tagName)
Constructs an Element (or a text element) with the specified name or text.
Parameters:
tagName - The tag name, or in the case of a text element the element's text
isTextElement - true for a text element, false otherwise
Method Detail
653
Adds the specified attribute and value to this Element if it is supported for the
Element and has a valid value. This method allows creating a key that is non-string to
be used by subclasses that optimize attributes retrieval
Parameters:
id - The attribute ID
value - The attribute value
addChild
public void addChild(Element childElement)
Adds the specified Element as a child to this element. If the specified element was
found to be unsupported (i.e. it's ID is TAG_UNSUPPORTED, it is not added.
Parameters:
childElement - The child element
setParent
protected void setParent(Element parent)
Method Detail
654
Deprecated. this uses the old vector API instead of the more modern Collection/List
Returns the internal children vector
Returns:
the children vector
setChildren
protected void setChildren(Vector children)
Deprecated. this uses the old vector API instead of the more modern Collection/List
Sets the children vector of this Element
Parameters:
children - The vector to set as this Element's children
setTagName
protected void setTagName(String name)
Returns all descendants with the specified tag name and the none empty attribute
Method Detail
655
....
DEPTH_INFINITE - for all descendants)
Returns:
A vector containing descendants with the specified tag name
getDescendantsByTagName
public Vector getDescendantsByTagName(String name,
int depth)
Method Detail
656
Returns true if the specified element is contained in this element's hierarchy (meaning
it is one of its descendants)
Parameters:
element - The element to look for
Returns:
true if this element contains the specified element, false otherwise
setAttribute
public int setAttribute(String attribute,
String value)
Adds the specified attribute and value to this Element if it is supported for the
Element and has a valid value.
Parameters:
attribute - The attribute's name
value - The attribute's value
Returns:
a positive error code or -1 if attribute is supported and valid
removeAttribute
public void removeAttribute(String attribute)
Removes the specified attribute if it exist in this Element This method allows creating
a key that is non-string to be used by subclasses that optimize attributes retrieval
Parameters:
id - The attribute ID
getAttributeAsInt
public int getAttributeAsInt(String name,
int def)
Returns the attribute value by its name (or null if it wasn't defined for this element)
Parameters:
name - The attribute id
Returns:
the attribute value by its name (or null if it wasn't defined for this element)
Method Detail
657
Sets the text of this element to the specified string (For text elements only)
Parameters:
str - The text to set
Throws:
IllegalStateException - if this is not a text element
toString
public String toString()
Method Detail
658
Iterable for children of this entry making tree walking easier, this makes for(Element
child : base) {} possible
Specified by:
iterator in interface Iterable<Element>
Returns:
the children iterator
Method Detail
659
Class StringReader
java.lang.Object
java.io.Reader
com.codename1.util.regex.StringReader
All Implemented Interfaces:
AutoCloseable
public class
extends Reader
Field Summary
Constructor Summary
Constructor and Description
StringReader(String str)
Method Summary
Modifier and Type
void
int
int
String
readLine()
boolean
ready()
Constructor Detail
StringReader
public StringReader(String str)
Class StringReader
660
Detail
read
public int read()
ready
public boolean ready()
Method Detail
661
Class StringCharacterIterator
java.lang.Object
com.codename1.util.regex.StringCharacterIterator
All Implemented Interfaces:
CharacterIterator
Constructor Summary
Constructor and Description
StringCharacterIterator(String src)
Method Summary
Modifier and Type
char
charAt(int pos)
boolean
isEnd(int pos)
String
substring(int beginIndex)
String
Constructor Detail
StringCharacterIterator
public StringCharacterIterator(String src)
Parameters:
src - - encapsulated String
Method Detail
substring
public String substring(int beginIndex,
int endIndex)
Specified by:
substring in interface CharacterIterator
Returns:
a substring
Class StringCharacterIterator
662
Specified by:
substring in interface CharacterIterator
Returns:
a substring
charAt
public char charAt(int pos)
Specified by:
charAt in interface CharacterIterator
Returns:
a character at the specified position.
isEnd
public boolean isEnd(int pos)
Specified by:
isEnd
in interface CharacterIterator
Returns:
true
Method Detail
iff if the specified index is after the end of the character stream
663
Class StreamCharacterIterator
java.lang.Object
com.codename1.util.regex.StreamCharacterIterator
All Implemented Interfaces:
CharacterIterator
Constructor Summary
Constructor and Description
StreamCharacterIterator(InputStream is)
Method Summary
Modifier and Type
char
charAt(int pos)
boolean
isEnd(int pos)
String
substring(int beginIndex)
String
Constructor Detail
StreamCharacterIterator
public StreamCharacterIterator(InputStream is)
Parameters:
is - an InputStream, which is parsed
Method Detail
substring
public String substring(int beginIndex,
int endIndex)
Specified by:
substring in interface CharacterIterator
Returns:
a substring
Class StreamCharacterIterator
664
Specified by:
substring in interface CharacterIterator
Returns:
a substring
charAt
public char charAt(int pos)
Specified by:
charAt in interface CharacterIterator
Returns:
a character at the specified position.
isEnd
public boolean isEnd(int pos)
Specified by:
isEnd
in interface CharacterIterator
Returns:
true
Method Detail
iff if the specified index is after the end of the character stream
665
Class ReaderCharacterIterator
java.lang.Object
com.codename1.util.regex.ReaderCharacterIterator
All Implemented Interfaces:
CharacterIterator
Constructor Summary
Constructor and Description
ReaderCharacterIterator(Reader reader)
Method Summary
Modifier and Type
char
charAt(int pos)
boolean
isEnd(int pos)
String
substring(int beginIndex)
String
Constructor Detail
ReaderCharacterIterator
public ReaderCharacterIterator(Reader reader)
Parameters:
reader
Method Detail
substring
public String substring(int beginIndex,
int endIndex)
Specified by:
substring in interface CharacterIterator
Returns:
a substring
Class ReaderCharacterIterator
666
Specified by:
substring in interface CharacterIterator
Returns:
a substring
charAt
public char charAt(int pos)
Specified by:
charAt in interface CharacterIterator
Returns:
a character at the specified position.
isEnd
public boolean isEnd(int pos)
Specified by:
isEnd
in interface CharacterIterator
Returns:
true
Method Detail
iff if the specified index is after the end of the character stream
667
Class REUtil
java.lang.Object
com.codename1.util.regex.REUtil
public class
extends Object
This is a class that contains utility helper methods for this package.
Version:
$Id: REUtil.java 518156 2007-03-14 14:31:26Z vgritsenko $
Constructor Summary
Constructor and Description
REUtil()
Method Summary
Modifier and Type
static RE
static RE
Constructor Detail
REUtil
public REUtil()
Method Detail
createRE
public static RE createRE(String expression,
int matchFlags)
throws RESyntaxException
Class REUtil
668
Method Detail
669
Class RESyntaxException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
com.codename1.util.regex.RESyntaxException
public class
extends RuntimeException
Exception thrown to indicate a syntax error in a regular expression. This is a non-checked exception
because you should only have problems compiling a regular expression during development. If you
are making regular expresion programs dynamically then you can catch it if you wish. But should not
be forced to.
Version:
$Id: RESyntaxException.java 518156 2007-03-14 14:31:26Z vgritsenko $
Constructor Summary
Constructor and Description
RESyntaxException(String s)
Constructor.
Method Summary
Constructor Detail
RESyntaxException
public RESyntaxException(String s)
Constructor.
Parameters:
s - Further description of the syntax error
Class RESyntaxException
670
Class REProgram
java.lang.Object
com.codename1.util.regex.REProgram
public class
extends Object
A class that holds compiled regular expressions. You should not need to work directly with this class.
Version:
$Id: REProgram.java 518156 2007-03-14 14:31:26Z vgritsenko $
See Also:
RE, RECompiler
Constructor Summary
Constructor and Description
REProgram(char[] instruction)
Method Summary
Modifier and
Type
char[]
char[]
void
Constructor Detail
REProgram
public REProgram(char[] instruction)
Constructor Detail
671
Method Detail
getInstructions
public char[] getInstructions()
Returns a copy of the current regular expression program in a character array that is
exactly the right length to hold the program. If there is no program compiled yet,
getInstructions() will return null.
Returns:
A copy of the current compiled RE program
setInstructions
public void setInstructions(char[] instruction,
int lenInstruction)
Sets a new regular expression program to run. It is this method which performs any
special compile-time search optimizations. Currently only two optimizations are in
place - one which checks for backreferences (so that they can be lazily allocated) and
another which attempts to find an prefix anchor string so that substantial amounts of
input can potentially be skipped without running the actual program.
Parameters:
instruction - Program instruction buffer
lenInstruction - Length of instruction buffer in use
getPrefix
public char[] getPrefix()
Constructor Detail
672
Class REDebugCompiler
java.lang.Object
com.codename1.util.regex.RECompiler
com.codename1.util.regex.REDebugCompiler
public class
extends RECompiler
A subclass of RECompiler which can dump a regular expression program for debugging purposes.
Constructor Summary
Constructor and Description
REDebugCompiler()
Method Summary
Modifier and Type
void
void
Constructor Detail
REDebugCompiler
public REDebugCompiler()
Method Detail
dumpProgram
public void dumpProgram(PrintStream p)
Method Detail
673
Class RECompiler
java.lang.Object
com.codename1.util.regex.RECompiler
Direct Known Subclasses:
REDebugCompiler
public class
extends Object
A regular expression compiler class. This class compiles a pattern string into a regular expression
program interpretable by the RE evaluator class. The 'recompile' command line tool uses this
compiler to pre-compile regular expressions for use with RE. For a description of the syntax accepted
by RECompiler and what you can do with regular expressions, see the documentation for the RE
matcher class.
Version:
$Id: RECompiler.java 518156 2007-03-14 14:31:26Z vgritsenko $
See Also:
RE
Constructor Summary
Constructor and Description
RECompiler()
Constructor.
Method Summary
Modifier and
Type
REProgram
Constructor Detail
RECompiler
public RECompiler()
Method Detail
compile
public REProgram compile(String pattern)
throws RESyntaxException
Method Detail
674
Method Detail
675
Class RECharacter
java.lang.Object
com.codename1.util.regex.RECharacter
public class
extends Object
Field Summary
Modifier and Type
static byte
COMBINING_SPACING_MARK
static byte
CONNECTOR_PUNCTUATION
static byte
CONTROL
static byte
CURRENCY_SYMBOL
static byte
DASH_PUNCTUATION
static byte
DECIMAL_DIGIT_NUMBER
static byte
ENCLOSING_MARK
static byte
END_PUNCTUATION
static byte
FORMAT
static byte
LETTER_NUMBER
static byte
LINE_SEPARATOR
static byte
LOWERCASE_LETTER
static byte
MATH_SYMBOL
static byte
MODIFIER_LETTER
static byte
MODIFIER_SYMBOL
static byte
NON_SPACING_MARK
static byte
OTHER_LETTER
static byte
OTHER_NUMBER
static byte
OTHER_PUNCTUATION
static byte
OTHER_SYMBOL
static byte
PARAGRAPH_SEPARATOR
static byte
PRIVATE_USE
static byte
SPACE_SEPARATOR
static byte
START_PUNCTUATION
static byte
SURROGATE
static byte
TITLECASE_LETTER
static byte
UNASSIGNED
static byte
UPPERCASE_LETTER
Constructor Summary
Constructor and Description
RECharacter()
Class RECharacter
676
Summary
static byte
getType(char c)
static boolean
isDigit(char c)
static boolean
isJavaIdentifierPart(char c)
static boolean
isJavaIdentifierStart(char c)
static boolean
isLetter(char c)
static boolean
isLetterOrDigit(char c)
static boolean
isSpaceChar(char c)
static boolean
isWhitespace(char c)
static char
toLowerCase(char c)
static char
toUpperCase(char c)
Field Detail
UNASSIGNED
public static final byte UNASSIGNED
See Also:
Constant Field Values
UPPERCASE_LETTER
public static final byte UPPERCASE_LETTER
See Also:
Constant Field Values
LOWERCASE_LETTER
public static final byte LOWERCASE_LETTER
See Also:
Constant Field Values
TITLECASE_LETTER
public static final byte TITLECASE_LETTER
See Also:
Constant Field Values
MODIFIER_LETTER
public static final byte MODIFIER_LETTER
See Also:
Constant Field Values
OTHER_LETTER
public static final byte OTHER_LETTER
See Also:
Constant Field Values
Method Summary
677
See Also:
Constant Field Values
ENCLOSING_MARK
public static final byte ENCLOSING_MARK
See Also:
Constant Field Values
COMBINING_SPACING_MARK
public static final byte COMBINING_SPACING_MARK
See Also:
Constant Field Values
DECIMAL_DIGIT_NUMBER
public static final byte DECIMAL_DIGIT_NUMBER
See Also:
Constant Field Values
LETTER_NUMBER
public static final byte LETTER_NUMBER
See Also:
Constant Field Values
OTHER_NUMBER
public static final byte OTHER_NUMBER
See Also:
Constant Field Values
SPACE_SEPARATOR
public static final byte SPACE_SEPARATOR
See Also:
Constant Field Values
LINE_SEPARATOR
public static final byte LINE_SEPARATOR
See Also:
Constant Field Values
PARAGRAPH_SEPARATOR
public static final byte PARAGRAPH_SEPARATOR
See Also:
Constant Field Values
CONTROL
public static final byte CONTROL
See Also:
Constant Field Values
FORMAT
public static final byte FORMAT
See Also:
Constant Field Values
Field Detail
678
See Also:
Constant Field Values
SURROGATE
public static final byte SURROGATE
See Also:
Constant Field Values
DASH_PUNCTUATION
public static final byte DASH_PUNCTUATION
See Also:
Constant Field Values
START_PUNCTUATION
public static final byte START_PUNCTUATION
See Also:
Constant Field Values
END_PUNCTUATION
public static final byte END_PUNCTUATION
See Also:
Constant Field Values
CONNECTOR_PUNCTUATION
public static final byte CONNECTOR_PUNCTUATION
See Also:
Constant Field Values
OTHER_PUNCTUATION
public static final byte OTHER_PUNCTUATION
See Also:
Constant Field Values
MATH_SYMBOL
public static final byte MATH_SYMBOL
See Also:
Constant Field Values
CURRENCY_SYMBOL
public static final byte CURRENCY_SYMBOL
See Also:
Constant Field Values
MODIFIER_SYMBOL
public static final byte MODIFIER_SYMBOL
See Also:
Constant Field Values
OTHER_SYMBOL
public static final byte OTHER_SYMBOL
See Also:
Constant Field Values
Field Detail
679
Detail
RECharacter
public RECharacter()
Method Detail
toLowerCase
public static char toLowerCase(char c)
toUpperCase
public static char toUpperCase(char c)
isWhitespace
public static boolean isWhitespace(char c)
isDigit
public static boolean isDigit(char c)
isLetter
public static boolean isLetter(char c)
isLetterOrDigit
public static boolean isLetterOrDigit(char c)
isSpaceChar
public static boolean isSpaceChar(char c)
isJavaIdentifierStart
public static boolean isJavaIdentifierStart(char c)
isJavaIdentifierPart
public static boolean isJavaIdentifierPart(char c)
getType
public static byte getType(char c)
Constructor Detail
680
Class RE
java.lang.Object
com.codename1.util.regex.RE
public class
extends Object
Once you have done this, you can call either of the RE.match methods to perform matching on a
String. For example:
boolean matched = r.match("aaaab");
will cause the boolean matched to be set to true because the pattern "a*b" matches the string
"aaaab".
If you were interested in the number of a's which matched the first part of our example expression,
you could change the expression to "(a*)b". Then when you compiled the expression and matched it
against something like "xaaaab", you would get results like this:
RE r = new RE("(a*)b");
boolean matched = r.match("xaaaab");
// Compile expression
// Match against "xaaaab"
You can also refer to the contents of a parenthesized expression within a regular expression itself.
This is called a 'backreference'. The first backreference in a regular expression is denoted by \1, the
second by \2 and so on. So the expression:
([0-9]+)=\1
will match any string of the form n=n (like 0=0 or 2=2).
The full regular expression syntax accepted by RE is described here:
Characters
unicodeChar
\
\\
\0nnn
\xhh
Method Detail
681
Matches
Matches
Matches
Matches
Matches
Character Classes
[abc]
[a-zA-Z]
[^abc]
NOTE: Incomplete ranges will be interpreted as "starts from zero" or "ends with last character".
I.e. [-a] is the same as [\\u0000-a], and [a-] is the same as [a-\\uFFFF], [-] means "all characters".
Standard POSIX Character Classes
[:alnum:]
[:alpha:]
[:blank:]
[:cntrl:]
[:digit:]
[:graph:]
Alphanumeric characters.
Alphabetic characters.
Space and tab characters.
Control characters.
Numeric characters.
Characters that are printable and are also visible.
(A space is printable, but not visible, while an
`a' is both.)
Lower-case alphabetic characters.
Printable characters (characters that are not
control characters.)
Punctuation characters (characters that are not letter,
digits, control characters, or space characters).
Space characters (such as space, tab, and formfeed,
to name a few).
Upper-case alphabetic characters.
Characters that are hexadecimal digits.
[:lower:]
[:print:]
[:punct:]
[:space:]
[:upper:]
[:xdigit:]
Predefined Classes
.
\w
\W
\s
\S
\d
\D
Matches
Matches
Matches
Matches
Matches
Matches
Matches
Boundary Matchers
^
$
\b
\B
Matches
Matches
Matches
Matches
only
only
only
only
Matches
Matches
Matches
Matches
Matches
Matches
A
A
A
A
A
A
at
at
at
at
Greedy Closures
A*
A+
A?
A{n}
A{n,}
A{n,m}
Reluctant Closures
A*?
A+?
Class RE
682
Logical Operators
AB
A|B
(A)
(?:A)
Matches A followed by B
Matches either A or B
Used for subexpression grouping
Used for subexpression clustering (just like grouping but
no backrefs)
Backreferences
\1
\2
\3
\4
\5
\6
\7
\8
\9
Backreference
Backreference
Backreference
Backreference
Backreference
Backreference
Backreference
Backreference
Backreference
to
to
to
to
to
to
to
to
to
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
parenthesized
parenthesized
parenthesized
parenthesized
parenthesized
parenthesized
parenthesized
parenthesized
parenthesized
subexpression
subexpression
subexpression
subexpression
subexpression
subexpression
subexpression
subexpression
subexpression
All closure operators (+, *, ?, {m,n}) are greedy by default, meaning that they match as many
elements of the string as possible without causing the overall match to fail. If you want a closure to be
reluctant (non-greedy), you can simply follow it with a '?'. A reluctant closure will match as few
elements of the string as possible when finding matches. {m,n} closures don't currently support
reluctancy.
Line terminators
A line terminator is a one- or two-character sequence that marks the end of a line of the input
character sequence. The following are recognized as line terminators:
A newline (line feed) character ('\n'),
A carriage-return character followed immediately by a newline character ("\r\n"),
A standalone carriage-return character ('\r'),
A next-line character (' '),
A line-separator character (' '), or
A paragraph-separator character (' ).
RE runs programs compiled by the RECompiler class. But the RE matcher class does not include the
actual regular expression compiler for reasons of efficiency. You can construct a single RECompiler
object and re-use it to compile each expression. Similarly, you can change the program run by a given
matcher object at any time. However, RE and RECompiler are not threadsafe (for efficiency reasons,
and because requiring thread safety in this class is deemed to be a rare requirement), so you will
need to construct a separate compiler or matcher object for each thread (unless you do thread
synchronization yourself). Once expression compiled into the REProgram object, REProgram can be
safely shared across multiple threads and RE objects.
ISSUES:
com.weusours.util.re is not currently compatible with all standard POSIX regcomp flags
com.weusours.util.re does not support POSIX equivalence classes ([=foo=] syntax)
(I18N/locale issue)
com.weusours.util.re does not support nested POSIX character classes (definitely should, but
not completely trivial)
com.weusours.util.re Does not support POSIX character collation concepts ([.foo.] syntax)
(I18N/locale issue)
Should there be different matching styles (simple, POSIX, Perl etc?)
Should RE support character iterators (for backwards RE matching!)?
Should RE support reluctant {m,n} closures (does anyone care)?
Not *all* possibilities are considered for greediness when backreferences are involved (as
POSIX suggests should be the case). The POSIX RE "(ac*)c*d[ac]*\1", when matched
against "acdacaa" should yield a match of acdacaa where \1 is "a". This is not the case in this
RE package, and actually Perl doesn't go to this extent either! Until someone actually
complains about this, I'm not sure it's worth "fixing". If it ever is fixed, test #137 in RETest.txt
should be updated.
See Also:
Class RE
683
Field Summary
Modifier and
Type
static int
static int
static int
static int
static int
static int
Flag bit that indicates that subst should replace all occurrences of this
regular expression.
REPLACE_BACKREFERENCES
static int
Flag bit that indicates that subst should only replace the first occurrence of
this regular expression.
Constructor Summary
Constructor and Description
RE()
Construct a matcher for a pre-compiled regular expression from program (bytecode) data.
RE(REProgram program, int matchFlags)
Construct a matcher for a pre-compiled regular expression from program (bytecode) data.
RE(String pattern)
Constructs a regular expression matcher from a String by compiling it using a new instance
of RECompiler.
RE(String pattern, int matchFlags)
Constructs a regular expression matcher from a String by compiling it using a new instance
of RECompiler.
Method Summary
Modifier
and Type
int
String
int
int
int
int
Field Summary
684
getProgram()
Returns the current regular expression program in use by this matcher object.
grep(Object[] search)
String[]
protected
void
boolean
boolean
boolean
protected
boolean
protected
int
Match the current regular expression program against the current input string,
starting at index i of the input string.
matchNodes(int firstNode, int lastNode, int idxStart)
void
Sets match behaviour flags which alter the way RE does matching.
protected
void
protected
void
void
Sets the current regular expression program used by this matcher object.
simplePatternToFullRegularExpression(String pattern)
static
String
String[]
String
String
split(String s)
Field Detail
MATCH_NORMAL
public static final int MATCH_NORMAL
Method Summary
685
Flag bit that indicates that subst should replace all occurrences of this regular
expression.
See Also:
Constant Field Values
REPLACE_FIRSTONLY
public static final int REPLACE_FIRSTONLY
Flag bit that indicates that subst should only replace the first occurrence of this
regular expression.
See Also:
Constant Field Values
REPLACE_BACKREFERENCES
public static final int REPLACE_BACKREFERENCES
Constructor Detail
RE
public RE(String pattern)
throws RESyntaxException
RE
public RE(String pattern,
int matchFlags)
throws RESyntaxException
Field Detail
686
See Also:
RECompiler
RE
public RE(REProgram program,
int matchFlags)
See Also:
RECompiler, REProgram
RE
public RE(REProgram program)
RE
public RE()
Method Detail
simplePatternToFullRegularExpression
public static String simplePatternToFullRegularExpression(String pattern)
Sets match behaviour flags which alter the way RE does matching.
Parameters:
matchFlags - One or more of the RE match behaviour flags (RE.MATCH_*):
MATCH_NORMAL
MATCH_CASEINDEPENDENT
MATCH_MULTILINE
getMatchFlags
public int getMatchFlags()
Constructor Detail
687
See Also:
setMatchFlags(int)
setProgram
public void setProgram(REProgram program)
Sets the current regular expression program used by this matcher object.
Parameters:
program - Regular expression program compiled by RECompiler.
See Also:
RECompiler, REProgram
getProgram
public REProgram getProgram()
Returns the current regular expression program in use by this matcher object.
Returns:
Regular expression program
See Also:
setProgram(com.codename1.util.regex.REProgram)
getParenCount
public int getParenCount()
Method Detail
688
Throws an Error representing an internal error condition probably resulting from a bug
in the regular expression compiler (or possibly data corruption). In practice, this
should be very rare.
Parameters:
s - Error description
Throws:
Error
matchNodes
protected int matchNodes(int firstNode,
int lastNode,
int idxStart)
Match the current regular expression program against the current input string, starting
at index i of the input string. This method is only meant for internal use.
Parameters:
i - The input string index to start matching at
Returns:
True if the input matched the expression
match
public boolean match(String search,
int i)
Matches the current regular expression program against a character array, starting at
a given index.
Parameters:
search - String to match against
i - Index to start searching at
Returns:
True if string matched
Method Detail
689
Matches the current regular expression program against a character array, starting at
a given index.
Parameters:
search - String to match against
i - Index to start searching at
Returns:
True if string matched
match
public boolean match(String search)
Splits a string into an array of strings on regular expression boundaries. This function
works the same way as the Perl function of the same name. Given a regular
expression of "[ab]+" and a string to split of "xyzzyababbayyzabbbab123", the result
would be the array of Strings "[xyzzy, yyz, 123]".
Please note that the first string in the resulting array may be an empty string. This
happens when the very first character of input string is matched by the pattern.
Parameters:
s - String to split on this regular exression
Returns:
Array of strings
subst
public String subst(String substituteIn,
String substitution)
Substitutes a string for this regular expression in another string. This method works
like the Perl function of the same name. Given a regular expression of "a*b", a String
to substituteIn of "aaaabfooaaabgarplyaaabwackyb" and the substitution String "-",
the resulting String returned by subst would be "-foo-garply-wacky-".
Parameters:
substituteIn - String to substitute within
substitution - String to substitute for all matches of this regular expression.
Returns:
The string substituteIn with zero or more occurrences of the current regular
expression replaced with the substitution String (if this regular expression
object doesn't match at any position, the original String is returned
unchanged).
subst
public String subst(String substituteIn,
String substitution,
int flags)
Substitutes a string for this regular expression in another string. This method works
like the Perl function of the same name. Given a regular expression of "a*b", a String
to substituteIn of "aaaabfooaaabgarplyaaabwackyb" and the substitution String "-",
the resulting String returned by subst would be "-foo-garply-wacky-".
It is also possible to reference the contents of a parenthesized expression with $0,
$1, ... $9. A regular expression of "http://[\\.\\w\\-\\?/~_@&=%]+", a String to
Method Detail
690
expression
REPLACE_FIRSTONLY flag bit is set, only the first occurrence of this regular
expression is replaced. If the bit is not set (REPLACE_ALL), all occurrences
of this pattern will be replaced. If the flag REPLACE_BACKREFERENCES is
set, all backreferences will be processed.
Returns:
The string substituteIn with zero or more occurrences of the current regular
expression replaced with the substitution String (if this regular expression
object doesn't match at any position, the original String is returned
unchanged).
grep
public String[] grep(Object[] search)
Method Detail
691
Interface CharacterIterator
All Known Implementing Classes:
CharacterArrayCharacterIterator, ReaderCharacterIterator, StreamCharacterIterator,
StringCharacterIterator
public interface
Encapsulates different types of character sources - String, InputStream, ... Defines a set of common
methods
Version:
CVS $Id: CharacterIterator.java 518156 2007-03-14 14:31:26Z vgritsenko $
Method Summary
Modifier and Type
char
charAt(int pos)
boolean
isEnd(int pos)
String
substring(int beginIndex)
String
Method Detail
substring
String substring(int beginIndex,
int endIndex)
Returns:
a substring
substring
String substring(int beginIndex)
Returns:
a substring
charAt
char charAt(int pos)
Returns:
a character at the specified position.
isEnd
boolean isEnd(int pos)
Returns:
true
Interface CharacterIterator
iff if the specified index is after the end of the character stream
692
Class CharacterArrayCharacterIterator
java.lang.Object
com.codename1.util.regex.CharacterArrayCharacterIterator
All Implemented Interfaces:
CharacterIterator
Constructor Summary
Constructor and Description
CharacterArrayCharacterIterator(char[] src, int off, int len)
Method Summary
Modifier and Type
char
charAt(int pos)
boolean
isEnd(int pos)
String
substring(int beginIndex)
String
Constructor Detail
CharacterArrayCharacterIterator
public CharacterArrayCharacterIterator(char[] src,
int off,
int len)
Parameters:
src - - encapsulated String
Method Detail
substring
public String substring(int beginIndex,
int endIndex)
Specified by:
substring
Method Detail
in interface CharacterIterator
693
Specified by:
substring in interface CharacterIterator
Returns:
a substring
charAt
public char charAt(int pos)
Specified by:
charAt in interface CharacterIterator
Returns:
a character at the specified position.
isEnd
public boolean isEnd(int pos)
Specified by:
isEnd
in interface CharacterIterator
Returns:
true
Method Detail
iff if the specified index is after the end of the character stream
694
Class StringUtil
java.lang.Object
com.codename1.util.StringUtil
public class
extends Object
Constructor Summary
Constructor and Description
StringUtil()
Method Summary
Modifier and
Type
static String
This method replaces all occurrences of the pattern with the replacement
String
setImplementation(com.codename1.impl.CodenameOneImplementation i)
static void
Deprecated.
exposed as part of an internal optimization, this method isn't meant for
general access
static
List<String>
static
List<String>
static Vector
Deprecated.
use the tokenize() method instead
tokenizeString(String source, String separator)
static Vector
Deprecated.
use the tokenize() method instead
Constructor Detail
StringUtil
public StringUtil()
Method Detail
Class StringUtil
695
Deprecated. exposed as part of an internal optimization, this method isn't meant for
general access
replaceAll
public static String replaceAll(String source,
String pattern,
String replace)
This method replaces all occurrences of the pattern with the replacement String
Parameters:
source - the String source
pattern - String to replace in the source
replace - replacement String
Returns:
string with replaced elements
tokenizeString
public static Vector tokenizeString(String source,
char separator)
Method Detail
696
Class MathUtil
java.lang.Object
com.codename1.util.MathUtil
MathUtil for Java ME. This fills the gap in Java ME Math with a port of Sun's public FDLIBM C-library
for IEEE-754.
See Also:
For the Freely Distributable C-library conforming to IEEE-754 floating point math.,
For the GNU C variant of the same IEEE-754 routines., Another take on the IEEE-754
routines., Yet another take on the IEEE-754 routines., For other approximations., For
fast but rough approximations., For more fast but rough approximations.
Constructor Summary
Constructor and Description
MathUtil()
Method Summary
Modifier
and Type
static
double
acos(double a)
static
double
asin(double a)
static
double
atan(double a)
static
double
static
double
static
double
static
double
static long
static int
copysign(double x, double y)
Deprecated.
Please update your code to use copySign
copySign(double x, double y)
exp(double a)
static
double
log(double a)
static
double
log10(double a)
static
double
Class MathUtil
For any real arguments x and y not both equal to zero, atan2(y, x) is the angle
in radians between the positive x-axis of a plane and the point given by the
coordinates (x, y) on it.
Returns the next representable floating point number after the first argument in
the direction of the second argument.
697
static
double
static long
static int
round(double a)
static
double
scalbn(double x, int n)
static
double
Deprecated.
Please update your code to use scalb
ulp(double d)
static
double
Returns the size of an ulp (units in the last place) of the argument.
Constructor Detail
MathUtil
public MathUtil()
Method Detail
exp
public static final double exp(double a)
Return the natural logarithm, ln(a), as it relates to Math.E. This in turn uses
ieee7854_log(double).
log10
public static final double log10(double a)
Method Summary
698
For any real arguments x and y not both equal to zero, atan2(y, x) is the angle in
radians between the positive x-axis of a plane and the point given by the coordinates
(x, y) on it. The angle is positive for counter-clockwise angles (upper half-plane, y >
0), and negative for clockwise angles (lower half-plane, y < 0). This in turn uses
ieee7854_arctan2(double).
scalb
public static final double scalb(double x,
int n)
copysign
public static final double copysign(double x,
double y)
Returns the size of an ulp (units in the last place) of the argument.
Parameters:
d - value whose ulp is to be returned
Returns:
size of an ulp for the argument
Method Detail
699
Returns the next representable floating point number after the first argument in the
direction of the second argument.
Parameters:
start - starting value
direction - value indicating which of the neighboring representable floating
point number to return
Returns:
The floating-point number next to start in the direction of .
round
public static int round(float a)
Method Detail
700
Interface LazyValue<T>
public interface
Useful when passing a value that might not exist to a function, e.g. when we pass a form that we
might need to construct dynamically later on.
Method Summary
Modifier and Type Method and Description
get(Object... args)
Method Detail
get
T get(Object... args)
Interface LazyValue<T>
701
Class CaseInsensitiveOrder
java.lang.Object
com.codename1.util.CaseInsensitiveOrder
All Implemented Interfaces:
Comparator<String>
public class
extends Object
implements Comparator<String>
Constructor Summary
Constructor and Description
CaseInsensitiveOrder()
Method Summary
Modifier and Type
int
Constructor Detail
CaseInsensitiveOrder
public CaseInsensitiveOrder()
Method Detail
compare
public int compare(String s1,
String s2)
Compares the two specified objects to determine their relative ordering. The ordering
implied by the return value of this method for all possible pairs of (object1, object2)
should form an equivalence relation. This means that
compare(a,a) returns zero for all a
the sign of compare(a,b) must be the opposite of the sign of compare(b,a) for
all pairs of (a,b)
Method Detail
702
Method Detail
703
Interface Callback<T>
public interface
Simple interface that allows asynchronous code to perform a parameterized callback or failure in a
similar way to GWT's callback interface
Method Summary
Modifier and
Type
void
void
Method Detail
onSucess
void onSucess(T value)
Interface Callback<T>
704
Class CStringBuilder
java.lang.Object
com.codename1.util.CStringBuilder
Deprecated.
we will be moving to the proper string builder very soon
public final class
extends Object
This is generally the Apache String builder class refactored here so we can use it regardless of vm
limitations/differences for increased performance. A modifiable sequence of characters for use in
creating and modifying Strings. This class is intended as a direct replacement of StringBuffer for
non-concurrent use; unlike StringBuffer this class is not synchronized for thread safety.
The majority of the modification methods on this class return StringBuilder, so that, like
StringBuffers, they can be used in chaining method calls together. For example, new
StringBuilder("One should ").append("always strive ").append("to achieve Harmony").
Since:
1.5
See Also:
CharSequence, Appendable, StringBuffer, String
Constructor Summary
Constructor and Description
CStringBuilder()
Deprecated.
Constructs an instance with an initial capacity of 16.
CStringBuilder(int capacity)
Deprecated.
Constructs an instance with the specified capacity.
CStringBuilder(String str)
Deprecated.
Constructs an instance that's initialized with the contents of the specified String.
Method Summary
Modifier and
Type
CStringBuilder
Deprecated.
Appends the string representation of the specified boolean value.
append(char c)
CStringBuilder
Deprecated.
Appends the string representation of the specified char value.
append(char[] ch)
CStringBuilder
Deprecated.
Appends the string representation of the specified char[].
append(char[] str, int offset, int len)
CStringBuilder
Deprecated.
Appends the string representation of the specified subset of the char[].
CStringBuilder
append(double d)
Deprecated.
Method Detail
705
Deprecated.
Appends the string representation of the specified float value.
append(int i)
CStringBuilder
Deprecated.
Appends the string representation of the specified int value.
append(long lng)
CStringBuilder
Deprecated.
Appends the string representation of the specified long value.
append(Object obj)
CStringBuilder
Deprecated.
Appends the string representation of the specified Object.
append(String str)
CStringBuilder
Deprecated.
Appends the contents of the specified string.
appendCodePoint(int codePoint)
CStringBuilder
int
char
int
int
Deprecated.
Appends the encoded Unicode code point.
capacity()
Retrieves the Unicode code point value that precedes the index.
codePointCount(int beginIndex, int endIndex)
int
CStringBuilder
Deprecated.
Deletes a sequence of characters specified by start and end.
deleteCharAt(int index)
CStringBuilder
Deprecated.
Deletes the character at the specified index.
ensureCapacity(int min)
void
void
int
int
CStringBuilder
Deprecated.
Inserts the string representation of the specified boolean value at the
specified offset.
insert(int offset, char c)
CStringBuilder
Deprecated.
Inserts the string representation of the specified char value at the
specified offset.
insert(int offset, char[] ch)
CStringBuilder
CStringBuilder
Method Summary
Deprecated.
Inserts the string representation of the specified char[] at the specified
offset.
insert(int offset, char[] str, int strOffset, int strLen)
706
Deprecated.
Inserts the string representation of the specified double value at the
specified offset.
insert(int offset, float f)
CStringBuilder
Deprecated.
Inserts the string representation of the specified float value at the
specified offset.
insert(int offset, int i)
CStringBuilder
Deprecated.
Inserts the string representation of the specified int value at the specified
offset.
insert(int offset, long l)
CStringBuilder
Deprecated.
Inserts the string representation of the specified long value at the
specified offset.
insert(int offset, Object obj)
CStringBuilder
Deprecated.
Inserts the string representation of the specified Object at the specified
offset.
insert(int offset, String str)
CStringBuilder
int
int
int
int
Deprecated.
Inserts the specified string at the specified offset.
lastIndexOf(String string)
from index.
Deprecated.
Replaces the specified subsequence in this builder with the specified
string.
reverse()
CStringBuilder
void
void
Deprecated.
Reverses the order of characters in this builder.
setCharAt(int index, char ch)
Sets the character at the index.
setLength(int length)
String
Returns the String value of the subsequence from the start index to the
current end.
substring(int start, int end)
String
Returns the String value of the subsequence from the start index to the
end index.
toString()
String
void
Method Summary
Deprecated.
Returns the contents of this builder.
trimToSize()
707
Constructor Detail
CStringBuilder
public CStringBuilder()
Deprecated.
Constructs an instance with an initial capacity of 16.
See Also:
capacity()
CStringBuilder
public CStringBuilder(int capacity)
Deprecated.
Constructs an instance with the specified capacity.
Parameters:
capacity - the initial capacity to use.
Throws:
NegativeArraySizeException - if the specified capacity is negative.
See Also:
capacity()
CStringBuilder
public CStringBuilder(String str)
Deprecated.
Constructs an instance that's initialized with the contents of the specified String. The
capacity of the new builder will be the length of the String plus 16.
Parameters:
str - the String to copy into the builder.
Throws:
NullPointerException - if str is null.
Method Detail
append
public CStringBuilder append(boolean b)
Deprecated.
Appends the string representation of the specified boolean value. The boolean value
is converted to a String according to the rule defined by String.valueOf(boolean).
Parameters:
b - the boolean value to append.
Returns:
this builder.
See Also:
String.valueOf(boolean)
append
public CStringBuilder append(char c)
Deprecated.
Appends the string representation of the specified char value. The char value is
converted to a string according to the rule defined by String.valueOf(char).
Parameters:
c - the char value to append.
Returns:
708
append
public CStringBuilder append(int i)
Deprecated.
Appends the string representation of the specified int value. The int value is
converted to a string according to the rule defined by String.valueOf(int).
Parameters:
i - the int value to append.
Returns:
this builder.
See Also:
String.valueOf(int)
append
public CStringBuilder append(long lng)
Deprecated.
Appends the string representation of the specified long value. The long value is
converted to a string according to the rule defined by String.valueOf(long).
Parameters:
lng - the long value.
Returns:
this builder.
See Also:
String.valueOf(long)
append
public CStringBuilder append(float f)
Deprecated.
Appends the string representation of the specified float value. The float value is
converted to a string according to the rule defined by String.valueOf(float).
Parameters:
f - the float value to append.
Returns:
this builder.
See Also:
String.valueOf(float)
append
public CStringBuilder append(double d)
Deprecated.
Appends the string representation of the specified double value. The double value is
converted to a string according to the rule defined by String.valueOf(double).
Parameters:
d - the double value to append.
Returns:
this builder.
See Also:
String.valueOf(double)
append
public CStringBuilder append(Object obj)
Deprecated.
Appends the string representation of the specified Object. The Object value is
converted to a string according to the rule defined by String.valueOf(Object).
Parameters:
obj - the Object to append.
Returns:
this builder.
See Also:
Method Detail
709
append
public CStringBuilder append(String str)
Deprecated.
Appends the contents of the specified string. If the string is null, then the string
"null" is appended.
Parameters:
str - the string to append.
Returns:
this builder.
append
public CStringBuilder append(char[] ch)
Deprecated.
Appends the string representation of the specified char[]. The char[] is converted to
a string according to the rule defined by String.valueOf(char[]).
Parameters:
ch - the char[] to append..
Returns:
this builder.
See Also:
String.valueOf(char[])
append
public CStringBuilder append(char[] str,
int offset,
int len)
Deprecated.
Appends the string representation of the specified subset of the char[]. The char[]
value is converted to a String according to the rule defined by
String.valueOf(char[],int,int).
Parameters:
str - the char[] to append.
offset - the inclusive offset index.
len - the number of characters.
Returns:
this builder.
Throws:
ArrayIndexOutOfBoundsException - if offset and len do not specify a valid
subsequence.
See Also:
String.valueOf(char[],int,int)
appendCodePoint
public CStringBuilder appendCodePoint(int codePoint)
Deprecated.
Appends the encoded Unicode code point. The code point is converted to a char[]
as defined by Character.toChars(int).
Parameters:
codePoint - the Unicode code point to encode and append.
Returns:
this builder.
See Also:
Character.toChars(int)
delete
public CStringBuilder delete(int start,
int end)
Deprecated.
Deletes a sequence of characters specified by start and end. Shifts any remaining
characters to the left.
Parameters:
Method Detail
710
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if start
the current length or greater than end.
deleteCharAt
public CStringBuilder deleteCharAt(int index)
Deprecated.
Deletes the character at the specified index. shifts any remaining characters to the
left.
Parameters:
index - the index of the character to delete.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if index is less than zero or is greater
than or equal to the current length.
insert
public CStringBuilder insert(int offset,
boolean b)
Deprecated.
Inserts the string representation of the specified boolean value at the specified
offset. The boolean value is converted to a string according to the rule defined by
String.valueOf(boolean).
Parameters:
offset - the index to insert at.
b - the boolean value to insert.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if offset is negative or greater than the
current length.
See Also:
String.valueOf(boolean)
insert
public CStringBuilder insert(int offset,
char c)
Deprecated.
Inserts the string representation of the specified char value at the specified offset.
The char value is converted to a string according to the rule defined by
String.valueOf(char).
Parameters:
offset - the index to insert at.
c - the char value to insert.
Returns:
this builder.
Throws:
IndexOutOfBoundsException - if offset is negative or greater than the current
length().
See Also:
String.valueOf(char)
insert
public CStringBuilder insert(int offset,
int i)
Deprecated.
Inserts the string representation of the specified int value at the specified offset.
The int value is converted to a String according to the rule defined by
Method Detail
711
Parameters:
offset - the index to insert
i - the int value to insert.
at.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException
current length().
See Also:
String.valueOf(int)
insert
public CStringBuilder insert(int offset,
long l)
Deprecated.
Inserts the string representation of the specified long value at the specified offset.
The long value is converted to a String according to the rule defined by
String.valueOf(long).
Parameters:
offset - the index to insert at.
l - the long value to insert.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if offset is negative or greater than the
current {code length()}.
See Also:
String.valueOf(long)
insert
public CStringBuilder insert(int offset,
float f)
Deprecated.
Inserts the string representation of the specified float value at the specified offset.
The float value is converted to a string according to the rule defined by
String.valueOf(float).
Parameters:
offset - the index to insert at.
f - the float value to insert.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if offset is negative or greater than the
current length().
See Also:
String.valueOf(float)
insert
public CStringBuilder insert(int offset,
double d)
Deprecated.
Inserts the string representation of the specified double value at the specified offset.
The double value is converted to a String according to the rule defined by
String.valueOf(double).
Parameters:
offset - the index to insert at.
d - the double value to insert.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if offset is negative or greater than the
current length().
See Also:
Method Detail
712
insert
public CStringBuilder insert(int offset,
Object obj)
Deprecated.
Inserts the string representation of the specified Object at the specified offset. The
Object value is converted to a String according to the rule defined by
String.valueOf(Object).
Parameters:
offset - the index to insert at.
obj - the Object to insert.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if offset is negative or greater than the
current length().
See Also:
String.valueOf(Object)
insert
public CStringBuilder insert(int offset,
String str)
Deprecated.
Inserts the specified string at the specified offset. If the specified string is null, then
the String "null" is inserted.
Parameters:
offset - the index to insert at.
str - the String to insert.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if offset is negative or greater than the
current length().
insert
public CStringBuilder insert(int offset,
char[] ch)
Deprecated.
Inserts the string representation of the specified char[] at the specified offset. The
char[] value is converted to a String according to the rule defined by
String.valueOf(char[]).
Parameters:
offset - the index to insert at.
ch - the char[] to insert.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if offset is negative or greater than the
current length().
See Also:
String.valueOf(char[])
insert
public CStringBuilder insert(int offset,
char[] str,
int strOffset,
int strLen)
Deprecated.
Inserts the string representation of the specified subsequence of the char[] at the
specified offset. The char[] value is converted to a String according to the rule
defined by String.valueOf(char[],int,int).
Parameters:
offset - the index to insert at.
Method Detail
713
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if offset is negative or greater
current length(), or strOffset and strLen do not specify a valid
than the
subsequence.
See Also:
String.valueOf(char[],int,int)
replace
public CStringBuilder replace(int start,
int end,
String str)
Deprecated.
Replaces the specified subsequence in this builder with the specified string.
Parameters:
start - the inclusive begin index.
end - the exclusive end index.
str - the replacement string.
Returns:
this builder.
Throws:
StringIndexOutOfBoundsException - if start is negative, greater than the
current length() or greater than end.
NullPointerException - if str is null.
reverse
public CStringBuilder reverse()
Deprecated.
Reverses the order of characters in this builder.
Returns:
this buffer.
toString
public String toString()
Deprecated.
Returns the contents of this builder.
Returns:
the string representation of the data in this builder.
capacity
public int capacity()
Method Detail
714
Ensures that this object has a minimum capacity available before requiring the
internal buffer to be enlarged. The general policy of this method is that if the
minimumCapacity is larger than the current capacity(), then the capacity will be
increased to the largest value of either the minimumCapacity or the current capacity
multiplied by two plus two. Although this is the general policy, there is no guarantee
that the capacity will change.
Parameters:
min - the new minimum capacity to set.
getChars
public void getChars(int start,
int end,
char[] dest,
int destStart)
Sets the current length to a new value. If the new length is larger than the current
length, then the new characters at the end of this object will contain the char value of
.
Parameters:
length - the new length of this StringBuffer.
Throws:
IndexOutOfBoundsException - if length < 0.
See Also:
length()
substring
public String substring(int start)
Returns the String value of the subsequence from the start index to the current end.
Method Detail
715
Returns the String value of the subsequence from the start index to the end index.
Parameters:
start - the inclusive start index to begin the subsequence.
end - the exclusive end index to end the subsequence.
Returns:
a String containing the subsequence.
Throws:
StringIndexOutOfBoundsException - if start is negative, greater than end or
if end is greater than the current length().
indexOf
public int indexOf(String string)
Searches for the first index of the specified character. The search for the character
starts at the beginning and moves towards the end.
Parameters:
string - the string to find.
Returns:
the index of the specified character, -1 if the character isn't found.
Since:
1.4
See Also:
lastIndexOf(String)
indexOf
public int indexOf(String subString,
int start)
Searches for the index of the specified character. The search for the character starts
at the specified offset and moves towards the end.
Parameters:
subString - the string to find.
start - the starting offset.
Returns:
the index of the specified character, -1 if the character isn't found
Since:
1.4
See Also:
lastIndexOf(String,int)
lastIndexOf
public int lastIndexOf(String string)
Searches for the last index of the specified character. The search for the character
starts at the end and moves towards the beginning.
Parameters:
string - the string to find.
Returns:
the index of the specified character, -1 if the character isn't found.
Throws:
NullPointerException - if string is null.
Since:
1.4
See Also:
String.lastIndexOf(java.lang.String)
Method Detail
716
Searches for the index of the specified character. The search for the character starts
at the specified offset and moves towards the beginning.
Parameters:
subString - the string to find.
start - the starting offset.
Returns:
the index of the specified character, -1 if the character isn't found.
Throws:
NullPointerException - if subString is null.
Since:
1.4
See Also:
String.lastIndexOf(String,int)
trimToSize
public void trimToSize()
Trims off any extra capacity beyond the current length. Note, this method is NOT
guaranteed to change the capacity of this object.
Since:
1.5
codePointAt
public int codePointAt(int index)
Retrieves the Unicode code point value that precedes the index.
Parameters:
index - the index to the char code unit within this object.
Returns:
the Unicode code point value.
Throws:
IndexOutOfBoundsException - if index is less than 1 or greater than length().
Since:
1.5
See Also:
Character, Character.codePointBefore(char[], int, int)
codePointCount
public int codePointCount(int beginIndex,
int endIndex)
Calculates the number of Unicode code points between beginIndex and endIndex.
Parameters:
beginIndex - the inclusive beginning index of the subsequence.
endIndex - the exclusive end index of the subsequence.
Returns:
Method Detail
717
or greater than
Since:
1.5
See Also:
Character, Character.codePointCount(char[], int, int)
offsetByCodePoints
public int offsetByCodePoints(int index,
int codePointOffset)
Returns the index that is offset codePointOffset code points from index.
Parameters:
index - the index to calculate the offset from.
codePointOffset - the number of code points to count.
Returns:
the index that is codePointOffset code points away from index.
Throws:
IndexOutOfBoundsException - if index is negative or greater than length() or
if there aren't enough code points before or after index to match
codePointOffset.
Since:
1.5
See Also:
Character, Character.offsetByCodePoints(char[], int, int, int, int)
Method Detail
718
Class BigInteger
java.lang.Object
com.codename1.util.BigInteger
public class
extends Object
Field Summary
Modifier and Type Field and Description
static BigInteger
ONE
static BigInteger
ZERO
Constructor Summary
Constructor and Description
BigInteger(byte[] bval)
BigInteger(int sign, byte[] mag)
BigInteger(int bitLength, int certainty, Random rnd)
BigInteger(int numBits, Random rnd)
BigInteger(String sval)
BigInteger(String sval, int rdx)
Method Summary
Modifier and
Type
BigInteger
abs()
BigInteger
add(BigInteger val)
BigInteger
and(BigInteger value)
BigInteger
andNot(BigInteger value)
int
bitCount()
int
bitLength()
byte
byteValue()
BigInteger
clearBit(int n)
int
compareTo(BigInteger val)
int
compareTo(Object o)
BigInteger
divide(BigInteger val)
BigInteger[]
divideAndRemainder(BigInteger val)
boolean
equals(Object val)
BigInteger
flipBit(int n)
BigInteger
gcd(BigInteger val)
Class BigInteger
719
getLowestSetBit()
hashCode()
int
int
intValue()
isProbablePrime(int certainty)
boolean
long
longValue()
BigInteger
max(BigInteger val)
BigInteger
min(BigInteger val)
BigInteger
mod(BigInteger m)
BigInteger
modInverse(BigInteger m)
BigInteger
BigInteger
multiply(BigInteger val)
BigInteger
negate()
BigInteger
not()
BigInteger
or(BigInteger value)
BigInteger
pow(int exp)
static
BigInteger
BigInteger
remainder(BigInteger n)
BigInteger
setBit(int n)
BigInteger
shiftLeft(int n)
BigInteger
shiftRight(int n)
int
signum()
BigInteger
subtract(BigInteger val)
boolean
testBit(int n)
byte[]
toByteArray()
toString()
String
String
toString(int rdx)
static
BigInteger
valueOf(long val)
BigInteger
xor(BigInteger val)
Field Detail
ZERO
public static final BigInteger ZERO
ONE
public static final BigInteger ONE
Constructor Detail
Method Summary
720
Throws:
NumberFormatException
BigInteger
public BigInteger(String sval,
int rdx)
throws NumberFormatException
Throws:
NumberFormatException
BigInteger
public BigInteger(byte[] bval)
throws NumberFormatException
Throws:
NumberFormatException
BigInteger
public BigInteger(int sign,
byte[] mag)
throws NumberFormatException
Throws:
NumberFormatException
BigInteger
public BigInteger(int numBits,
Random rnd)
throws IllegalArgumentException
Throws:
IllegalArgumentException
BigInteger
public BigInteger(int bitLength,
int certainty,
Random rnd)
throws ArithmeticException
Throws:
ArithmeticException
Method Detail
abs
public BigInteger abs()
add
public BigInteger add(BigInteger val)
throws ArithmeticException
Throws:
ArithmeticException
and
public BigInteger and(BigInteger value)
andNot
public BigInteger andNot(BigInteger value)
Constructor Detail
721
bitLength
public int bitLength()
compareTo
public int compareTo(Object o)
compareTo
public int compareTo(BigInteger val)
divide
public BigInteger divide(BigInteger val)
throws ArithmeticException
Throws:
ArithmeticException
divideAndRemainder
public BigInteger[] divideAndRemainder(BigInteger val)
throws ArithmeticException
Throws:
ArithmeticException
equals
public boolean equals(Object val)
hashCode
public int hashCode()
Method Detail
722
byteValue
public byte byteValue()
isProbablePrime
public boolean isProbablePrime(int certainty)
max
public BigInteger max(BigInteger val)
min
public BigInteger min(BigInteger val)
mod
public BigInteger mod(BigInteger m)
throws ArithmeticException
Throws:
ArithmeticException
modInverse
public BigInteger modInverse(BigInteger m)
throws ArithmeticException
Throws:
ArithmeticException
modPow
public BigInteger modPow(BigInteger exponent,
BigInteger m)
throws ArithmeticException
Throws:
ArithmeticException
multiply
public BigInteger multiply(BigInteger val)
negate
public BigInteger negate()
not
public BigInteger not()
pow
public BigInteger pow(int exp)
throws ArithmeticException
Throws:
ArithmeticException
Method Detail
723
remainder
public BigInteger remainder(BigInteger n)
throws ArithmeticException
Throws:
ArithmeticException
shiftLeft
public BigInteger shiftLeft(int n)
shiftRight
public BigInteger shiftRight(int n)
signum
public int signum()
subtract
public BigInteger subtract(BigInteger val)
toByteArray
public byte[] toByteArray()
xor
public BigInteger xor(BigInteger val)
or
public BigInteger or(BigInteger value)
setBit
public BigInteger setBit(int n)
throws ArithmeticException
Throws:
ArithmeticException
clearBit
public BigInteger clearBit(int n)
throws ArithmeticException
Throws:
ArithmeticException
flipBit
public BigInteger flipBit(int n)
throws ArithmeticException
Throws:
ArithmeticException
toString
public String toString()
Method Detail
724
valueOf
public static BigInteger valueOf(long val)
getLowestSetBit
public int getLowestSetBit()
testBit
public boolean testBit(int n)
throws ArithmeticException
Throws:
ArithmeticException
Method Detail
725
Class BigDecimal
java.lang.Object
com.codename1.util.BigDecimal
public class
extends Object
Class representing a simple version of a big decimal. A BigDecimal is basically a BigInteger with a
few digits on the right of the decimal point. The number of (binary) digits on the right of the decimal
point is called the scale of the BigDecimal. Unlike in BigDecimal, the scale is not adjusted
automatically, but must be set manually. All BigDecimals taking part in the same arithmetic operation
must have equal scale. The result of a multiplication of two BigDecimals returns a BigDecimal with
double scale.
Constructor Summary
Constructor and Description
BigDecimal(BigInteger bigInt, int scale)
Constructor for BigDecimal.
Method Summary
Modifier and Type
BigDecimal
add(BigDecimal b)
BigDecimal
add(BigInteger b)
BigDecimal
adjustScale(int newScale)
int
compareTo(BigDecimal val)
int
compareTo(BigInteger val)
BigDecimal
divide(BigDecimal b)
BigDecimal
divide(BigInteger b)
boolean
equals(Object o)
BigInteger
floor()
static BigDecimal
int
getScale()
int
hashCode()
int
intValue()
long
longValue()
BigDecimal
multiply(BigDecimal b)
BigDecimal
multiply(BigInteger b)
BigDecimal
negate()
BigInteger
round()
BigDecimal
shiftLeft(int n)
BigDecimal
subtract(BigDecimal b)
BigDecimal
subtract(BigInteger b)
Class BigDecimal
value as value.
726
String
Constructor Detail
BigDecimal
public BigDecimal(BigInteger bigInt,
int scale)
Constructor for BigDecimal. The value of the constructed BigDecimal equals bigInt /
scale
2
.
Parameters:
bigInt - The bigInt value parameter.
scale - The scale of the constructed BigDecimal.
Method Detail
getInstance
public static BigDecimal getInstance(BigInteger value,
int scale)
add
public BigDecimal add(BigDecimal b)
add
public BigDecimal add(BigInteger b)
negate
public BigDecimal negate()
subtract
public BigDecimal subtract(BigDecimal b)
subtract
public BigDecimal subtract(BigInteger b)
multiply
public BigDecimal multiply(BigDecimal b)
multiply
public BigDecimal multiply(BigInteger b)
divide
public BigDecimal divide(BigDecimal b)
Method Summary
727
shiftLeft
public BigDecimal shiftLeft(int n)
compareTo
public int compareTo(BigDecimal val)
compareTo
public int compareTo(BigInteger val)
floor
public BigInteger floor()
round
public BigInteger round()
intValue
public int intValue()
longValue
public long longValue()
getScale
public int getScale()
toString
public String toString()
Method Detail
728
Method Detail
729
Class Base64
java.lang.Object
com.codename1.util.Base64
public class
extends Object
Constructor Summary
Constructor and Description
Base64()
Method Summary
Modifier and
Type
static byte[]
static byte[]
static String
static String
Constructor Detail
Base64
public Base64()
Method Detail
decode
public static byte[] decode(byte[] in)
decode
public static byte[] decode(byte[] in,
int len)
Decodes an array of bytes containing a Base64 ascii string into binary data
Parameters:
in - the array
len - the length of the array
Class Base64
730
Method Detail
731
Class Validator
java.lang.Object
com.codename1.ui.validation.Validator
public class
extends Object
Binds validation constraints to form elements, when validation fails it can be highlighted directly on the
component via an emblem or change of the UIID (to original UIID name + "Invalid" e.g.
"TextFieldInvalid"). Validators just run thru a set of Constraint objects to decide if validation
succeeded or failed.
Constructor Summary
Constructor and Description
Validator()
Method Summary
Modifier and Type
Validator
Validator
Submit buttons (or any other component type) can be disabled until all co
bindDataListener(Component cmp)
void
protected Object
Deprecated.
this method was exposed by accident, constraint implicitly calls it and you
protected in a future update to Codename One!
getComponentValue(Component cmp)
Returns the value of the given component, this can be overriden to add su
getDefaultValidationEmblemPositionX()
static float
static float
static Image
static
Validator.HighlightMode
String
String
float
Class Validator
The emblem that will be drawn on top of the component to indicate the va
getDefaultValidationFailureHighlightMode()
Returns the validation error message for the given component or null if no
getErrorMessageUIID()
732
float
getValidationFailedEmblem()
Image
The emblem that will be drawn on top of the component to indicate the va
Validator.HighlightMode
boolean
boolean
getValidationFailureHighlightMode()
Indicates whether an error message should be shown for the focused com
isValid()
static boolean
Indicates whether validation should occur on every key press (data chang
completion)
setDefaultValidationEmblemPositionX(float aDefaultValidationEmble
static void
setDefaultValidationEmblemPositionY(float aDefaultValidationEmble
static void
static void
static void
setDefaultValidationFailedEmblem(Image aDefaultValidationFailedEm
The emblem that will be drawn on top of the component to indicate the va
setDefaultValidationFailureHighlightMode(Validator.HighlightMode
void
setShowErrorMessageForFocusedComponent(boolean showErrorMessageFo
void
Indicates whether an error message should be shown for the focused com
setValidateOnEveryKey(boolean aValidateOnEveryKey)
static void
Indicates whether validation should occur on every key press (data chang
completion)
setValidationEmblemPositionX(float validationEmblemPositionX)
void
setValidationEmblemPositionY(float validationEmblemPositionY)
void
setValidationFailedEmblem(Image validationFailedEmblem)
void
The emblem that will be drawn on top of the component to indicate the va
setValidationFailureHighlightMode(Validator.HighlightMode validat
void
protected void
validate(Component cmp)
Constructor Detail
Validator
public Validator()
Method Summary
733
Method Detail
getDefaultValidationFailureHighlightMode
public static Validator.HighlightMode getDefaultValidationFailureHighlightMode()
The emblem that will be drawn on top of the component to indicate the validation
failure
Returns:
the defaultValidationFailedEmblem
setDefaultValidationFailedEmblem
The emblem that will be drawn on top of the component to indicate the validation
failure
Parameters:
aDefaultValidationFailedEmblem - the defaultValidationFailedEmblem to set
getDefaultValidationEmblemPositionX
public static float getDefaultValidationEmblemPositionX()
The position of the validation emblem on the component as X/Y values between 0
and 1 where 0 indicates the start of the component and 1 indicates its end on the
given axis.
Returns:
the defaultValidationEmblemPositionX
setDefaultValidationEmblemPositionX
The position of the validation emblem on the component as X/Y values between 0
and 1 where 0 indicates the start of the component and 1 indicates its end on the
given axis.
Parameters:
aDefaultValidationEmblemPositionX - the
defaultValidationEmblemPositionX to set
getDefaultValidationEmblemPositionY
public static float getDefaultValidationEmblemPositionY()
The position of the validation emblem on the component as X/Y values between 0
and 1 where 0 indicates the start of the component and 1 indicates its end on the
given axis.
Returns:
the defaultValidationEmblemPositionY
Method Detail
734
The position of the validation emblem on the component as X/Y values between 0
and 1 where 0 indicates the start of the component and 1 indicates its end on the
given axis.
Parameters:
aDefaultValidationEmblemPositionY - the
defaultValidationEmblemPositionY to set
isValidateOnEveryKey
public static boolean isValidateOnEveryKey()
Indicates whether validation should occur on every key press (data change listener)
or action performed (editing completion)
Returns:
the validateOnEveryKey
setValidateOnEveryKey
public static void setValidateOnEveryKey(boolean aValidateOnEveryKey)
Indicates whether validation should occur on every key press (data change listener)
or action performed (editing completion)
Parameters:
aValidateOnEveryKey - the validateOnEveryKey to set
getValidationFailureHighlightMode
public Validator.HighlightMode getValidationFailureHighlightMode()
The emblem that will be drawn on top of the component to indicate the validation
failure
Returns:
the validationFailedEmblem
setValidationFailedEmblem
public void setValidationFailedEmblem(Image validationFailedEmblem)
The emblem that will be drawn on top of the component to indicate the validation
failure
Parameters:
validationFailedEmblem - the validationFailedEmblem to set
getValidationEmblemPositionX
public float getValidationEmblemPositionX()
The position of the validation emblem on the component as X/Y values between 0
and 1 where 0 indicates the start of the component and 1 indicates its end on the
given axis.
Returns:
the validationEmblemPositionX
Method Detail
735
The position of the validation emblem on the component as X/Y values between 0
and 1 where 0 indicates the start of the component and 1 indicates its end on the
given axis.
Parameters:
validationEmblemPositionX - the validationEmblemPositionX to set
getValidationEmblemPositionY
public float getValidationEmblemPositionY()
The position of the validation emblem on the component as X/Y values between 0
and 1 where 0 indicates the start of the component and 1 indicates its end on the
given axis.
Returns:
the validationEmblemPositionY
setValidationEmblemPositionY
public void setValidationEmblemPositionY(float validationEmblemPositionY)
The position of the validation emblem on the component as X/Y values between 0
and 1 where 0 indicates the start of the component and 1 indicates its end on the
given axis.
Parameters:
validationEmblemPositionY - the validationEmblemPositionY to set
isShowErrorMessageForFocusedComponent
public boolean isShowErrorMessageForFocusedComponent()
Indicates whether an error message should be shown for the focused component
Returns:
true if the error message should be displayed
setShowErrorMessageForFocusedComponent
Indicates whether an error message should be shown for the focused component
Parameters:
showErrorMessageForFocusedComponent - true to show the error message
getErrorMessageUIID
public String getErrorMessageUIID()
Error message UIID defaults to DialogBody. Allows customizing the look of the
message
Returns:
the errorMessageUIID
setErrorMessageUIID
public void setErrorMessageUIID(String errorMessageUIID)
Error message UIID defaults to DialogBody. Allows customizing the look of the
message
Parameters:
errorMessageUIID - the errorMessageUIID to set
addConstraint
public Validator addConstraint(Component cmp,
Constraint... c)
Places a constraint on the validator, returns this object so constraint additions can be
chained. Notice that only one constraint
Parameters:
cmp - the component to validate
c - the constraint or constraints
Method Detail
736
Returns:
this object so we can write code like v.addConstraint(cmp1,
cons).addConstraint(cmp2, otherConstraint);
addSubmitButtons
public Validator addSubmitButtons(Component... cmp)
Submit buttons (or any other component type) can be disabled until all components
contain a valid value. Notice that this method should be invoked after all the
constraints are added so the initial state of the buttons will be correct.
Parameters:
cmp - set of buttons or components to disable until everything is valid
Returns:
the validator instance so this method can be chained
getComponentValue
protected Object getComponentValue(Component cmp)
Returns the value of the given component, this can be overriden to add support for
custom built components
Parameters:
cmp - the component
Returns:
the object value
bindDataListener
public void bindDataListener(Component cmp)
Deprecated. this method was exposed by accident, constraint implicitly calls it and
you don't need to call it directly. It will be made protected in a future update to
Codename One!
Binds an event listener to the given component
Parameters:
cmp - the component to bind the data listener to
isValid
public boolean isValid()
Returns the validation error message for the given component or null if no such
message exists
Parameters:
cmp - the invalid component
Returns:
a string representing the error message
Method Detail
737
Enum Validator.HighlightMode
java.lang.Object
java.lang.Enum<Validator.HighlightMode>
com.codename1.ui.validation.Validator.HighlightMode
All Implemented Interfaces:
Comparable<Validator.HighlightMode>
Enclosing class:
Validator
Method Summary
Modifier and Type
static
Validator.HighlightMode
static
Validator.HighlightMode[]
EMBLEM
public static final Validator.HighlightMode EMBLEM
Enum Validator.HighlightMode
738
NONE
public static final Validator.HighlightMode NONE
Method Detail
values
public static Validator.HighlightMode[] values()
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
for (Validator.HighlightMode c : Validator.HighlightMode.values())
System.out.println(c);
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static Validator.HighlightMode valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
739
Class RegexConstraint
java.lang.Object
com.codename1.ui.validation.RegexConstraint
All Implemented Interfaces:
Constraint
public class
extends Object
implements Constraint
Constructor Summary
Constructor and Description
RegexConstraint(String regex, String errorMessage)
Method Summary
Modifier and Type
String
boolean
static Constraint
static Constraint
static Constraint
static Constraint
isValid(Object value)
Constructor Detail
RegexConstraint
public RegexConstraint(String regex,
String errorMessage)
Method Detail
740
Detail
validEmail
public static Constraint validEmail(String errorMessage)
Method Detail
741
Class LengthConstraint
java.lang.Object
com.codename1.ui.validation.LengthConstraint
All Implemented Interfaces:
Constraint
public class
extends Object
implements Constraint
Constructor Summary
Constructor and Description
LengthConstraint(int length)
Method Summary
Modifier and Type
String
boolean
isValid(Object value)
Constructor Detail
LengthConstraint
public LengthConstraint(int length,
String errorMessage)
Class LengthConstraint
742
Detail
isValid
public boolean isValid(Object value)
Method Detail
743
Class GroupConstraint
java.lang.Object
com.codename1.ui.validation.GroupConstraint
All Implemented Interfaces:
Constraint
public class
extends Object
implements Constraint
Constructor Summary
Constructor and Description
GroupConstraint(Constraint... group)
Method Summary
Modifier and Type
String
boolean
isValid(Object value)
Constructor Detail
GroupConstraint
public GroupConstraint(Constraint... group)
Method Detail
isValid
public boolean isValid(Object value)
Class GroupConstraint
744
Method Detail
745
Interface Constraint
All Known Implementing Classes:
GroupConstraint, LengthConstraint, RegexConstraint
public interface
To perform validation we add a constraint to a validator, a constraint defines whether a value if valid
for a given object
Method Summary
Modifier and Type
String
boolean
Method Detail
isValid
boolean isValid(Object value)
Interface Constraint
746
Class WeakHashMap<K,V>
java.lang.Object
com.codename1.ui.util.WeakHashMap<K,V>
All Implemented Interfaces:
Map<K,V>
public class
extends Object
implements Map<K,V>
Constructor Summary
Constructor and Description
WeakHashMap()
Method Summary
Modifier and Type
void
boolean
boolean
Set<Map.Entry<K,V>>
V
boolean
Set<K>
V
void
V
int
Collection<V>
Method Detail
containsValue(Object value)
Unsupported operation
get(Object key)
this Map.
remove(Object key)
Unsupported operation
747
Constructor Detail
WeakHashMap
public WeakHashMap()
Method Detail
size
public int size()
containsKey
public boolean containsKey(Object key)
748
Returns a set of the keys contained in this Map. The Set is backed by this Map so
changes to one are reflected by the other. The Set does not support adding.
Specified by:
keySet in interface Map<K,V>
Returns:
a set of the keys.
values
public Collection<V> values()
Unsupported operation
Method Detail
749
Unsupported operation
Specified by:
entrySet in interface Map<K,V>
Returns:
a set of the mappings
Method Detail
750
Class UITimer
java.lang.Object
com.codename1.ui.util.UITimer
public class
extends Object
Simple timer callback that is invoked on the CodenameOne EDT thread rather than on a separate
thread. Notice that the accuracy of this timer is very low! A timer must be linked to a specific form
Constructor Summary
Modifier
protected
Method Summary
Modifier and
Type
void
void
static UITimer
static UITimer
Constructor Detail
UITimer
protected UITimer()
Class UITimer
751
Detail
schedule
public void schedule(int timeMillis,
boolean repeat,
Form bound)
Method Detail
752
Class UIBuilder
java.lang.Object
com.codename1.ui.util.UIBuilder
public class
extends Object
The UI builder can create a user interface based on the UI designed in the resource editor and allows
us to bind to said UI. Notice that if a Component was used in the GUI that is not a part of the
com.codename1.ui package (even a Component from sub packages such as table or tree) it MUST
be registered before loading a GUI!
Field Summary
Modifier and Type
static int
static String
static String
static String
static String
A key in the form state hashtable used in the back command navigation
FORM_STATE_KEY_NAME
A key in the form state hashtable used in the back command navigation
FORM_STATE_KEY_SELECTION
A key in the form state hashtable used in the back command navigation
FORM_STATE_KEY_TITLE
A key in the form state hashtable used in the back command navigation
Constructor Summary
Constructor and Description
UIBuilder()
Method Summary
Modifier and
Type
void
void
void
protected
boolean
protected void
Adds a command listener that would be bound to all forms in the GUI
seamlessly
addCommandListener(String formName, ActionListener l)
Adds a component listener that would be bound when a UI for this form is
created.
allowBackTo(String formName)
protected void
Class UIBuilder
Warning: This method is invoked OFF the EDT and is intended for usage
with asynchronous command processing.
753
This method effectively pops the form navigation stack and goes back to
the previous form if back navigation is enabled and there is a previous
form.
back(Component sourceComponent)
void
This method effectively pops the form navigation stack and goes back to
the previous form if back navigation is enabled and there is a previous
form.
beforeShow(Form f)
protected void
This method allows binding an action that should occur before showing
the given form
beforeShowContainer(Container c)
protected void
This method allows binding an action that should occur before showing
the given container
bindListenerToComponent(Component cmp, Object listener)
protected void
LazyValue<Form>
protected
Command
Binds the given listener object to the component, this works seamlessly
for common Codename One events but might be an issue with custom
components and custom listener types so this method can be overloaded
to add support for such cases.
createBackLazyValue(Form f)
protected
Component
Container
Container
Creates the container defined under the given name in the res file
createContainer(String resPath, String resourceName)
Creates the container defined under the given name in the res file
exitForm(Form f)
protected void
protected
Resources
Component
Component
This method allows binding an action that should occur before leaving
the given form, e.g.
fetchResourceFile()
protected String
protected String
protected
Hashtable
protected
Hashtable
String
Returns the state of the current form which we are about to leave as part
of the navigation logic.
getHomeForm()
String
Allows the navigation code to avoid storing the resource file and lets the
GC remove it from memory when its not in use
protected
Container
getRootAncestor(Component c)
Method Summary
754
boolean
static boolean
Enables blocking analytics in the UIBuilder, this is useful for the designer
tool.
isKeepResourcesInRam()
boolean
protected
boolean
protected void
protected void
This method allows binding logic that should occur before creating the
root object e.g.
popNavigationStack()
protected void
Removes a navigation frame from the stack, this is useful in case you
want to go back to a form in the middle of the navigation stack.
postAsyncCommand(Command cmd, ActionEvent sourceEvent)
protected void
protected void
protected void
This method allows binding an action that should occur immediately after
showing the given form
postShowContainer(Container c)
protected void
This method allows binding an action that should occur immediately after
showing the given container
protected
boolean
processBackground(Form f)
protected void
static void
void
Useful tool to refresh the current state of a container shown using show
container without pushing another instance to the back stack
reloadForm()
void
void
void
Useful tool to refresh the current state of a form shown using show form
without pushing another instance to the back stack
removeCommandListener(ActionListener l)
void
Method Summary
755
protected void
void
Invoked internally to set the back command on the form, this method
allows subclasses to change the behavior of back command adding or
disable it
setBackCommandEnabled(boolean back)
protected void
Pops the navigation stack until it finds form name and the back button will
match form name if form name isn't in the stack this method will fail
setBlockAnalytics(boolean aBlockAnalytics)
static void
Enables blocking analytics in the UIBuilder, this is useful for the designer
tool.
setContainerState(Container cnt, Hashtable state)
protected void
protected void
void
Sets the state of the current form to which we are returing as part of the
navigation logic.
setHomeForm(String homeForm)
void
protected
boolean
setListModel(ContainerList cmp)
protected
boolean
setListModel(List cmp)
protected void
Allows a subclass to set the list model for the given component
Allows a subclass to set the list model for the given component
setResourceFile(Resources res)
void
Allows the navigation code to avoid storing the resource file and lets the
GC remove it from memory when its not in use
shouldAddBackCommandToMenu()
protected
boolean
Back commands are set implicitly (see allowBackTo to disable that), this
method allows subclasses to disable the behavior where the back
command is also added to the menu (not just set to the back button).
shouldAutoStoreState()
protected
boolean
Indicates whether the UIBuilder should try storing states for forms on its
own by seeking lists, tabs and other statefull elements and keeping their
selection
showContainer(String resourceName, Command sourceCommand,
Component sourceComponent)
Container
Form
protected void
Method Summary
756
Field Detail
FORM_STATE_KEY_NAME
public static final String FORM_STATE_KEY_NAME
A key in the form state hashtable used in the back command navigation
See Also:
Constant Field Values
FORM_STATE_KEY_TITLE
public static final String FORM_STATE_KEY_TITLE
A key in the form state hashtable used in the back command navigation
See Also:
Constant Field Values
FORM_STATE_KEY_FOCUS
public static final String FORM_STATE_KEY_FOCUS
A key in the form state hashtable used in the back command navigation
See Also:
Constant Field Values
FORM_STATE_KEY_SELECTION
public static final String FORM_STATE_KEY_SELECTION
A key in the form state hashtable used in the back command navigation
See Also:
Constant Field Values
BACK_COMMAND_ID
public static final int BACK_COMMAND_ID
See Also:
Constant Field Values
Constructor Detail
UIBuilder
public UIBuilder()
Method Detail
isBlockAnalytics
public static boolean isBlockAnalytics()
Enables blocking analytics in the UIBuilder, this is useful for the designer tool.
Returns:
the blockAnalytics
setBlockAnalytics
public static void setBlockAnalytics(boolean aBlockAnalytics)
Enables blocking analytics in the UIBuilder, this is useful for the designer tool.
Parameters:
757
Removes a navigation frame from the stack, this is useful in case you want to go
back to a form in the middle of the navigation stack.
setBackDestination
protected void setBackDestination(String formName)
Pops the navigation stack until it finds form name and the back button will match form
name if form name isn't in the stack this method will fail
Parameters:
formName - the name of the form to navigate back to.
formNavigationStackDebug
protected String formNavigationStackDebug()
Useful method for logging form navigation, it returns a string representing the
navigation state which can be used to analyze crash reports
Returns:
A string representing form states
isBackCommandEnabled
public boolean isBackCommandEnabled()
This method allows the UIBuilder to package a smaller portion of Codename One into
the JAR and add support for additional 3rd party components to the GUI builder.
Components must be registered using their UIID name, by default all the content of
com.codename1.ui is registered however subpackages and 3rd party components
are not. Registration is essential for obfuscation to work properly!
Parameters:
name - the name of the component (UIID)
cmp - the class for the given component
analyticsCallback
protected void analyticsCallback(String page,
String referrer)
Creates the container defined under the given name in the res file
Parameters:
resPath - the path to the res file containing the UI widget
Method Detail
758
Creates the container defined under the given name in the res file
Parameters:
res - the res file containing the UI widget
resourceName - the name of the widget in the res file
Returns:
a Codename One container instance
findByName
public Component findByName(String name,
Component rootComponent)
This method can be overriden to create custom components in a custom way, the
component type is a shorthand for the component name and not the full name of the
class. By default this method returns null which indicates Codename One should try
to reolve the component on its own.
Parameters:
componentType - the type of the component from the UI builder
cls - assumed component class based on the component registry
Returns:
a new component instance or null
postCreateComponent
protected void postCreateComponent(Component cmp)
Binds the given listener object to the component, this works seamlessly for common
Codename One events but might be an issue with custom components and custom
listener types so this method can be overloaded to add support for such cases.
Method Detail
759
Allows a subclass to set the list model for the given component
Parameters:
cmp - the list whose model may be set
Returns:
true if a model was set by this method
setListModel
protected boolean setListModel(ContainerList cmp)
Allows a subclass to set the list model for the given component
Parameters:
cmp - the list whose model may be set
Returns:
true if a model was set by this method
createCommand
protected Command createCommand(String commandName,
Image icon,
int commandId,
String action)
Creates a command instance. This method is invoked by the loading code and can
be overriden to create a subclass of the Command class.
Parameters:
commandName - the label on the command
icon - the icon for the command
commandId - the id of the command
action - the action assigned to the command if such an action is defined
Returns:
a new command instance
fetchResourceFile
protected Resources fetchResourceFile()
Allows the navigation code to avoid storing the resource file and lets the GC remove
it from memory when its not in use
Returns:
the resourceFilePath
setResourceFilePath
public void setResourceFilePath(String resourceFilePath)
Allows the navigation code to avoid storing the resource file and lets the GC remove
it from memory when its not in use
Parameters:
resourceFilePath - the resourceFilePath to set
Method Detail
760
Adds a command listener that would be bound to all forms in the GUI seamlessly
Parameters:
l - the listener to bind
removeCommandListener
public void removeCommandListener(ActionListener l)
Adds a component listener that would be bound when a UI for this form is created.
Notice that this method is only effective before the form was created and would do
nothing for an existing form
Parameters:
formName - the name of the form to which the listener should be bound
componentName - the name of the component to bind to
listener - the listener to bind, common listener types are supported
removeComponentListener
public void removeComponentListener(String formName,
String componentName,
Object listener)
Method Detail
761
This method is invoked for every component to which an action event listener can be
bound and delivers the event data for the given component seamlessly.
Parameters:
c - the component broadcasting the event
event - the event meta data
asyncCommandProcess
protected void asyncCommandProcess(Command cmd,
ActionEvent sourceEvent)
Warning: This method is invoked OFF the EDT and is intended for usage with
asynchronous command processing. This method is invoked when the UI indicates
that an operation should occur in the background. To finish the processing of the
operation within the EDT one should override the postAsyncCommand() method.
Parameters:
cmd - the command requiring background processing
sourceEvent - the triggering event
postAsyncCommand
protected void postAsyncCommand(Command cmd,
ActionEvent sourceEvent)
Warning: this method is invoked on a separate thread. This method is invoked when
a next form property is defined, this property indicates a background process for a
form of a transitional nature should take place (e.g. splash screen, IO etc.) after
which the next form should be shown. After this method completes the next form is
shown.
Parameters:
f - the form for which the background thread was constructed, notice that
most methods are not threadsafe and one should use callSerially* in this
method when mutating the form.
Returns:
if false is returned from this method navigation should not proceed to that
given form
getFormState
protected Hashtable getFormState(Form f)
Returns the state of the current form which we are about to leave as part of the
navigation logic. When a back command will return to this form the state would be
restored using setFormState. The default implementation of this method restores
focus and list selection. You can add arbitrary keys to the form state, keys starting
with a $ sign are reserved for the UIBuilder base class use.
Method Detail
762
By default Codename One stores the states of components in the navigation graph
as it moves between forms. However, some components aren't recognized by
Codename One by default to enable smaller executable size. This method can be
overriden to enable storing the state of custom components
Parameters:
c - the component whose state should be restored
destination - the hashtable containing the state
storeComponentState
protected void storeComponentState(Component c,
Hashtable destination)
By default Codename One stores the states of components in the navigation graph
as it moves between forms. However, some components aren't recognized by
Codename One by default to enable smaller executable size. This method can be
overriden to enable storing the state of custom components
Parameters:
c - the component whose state should be stored
destination - the destination hashtable
shouldAutoStoreState
protected boolean shouldAutoStoreState()
Indicates whether the UIBuilder should try storing states for forms on its own by
seeking lists, tabs and other statefull elements and keeping their selection
Returns:
true to handle state automatically, false otherwise
setFormState
protected void setFormState(Form f,
Hashtable state)
Sets the state of the current form to which we are returing as part of the navigation
logic. When a back command is pressed this form state should be restored, it was
obtained via getFormState. The default implementation of this method restores focus
and list selection.
Parameters:
f - the form whose state should be preserved
state - arbitrary state object
getContainerState
protected Hashtable getContainerState(Container cnt)
This method is the container navigation equivalent of getFormState() see that method
for details.
Parameters:
cnt - the container
Returns:
the state
setContainerState
protected void setContainerState(Container cnt,
Hashtable state)
This method is the container navigation equivalent of setFormState() see that method
for details.
Parameters:
cnt - the container
Method Detail
763
This method effectively pops the form navigation stack and goes back to the previous
form if back navigation is enabled and there is a previous form.
back
public void back(Component sourceComponent)
This method effectively pops the form navigation stack and goes back to the previous
form if back navigation is enabled and there is a previous form.
Parameters:
sourceComponent - the component that triggered the back command which
effectively allows us to find the EmbeddedContainer for a case of container
navigation. Null can be used if not applicable.
getBackCommandText
protected String getBackCommandText(String previousFormTitle)
Returns the text for the back command string. This can be controlled in the theme by
the "backUsesTitleBool" constant
Parameters:
previousFormTitle - the title of the previous form
Returns:
the string for the back command inserted implicitly
setBackCommand
protected void setBackCommand(Form f,
Command backCommand)
Invoked internally to set the back command on the form, this method allows
subclasses to change the behavior of back command adding or disable it
Parameters:
f - the form
backCommand - the back command
showContainer
public Container showContainer(String resourceName,
Command sourceCommand,
Component sourceComponent)
Method Detail
764
Useful tool to refresh the current state of a container shown using show container
without pushing another instance to the back stack
Parameters:
cnt - the container thats embedded into the application
reloadForm
public void reloadForm()
Useful tool to refresh the current state of a form shown using show form without
pushing another instance to the back stack
createBackLazyValue
public LazyValue<Form> createBackLazyValue(Form f)
When navigating from one form/container to another we sometimes might not want
the back command to return to the previous container/form but rather to the one
before source. A good example would be a "refresh" command or a toggle button that
changes the form state.
Parameters:
source - the form or container we are leaving
destination - the container or form we are navigating to
Returns:
false if we want a standard back button to source, true if we want to use the
same back button as the one in source
showForm
public Form showForm(String resourceName,
Command sourceCommand)
Method Detail
765
This method allows binding an action that should occur before leaving the given form,
e.g. memory cleanup
Parameters:
f - the form being left
beforeShow
protected void beforeShow(Form f)
This method allows binding an action that should occur before showing the given
form
Parameters:
f - the form about to be shown
onBackNavigation
protected void onBackNavigation()
This callback is invoked to indicate that the upcoming form is shown as part of a
"back" navigation. This is useful for the case of a breadcrumb UI where the navigation
stack is shown at the top of the UI, in that case this method can be used to pop out
the breadcrumb stack.
shouldAddBackCommandToMenu
protected boolean shouldAddBackCommandToMenu()
Back commands are set implicitly (see allowBackTo to disable that), this method
allows subclasses to disable the behavior where the back command is also added to
the menu (not just set to the back button).
Returns:
postShow
protected void postShow(Form f)
This method allows binding an action that should occur immediately after showing the
given form
Parameters:
f - the form that was just shown
beforeShowContainer
protected void beforeShowContainer(Container c)
This method allows binding an action that should occur before showing the given
container
Parameters:
c - the container about to be shown
postShowContainer
protected void postShowContainer(Container c)
This method allows binding an action that should occur immediately after showing the
given container
Parameters:
c - the container that was just shown
onCreateRoot
protected void onCreateRoot(String rootName)
This method allows binding logic that should occur before creating the root object e.g.
a case where a created form needs data fetched for it.
Parameters:
rootName - the name of the root to be created from the resource file
Method Detail
766
Indicates that the UIBuilder should cache resources in memory and never release
them. This is useful with small resource files or high RAM devices since it saves the
cost of constantly fetching the res file from the jar whenever moving between forms.
This can be toggled in the properties (e.g. jad) using the flag: cacheResFile
(true/false) which defaults to false.
Returns:
the keepResourcesInRam
setKeepResourcesInRam
public void setKeepResourcesInRam(boolean keepResourcesInRam)
Indicates that the UIBuilder should cache resources in memory and never release
them. This is useful with small resource files or high RAM devices since it saves the
cost of constantly fetching the res file from the jar whenever moving between forms.
This can be toggled in the properties (e.g. jad) using the flag: cacheResFile
(true/false) which defaults to false.
Parameters:
keepResourcesInRam - the keepResourcesInRam to set
getRootAncestor
protected Container getRootAncestor(Component c)
Returns either the parent form or the component bellow the embedded container
above c.
Parameters:
c - the component whose root ancestor we should find
Returns:
the root
Method Detail
767
Class SwipeBackSupport
java.lang.Object
com.codename1.ui.util.SwipeBackSupport
public class
extends Object
Allows binding a swipe listener to the form that enables the user to swipe back to the previous form.
Constructor Summary
Constructor and Description
SwipeBackSupport()
Method Summary
Modifier and Type
protected void
static void
static void
Constructor Detail
SwipeBackSupport
public SwipeBackSupport()
Method Detail
bindBack
public static void bindBack(Form currentForm,
LazyValue<Form> destination)
Class SwipeBackSupport
768
Method Detail
769
Class Resources
java.lang.Object
com.codename1.ui.util.Resources
public class
extends Object
Loads resources from the binary resource file generated by the Codename One Designer. A resource
is loaded entirely into memory since random file access is not supported in Java ME, any other
approach would be inefficient. This means that memory must be made available to accommodate the
resource file.
Method Summary
Modifier and Type
InputStream
String[]
Font
String[]
static Resources
Image
String[]
Hashtable<String,String>
String[]
int
String[]
int
String[]
Returns the minor version number for this resource file This
value relates to the value from the header defined by the
resource file specification.
getResourceNames()
static Resources
Hashtable
String[]
String[]
Class Resources
770
boolean
static boolean
boolean
boolean
boolean
boolean
boolean
Collection<String>
Deprecated.
animations are no longer distinguished from images in the
resource file, use Image.isAnimation instead
isData(String name)
Enumeration
static Resources
static Resources
static Resources
static Resources
static Resources
static Resources
void
static void
setFailOnMissingTruetype(boolean aFailOnMissingTruetype)
setGlobalResources(Resources res)
static void
static void
static void
Deprecated.
do not use this method!
Method Summary
771
Method Detail
isFailOnMissingTruetype
public static boolean isFailOnMissingTruetype()
Returns:
the failOnMissingTruetype
setFailOnMissingTruetype
public static void setFailOnMissingTruetype(boolean aFailOnMissingTruetype)
Parameters:
aFailOnMissingTruetype
setRuntimeMultiImageEnabled
public static void setRuntimeMultiImageEnabled(boolean b)
This method allows overriding the data of a resource file with another resource file
thus replacing or enhancing existing content with platform specific content. E.g.
default icons for the application can be overriden on a specific platform
Parameters:
input - a new resource file
Throws:
IOException - exception thrown from the stream
setPassword
public static void setPassword(String password)
Returns the version number for this resource file. This value relates to the value from
the header defined by the resource file specification. 0 is returned for legacy versions
of the resource file format.
Returns:
major version number for the resource file
getMinorVersion
public int getMinorVersion()
Returns the minor version number for this resource file This value relates to the value
from the header defined by the resource file specification.
Returns:
minor version number for the resource file
getMetaData
public String[] getMetaData()
Method Detail
772
Method Detail
773
Deprecated. animations are no longer distinguished from images in the resource file,
use Image.isAnimation instead
Returns true if this is an animation resource
Parameters:
name - the name of the resource
Returns:
true if the resource is an animation
Throws:
NullPointerException - if the resource doesn't exist
isData
public boolean isData(String name)
Method Detail
774
Method Detail
775
Returns a hashmap containing localized String key/value pairs for the given locale
name
Parameters:
id - the name of the locale resource
locale - name of the locale resource
Returns:
Hashtable containing key value pairs for localized data
listL10NLocales
public Enumeration listL10NLocales(String id)
Method Detail
776
Parameters:
id - name of the font resource
Returns:
cached font instance
getTheme
public Hashtable getTheme(String id)
Global resources are used by new GUI builder apps to keep track of the applications
resources
Parameters:
res - the resource object used by default in the GUI builder forms
getGlobalResources
public static Resources getGlobalResources()
Global resources are used by new GUI builder apps to keep track of the applications
resources
Returns:
the resource object used by default in the GUI builder forms
Method Detail
777
Class ImageIO
java.lang.Object
com.codename1.ui.util.ImageIO
Enable simple operations on image file & image objects such as dynamic scaling and storage to
binary formats such as JPEG. Use Display.getImageIO() to get an instance of this class.
Field Summary
Modifier and Type
static String
static String
Constructor Summary
Constructor and Description
ImageIO()
Method Summary
Modifier and
Type
static
ImageIO
Dimension
abstract
boolean
void
abstract
void
void
String
Class ImageIO
778
Field Detail
FORMAT_JPEG
public static final String FORMAT_JPEG
Constructor Detail
ImageIO
public ImageIO()
Method Detail
save
public abstract void save(InputStream image,
OutputStream response,
String format,
int width,
int height,
float quality)
throws IOException
save
public void save(Image img,
OutputStream response,
String format,
float quality)
throws IOException
779
save
public void save(String imageFilePath,
OutputStream response,
String format,
int width,
int height,
float quality)
throws IOException
getImageSize
public Dimension getImageSize(String imageFilePath)
throws IOException
saveAndKeepAspect
public String saveAndKeepAspect(String imageFilePath,
String preferredOutputPath,
String format,
int width,
int height,
float quality,
boolean onlyDownscale,
boolean scaleToFill)
throws IOException
Scales an image on disk while maintaining an aspect ratio, the appropriate aspect
size will be picked based on the status of scaleToFill
Parameters:
imageFilePath - the path to the image
preferredOutputPath - the url where the image will be saved
format - the format for the image either FORMAT_JPEG or FORMAT_PNG
width - the desired width, either width or height will be respected based on
aspect dimensions
height - the desired height, either width or height will be respected based on
aspect dimensions
quality - the quality for JPEG scaling
onlyDownscale - will not scale if the resolution to scale will be higher in this
case will return the imageFilePath
scaleToFill - when set to true will pick the larger value so the resulting
image will be at least as big as width x height, when set to false will create an
image that is no bigger than width x height
Returns:
the url for the scaled image or the url of the unscaled image
Throws:
IOException - if the operation fails
Method Detail
780
isFormatSupported
public abstract boolean isFormatSupported(String format)
Method Detail
781
Class GlassTutorial
java.lang.Object
com.codename1.ui.util.GlassTutorial
All Implemented Interfaces:
Painter
public class
extends Object
implements Painter
A Glass Tutorial appears on top of the UI especially on a touch device but could be on any device and
points to/circles components within the UI coupled with explanation of what they do and a tint of the
screen. It is implemented as a GlassPane on top of a Form which is automatically removed when a
user touches the screen or presses a button.
To position elements within the glass tutorial the elements must be associated with a component
instance of the underlying UI and positioned relatively to said component.
The GlassTutorial uses the "GlassTutorial" UIID to paint itself it then paints the hint components in
their proper places.
Constructor Summary
Constructor and Description
GlassTutorial()
Method Summary
Modifier and
Type
void
void
Install the glass tutorial on a form and seamlessly dismiss it when no longer
necessary
void
Constructor Detail
GlassTutorial
public GlassTutorial()
Method Detail
Class GlassTutorial
782
Places a hint within the glass in a position relative to the destinationComponent, the
position is indicated with border layout attributes. Notice you can place multiple
components on a single element and they will be rendered in order e.g. a component
with a border can be used to "circle" the destination by placing it in the CENTER
position and another arrow with text can be places in the south position bellow.
Parameters:
hintComponent - The component that would be renderered in the given
position
destinationComponent - the "hinted" component over which the hint will show
position - the position relative to the destinationComponent in BorderLayout
values e.g. to place the hint above the component just place it in
BorderLayout.NORTH. The center will stretch the component but the other
sides will give the component its exact preferred size.
showOn
public void showOn(Form f)
Install the glass tutorial on a form and seamlessly dismiss it when no longer
necessary
Parameters:
f - the form
paint
public void paint(Graphics g,
Rectangle rect)
Method Detail
783
Class EventDispatcher
java.lang.Object
com.codename1.ui.util.EventDispatcher
public class
extends Object
Handles event dispatching while guaranteeing that all events would be fired properly on the EDT
regardless of their source. This class handles listener registration/removal in a safe and uniform way.
Constructor Summary
Constructor and Description
EventDispatcher()
Method Summary
Modifier
and Type
void
void
void
Add a listener to the dispatcher that would receive the events when they
occurs
fireActionEvent(ActionEvent ev)
Fires the event safely on the EDT without risk of concurrency errors
fireBindTargetChange(Component source, String propertyName,
Object oldValue, Object newValue)
void
Fires the event safely on the EDT without risk of concurrency errors
fireFocus(Component c)
Fires the event safely on the EDT without risk of concurrency errors
fireScrollEvent(int scrollX, int scrollY, int oldscrollX,
int oldscrollY)
Fires the event safely on the EDT without risk of concurrency errors
void
void
Collection
Fires the event safely on the EDT without risk of concurrency errors
fireStyleChangeEvent(String property, Style source)
Vector
boolean
Deprecated.
use getListenerCollection instead, this method will now be VERY SLOW
hasListeners()
boolean
void
void
Class EventDispatcher
Indicates whether this dispatcher blocks when firing events or not, normally a
dispatcher uses callSeriallyAndWait() to be 100% synchronous with event
delivery however this method is very slow.
removeListener(Object listener)
784
setFireStyleEventsOnNonEDT(boolean fire)
When set to true, style events will be dispatched even from non-EDT threads.
Constructor Detail
EventDispatcher
public EventDispatcher()
Method Detail
setFireStyleEventsOnNonEDT
public static void setFireStyleEventsOnNonEDT(boolean fire)
When set to true, style events will be dispatched even from non-EDT threads. When
set to false, when in non-EDT threads, style events will not be dispatched at all (And
developer has to make sure changes will be reflected by calling revalidate after all the
changes) Default is false. Setting this to true results in a performance penalty, and it
is better instead to simply aggregate events performed on non-EDT threads and
when all are over - call revalidate on the relevant container.
Parameters:
fire - true to fire on non-EDT, false otherwise
addListener
public void addListener(Object listener)
Add a listener to the dispatcher that would receive the events when they occurs
Parameters:
listener - a dispatcher listener to add
getListenerVector
public Vector getListenerVector()
Deprecated. use getListenerCollection instead, this method will now be VERY SLOW
Returns the vector of the listeners
Returns:
the vector of listeners attached to the event dispatcher
getListenerCollection
public Collection getListenerCollection()
Method Summary
785
Fires the event safely on the EDT without risk of concurrency errors
Parameters:
index - the index of the event
type - the type of the event
fireBindTargetChange
public void fireBindTargetChange(Component source,
String propertyName,
Object oldValue,
Object newValue)
Fires the event safely on the EDT without risk of concurrency errors
Parameters:
ev - the ActionEvent to fire to the listeners
fireSelectionEvent
public void fireSelectionEvent(int oldSelection,
int newSelection)
Fires the event safely on the EDT without risk of concurrency errors
Parameters:
oldSelection - old selection
newSelection - new selection
fireScrollEvent
public void fireScrollEvent(int
int
int
int
scrollX,
scrollY,
oldscrollX,
oldscrollY)
Fires the event safely on the EDT without risk of concurrency errors
fireFocus
public void fireFocus(Component c)
Fires the event safely on the EDT without risk of concurrency errors
Parameters:
c - the Component that gets the focus event
hasListeners
public boolean hasListeners()
Method Detail
786
Indicates whether this dispatcher blocks when firing events or not, normally a
dispatcher uses callSeriallyAndWait() to be 100% synchronous with event delivery
however this method is very slow. By setting blocking to false the callSerially method
is used which allows much faster execution for IO heavy operations.
Returns:
the blocking state
setBlocking
public void setBlocking(boolean blocking)
Indicates whether this dispatcher blocks when firing events or not, normally a
dispatcher uses callSeriallyAndWait() to be 100% synchronous with event delivery
however this method is very slow. By setting blocking to false the callSerially method
is used which allows much faster execution for IO heavy operations.
Parameters:
blocking - the blocking value
Method Detail
787
Class EmbeddedContainer
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.util.EmbeddedContainer
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
This class is mostly used internally by the GUI builder and isn't very useful for general purpose. The
embedded container allows placing a wholy different UI hierarchy within the current hierarchy and
replace it on the fly.
Field Summary
Constructor Summary
Constructor and Description
EmbeddedContainer()
Default constructor
Method Summary
Modifier and Type
String
void
Class EmbeddedContainer
788
Constructor Detail
EmbeddedContainer
public EmbeddedContainer()
Default constructor
789
Detail
getEmbed
public String getEmbed()
Method Detail
790
Class Effects
java.lang.Object
com.codename1.ui.util.Effects
public class
extends Object
Static utility class useful for simple visual effects that don't quite fit anywhere else in the core API.
Method Summary
Modifier
and Type
static
Image
static void
Deprecated.
use Component.growShrink instead
static
boolean
isGaussianBlurSupported()
static
Image
static
Image
static
Image
Takes the given image and appends an effect of reflection bellow it that is
similar to the way elements appear in water beneath them.
reflectionImage(Image source, float mirrorRatio, int alphaRatio)
Takes the given image and appends an effect of reflection bellow it that is
similar to the way elements appear in water beneath them.
reflectionImage(Image source, float mirrorRatio, int alphaRatio,
int spacing)
Takes the given image and appends an effect of reflection bellow it that is
similar to the way elements appear in water beneath them.
verticalPerspective(Image i, float topScaleRatio,
float bottomScaleRatio, float verticalShrink)
static
Image
Method Detail
reflectionImage
public static Image reflectionImage(Image source)
Takes the given image and appends an effect of reflection bellow it that is similar to
the way elements appear in water beneath them. This method shouldn't be used
when numAlpha is very low.
Parameters:
source - image to add the reflection effect to
Returns:
new image with a reflection effect for the source image
Class Effects
791
Takes the given image and appends an effect of reflection bellow it that is similar to
the way elements appear in water beneath them. This method shouldn't be used
when numAlpha is very low.
Parameters:
source - image to add the reflection effect to
mirrorRatio - generally less than 1, a mirror ration of 0.5f will create a mirror
image half the height of the image, 0.75f will create a 3 quarter height mirror
etc.
alphaRatio - starting point for the alpha value in the mirror, this should be a
number between 0 - 255 (recommended larger than 0) indicating the opacity
of the closest pixel. For a mirror thats completely opaque use 255. A
recommended value would be between 128 to 90.
Returns:
new image with a reflection effect for the source image
reflectionImage
public static Image reflectionImage(Image source,
float mirrorRatio,
int alphaRatio,
int spacing)
Takes the given image and appends an effect of reflection bellow it that is similar to
the way elements appear in water beneath them. This method shouldn't be used
when numAlpha is very low.
Parameters:
source - image to add the reflection effect to
mirrorRatio - generally less than 1, a mirror ration of 0.5f will create a mirror
image half the height of the image, 0.75f will create a 3 quarter height mirror
etc.
alphaRatio - starting point for the alpha value in the mirror, this should be a
number between 0 - 255 (recommended larger than 0) indicating the opacity
of the closest pixel. For a mirror thats completely opaque use 255. A
recommended value would be between 128 to 90.
spacing - the distance in pixels between the image and its reflection
Returns:
new image with a reflection effect for the source image
growShrink
public static void growShrink(Component c,
int duration)
i,
topScaleRatio,
bottomScaleRatio,
verticalShrink)
Skews an image in a faux perspective transform on the vertical axis, this is effectively
a fast scale algorithm that both shrinks the image vertically and reduces the width
Method Detail
792
Create a blur image from the given image. The algorithm is gaussian blur https://en.wikipedia.org/wiki/Gaussian_blur
Parameters:
image - the image to blur
radius - the radius to be used in the algorithm
isGaussianBlurSupported
public static boolean isGaussianBlurSupported()
Method Detail
793
Interface TreeModel
All Known Implementing Classes:
FileTreeModel
public interface
Arranges tree node objects, a node can essentially be anything and it will be displayed in a hierarchy
using the Tree
And heres a more "real world" example showing an XML hierarchy in a Tree:
Interface TreeModel
794
Method Summary
Modifier and
Type
Returns the child objects representing the given parent, null should return
the root objects
Vector
boolean
isLeaf(Object node)
Method Detail
getChildren
Vector getChildren(Object parent)
Returns the child objects representing the given parent, null should return the root
objects
Parameters:
parent - the parent object whose children should be returned, null would
return the tree roots
Returns:
the children of the given node within the tree
isLeaf
boolean isLeaf(Object node)
Method Summary
795
Class Tree
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.tree.Tree
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
Direct Known Subclasses:
FileTree
public class
extends Container
The Tree component allows constructing simple tree component hierarchies that can be expanded
seamlessly with no limit. The tree is bound to a model that can provide data with free form depth such
as file system or similarly structured data.
To customize the look of the tree the component can be derived and component creation can be
replaced.
And heres a more "real world" example showing an XML hierarchy in a Tree:
Method Detail
796
Field Summary
Constructor Summary
Constructor and Description
Tree()
Constructor for usage by GUI builder and automated tools, normally one should use the
version that accepts the model
Tree(TreeModel model)
Method Summary
Modifier
and Type
void
protected
void
Class Tree
Since a node may be any component type developers should override this method to add
the click listener to the given component.
protected
Dimension
calcPreferredSize()
protected
String
childToDisplayLabel(Object child)
Converts a tree child to a label, this method can be overriden for simple rendering effects
797
void
protected
Component
protected
Button
Creates a node within the tree, this method is protected allowing tree to be subclassed to
logic of individual tree buttons.
createNodeComponent(Object node, int depth)
Deprecated.
replaced with createNode, bindNodeListener and setNodeIcon
expandPath(boolean animate, Object... path)
void
void
TreeModel
getModel()
String[]
A component may expose mutable property names for a UI designer to manipulate, this A
usage internally by the GUI builder code
getPropertyTypeNames()
String[]
Class[]
This method is here to workaround an XMLVM array type bug where property types aren'
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListM
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
Returns the current value of the property name, this method is used by the GUI builder
getSelectedItem()
Object
boolean
isMultilineMode()
Toggles a mode where rows in the tree can be broken since span buttons will be used ins
removeLeafListener(ActionListener l)
void
static
void
setFolderIcon(Image folderIcon)
static
void
setFolderOpenIcon(Image folderIcon)
void
void
Toggles a mode where rows in the tree can be broken since span buttons will be used ins
static
void
setNodeIcon(Image nodeIcon)
protected
void
String
Sets a new value to the given property, returns an error message if failed and null if succe
Method Summary
798
Constructor Detail
Tree
public Tree()
Constructor for usage by GUI builder and automated tools, normally one should use
the version that accepts the model
799
Method Detail
isMultilineMode
public boolean isMultilineMode()
Toggles a mode where rows in the tree can be broken since span buttons will be
used instead of plain buttons.
Returns:
the multilineMode
setMultilineMode
public void setMultilineMode(boolean multilineMode)
Toggles a mode where rows in the tree can be broken since span buttons will be
used instead of plain buttons.
Parameters:
multilineMode - the multilineMode to set
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Constructor Detail
800
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
getModel
public TreeModel getModel()
Method Detail
801
expansion
collapsePath
public void collapsePath(Object... path)
Since a node may be any component type developers should override this method to
add support for binding the click listener to the given component.
Parameters:
l - listener interface
node - node component returned by createNode
setNodeIcon
protected void setNodeIcon(Image icon,
Component node)
Sets the icon for the given node similar in scope to bindNodeListener
Parameters:
icon - the icon for the node
node - the node instance
createNode
protected Component createNode(Object node,
int depth)
Creates a node within the tree, this method is protected allowing tree to be
subclassed to replace the rendering logic of individual tree buttons.
Parameters:
node - the node object from the model to display on the button
depth - the depth within the tree (normally represented by indenting the entry)
Returns:
a button representing the node within the tree
childToDisplayLabel
protected String childToDisplayLabel(Object child)
Converts a tree child to a label, this method can be overriden for simple rendering
effects
Method Detail
802
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Container
Returns:
the calculated preferred size based on component content
Method Detail
803
Interface TableModel
All Known Implementing Classes:
DefaultTableModel
public interface
The table and table model class are complimentry classes allowing the quick construction of tabular
data controls. The table model represents the data source according to which the table is constructed.
Method Summary
Modifier and Type
void
int
String
int
Object
boolean
void
void
Method Detail
getRowCount
int getRowCount()
Interface TableModel
804
Method Detail
805
Class TableLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.table.TableLayout
public class
extends Layout
TableLayout is a very elaborate constraint based layout manager that can arrange elements in
rows/columns while defining constraints to control complex behavior such as spanning,
alignment/weight etc.
Notice that the table layout is in the com.codename1.ui.table package and not in the layouts package.
This is due to the fact that TableLayout was originally designed for the Table class.
Despite being constraint based the table layout isn't strict about constraints and will implicitly add a
constraint when one is missing. However, unlike grid layout table layout won't implicitly add a row if
the row/column count is incorrect
E.g this creates a 2x2 table but adds 5 elements. The 5th element won't show:
Form hi = new Form("Table Layout 2x2", new TableLayout(2, 2));
hi.add(new Label("First")).
add(new Label("Second")).
add(new Label("Third")).
add(new Label("Fourth")).
add(new Label("Fifth"));
hi.show();
Table layout supports the ability to grow the last column which can be enabled using the
setGrowHorizontally method. You can also use a shortened terse syntax to construct a table layout
however since the table layout is a constraint based layout you won't be able to utilize its full power
with this syntax.
The default usage of the encloseIn below uses the setGrowHorizontally flag.
Container tl = TableLayout.encloseIn(2, new Label("First"),
new Label("Second"),
Class TableLayout
806
Class TableLayout
807
static class
Represents the layout constraint for an entry within the table indicating the
desired position/behavior of the component.
Constructor Summary
Constructor and Description
TableLayout(int rows, int columns)
Method Summary
Modifier and Type
void
TableLayout.Constraint
TableLayout.Constraint
static Container
static Container
boolean
808
Returns the spanning for the table cell at the given coordinate
getCellVerticalSpan(int row, int column)
Returns the spanning for the table cell at the given coordinate
getColumnPosition(int col)
static int
static int
static int
int
int
Dimension
int
int
boolean
boolean
Returns the column where the next operation of add will appear
getNextRow()
Returns the row where the next operation of add will appear
getPreferredSize(Container parent)
boolean
boolean
boolean
boolean
void
void
static void
static void
Method Summary
809
void
setMinimumSizePerColumn(int minimumSize)
static void
Sets the minimum size for a column in the table, this is applicable
for tables that are not scrollable on the X axis.
toString()
String
Constructor Detail
TableLayout
public TableLayout(int rows,
int columns)
Method Detail
getRows
public int getRows()
810
in class Layout
Parameters:
parent - the given parent container
getRowPosition
public int getRowPosition(int row)
Returns the position of the given table row. A valid value is only returned after the
layout occurred.
Parameters:
row - the row in the table
Returns:
the Y position in pixels or -1 if layout hasn't occured/row is too large etc.
getColumnPosition
public int getColumnPosition(int col)
Returns the position of the given table column. A valid value is only returned after the
layout occurred.
Parameters:
col - the column in the table
Returns:
the X position in pixels or -1 if layout hasn't occured/column is too large etc.
getPreferredSize
public Dimension getPreferredSize(Container parent)
Returns the row where the next operation of add will appear
Returns:
the row where the next operation of add will appear
getNextColumn
public int getNextColumn()
Returns the column where the next operation of add will appear
Returns:
the column where the next operation of add will appear
addLayoutComponent
public void addLayoutComponent(Object value,
Component comp,
Container c)
Some layouts can optionally track the addition of elements with meta-data that allows
the user to "hint" on object positioning.
Overrides:
addLayoutComponent in class Layout
Parameters:
value - optional meta data information, like alignment orientation
comp - the added component to the layout
c - the parent container
getCellHorizontalSpan
public int getCellHorizontalSpan(int row,
int column)
Method Detail
811
Returns the spanning for the table cell at the given coordinate
Parameters:
row - row in the table
column - column within the table
Returns:
the amount of spanning 1 for no spanning
isCellSpannedThroughVertically
public boolean isCellSpannedThroughVertically(int row,
int column)
Returns true if the cell at the given position is spanned through vertically
Parameters:
row - cell row
column - cell column
Returns:
true if the cell is a part of a span for another cell
isCellSpannedThroughHorizontally
public boolean isCellSpannedThroughHorizontally(int row,
int column)
Returns true if the cell at the given position is spanned through horizontally
Parameters:
row - cell row
column - cell column
Returns:
true if the cell is a part of a span for another cell
hasVerticalSpanning
public boolean hasVerticalSpanning()
Removes the component from the layout this operation is only useful if the layout
maintains references to components within it
Overrides:
removeLayoutComponent in class Layout
Parameters:
comp - the removed component from layout
Method Detail
812
Sets the minimum size for a column in the table, this is applicable for tables that are
not scrollable on the X axis. This will force the earlier columns to leave room for the
latter columns.
Parameters:
minimumSize - the minimum width of the column
getMinimumSizePerColumn
public static int getMinimumSizePerColumn()
Indicates the minimum size for a column in the table, this is applicable for tables that
are not scrollable on the X axis. This will force the earlier columns to leave room for
the latter columns.
Returns:
the minimum width of the column
setDefaultColumnWidth
public static void setDefaultColumnWidth(int w)
Indicates the default (in percentage) for the column width, -1 indicates automatic
sizing
Parameters:
w - width in percentage
getDefaultColumnWidth
public static int getDefaultColumnWidth()
Indicates the default (in percentage) for the column width, -1 indicates automatic
sizing
Returns:
width in percentage
Method Detail
813
Indicates the default (in percentage) for the row height, -1 indicates automatic sizing
Parameters:
h - height in percentage
getDefaultRowHeight
public static int getDefaultRowHeight()
Indicates the default (in percentage) for the row height, -1 indicates automatic sizing
Returns:
height in percentage
toString
public String toString()
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
equals
public boolean equals(Object o)
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Layout
isConstraintTracking
public boolean isConstraintTracking()
If this method returns true, the addLayoutComponent method will be called when
replacing a layout for every component within the container
Overrides:
isConstraintTracking in class Layout
Returns:
false by default
isGrowHorizontally
public boolean isGrowHorizontally()
Indicates whether the table layout should grow horizontally to take up available space
by stretching the last column
Returns:
the growHorizontally
Method Detail
814
Indicates whether the table layout should grow horizontally to take up available space
by stretching the last column
Parameters:
growHorizontally - the growHorizontally to set
encloseIn
public static Container encloseIn(int columns,
Component... cmps)
Creates a table layout container that grows the last column horizontally, the number
of rows is automatically calculated based on the number of columns. See usage:
Container tl = TableLayout.encloseIn(2, new Label("First"),
new Label("Second"),
new Label("Third"),
new Label("Fourth"),
new Label("Fifth")));
Parameters:
columns - the number
cmps - components to
of columns
add
Returns:
a newly created table layout container with the components in it
encloseIn
public static Container encloseIn(int columns,
boolean growHorizontally,
Component... cmps)
Method Detail
815
Parameters:
columns - the number of columns
growHorizontally - true to grow the
cmps - components to add
Returns:
a newly created table layout container with the components in it
Method Detail
816
Class TableLayout.Constraint
java.lang.Object
com.codename1.ui.table.TableLayout.Constraint
Enclosing class:
TableLayout
Represents the layout constraint for an entry within the table indicating the desired position/behavior
of the component.
Constructor Summary
Constructor and Description
Constraint()
Method Summary
Modifier and Type
int
getColumn()
int
getHeightPercentage()
int
getHorizontalAlign()
int
getHorizontalSpan()
int
getRow()
int
getVerticalAlign()
int
getVerticalSpan()
int
getWidthPercentage()
TableLayout.Constraint
TableLayout.Constraint
heightPercentage(int height)
TableLayout.Constraint
void
void
void
void
void
void
Class TableLayout.Constraint
817
String
TableLayout.Constraint
verticalAlign(int valign)
TableLayout.Constraint
TableLayout.Constraint
Constructor Detail
Constraint
public Constraint()
Method Detail
toString
public String toString()
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
setVerticalSpan
public void setVerticalSpan(int span)
Sets the cells to span vertically, this number must never be smaller than 1
Parameters:
span - a number larger than 1
verticalSpan
public TableLayout.Constraint verticalSpan(int span)
Sets the cells to span vertically, this number must never be smaller than 1
Parameters:
span - a number larger than 1
Returns:
this
setHorizontalSpan
public void setHorizontalSpan(int span)
Sets the cells to span horizontally, this number must never be smaller than 1
Parameters:
span - a number larger than 1
Method Summary
818
Sets the cells to span horizontally, this number must never be smaller than 1
Parameters:
span - a number larger than 1
setWidthPercentage
public void setWidthPercentage(int width)
Method Detail
819
Returns:
the row
getColumn
public int getColumn()
Returns:
the column
getWidthPercentage
public int getWidthPercentage()
Returns:
the width
getHeightPercentage
public int getHeightPercentage()
Returns:
the height
getHorizontalSpan
public int getHorizontalSpan()
Returns:
the spanHorizontal
getVerticalSpan
public int getVerticalSpan()
Returns:
the spanVertical
getHorizontalAlign
public int getHorizontalAlign()
Returns:
the align
getVerticalAlign
public int getVerticalAlign()
Returns:
the valign
Method Detail
820
Class Table
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.table.Table
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
The Table class represents a grid of data that can be used for rendering a grid of components/labels.
The table reflects and updates the underlying model data. Table relies heavily on the TableLayout
class and TableModel interface to present its UI. Unlike a List a Table doesn't feature a separate
renderer and instead allows developers to derive the class.
Form hi = new Form("Table", new BorderLayout());
TableModel model = new DefaultTableModel(new String[] {"Col 1", "Col 2", "Col 3"}, new Object[][] {
{"Row 1", "Row A", "Row X"},
{"Row 2", "Row B can now stretch", null},
{"Row 3", "Row C", "Row Z"},
{"Row 4", "Row D", "Row K"},
}) {
public boolean isCellEditable(int row, int col) {
return col != 0;
}
};
Table table = new Table(model) {
{@literal @}Override
protected Component createCell(Object value, int row, int column, boolean editable) { (1)
Component cell;
if(row == 1 && column == 1) { (2)
Picker p = new Picker();
p.setType(Display.PICKER_TYPE_STRINGS);
p.setStrings("Row B can now stretch", "This is a good value", "So Is This", "Better than text field");
p.setSelectedString((String)value); (3)
p.setUIID("TableCell");
p.addActionListener((e) -> getModel().setValueAt(row, column, p.getSelectedString())); (4)
cell = p;
} else {
cell = super.createCell(value, row, column, editable);
}
if(row > -1 && row % 2 == 0) { (5)
// pinstripe effect
cell.getAllStyles().setBgColor(0xeeeeee);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}
{@literal @}Override
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
TableLayout.Constraint con = super.createCellConstraint(value, row, column);
if(row == 1 && column == 1) {
con.setHorizontalSpan(2);
}
con.setWidthPercentage(33);
return con;
}
};
hi.add(BorderLayout.CENTER, table);
hi.show();
Class Table
821
Field Summary
Modifier and Type
static int
static int
static int
static int
Constructor Summary
Constructor and Description
Table()
Constructor for usage by GUI builder and automated tools, normally one should use the
version that accepts the model
Table(TableModel model)
Field Summary
822
Method Summary
Modifier and Type
protected Component
protected
TableLayout.Constraint
Creates the table cell constraint for the given cell, this method can be over
the table constraints.
deinitialize()
void
int
int
int
int
TableModel
Indicates the alignment of the cells see label alignment for details
getCellColumn(Component cell)
String[]
String[]
Class[]
Object
int
int
int
This method is here to workaround an XMLVM array type bug where prope
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the
getSelectedColumn()
Indicates the alignment of the title see label alignment for details
includeNullValues()
protected boolean
void
boolean
boolean
Allows subclasses to bind functionality that relies on fully initialized and "re
isDrawBorder()
Indicates whether the table should render a table header as the first row
paintGlass(Graphics g)
protected void
void
void
void
void
Method Summary
Sets the spacing of cells border (relevant only for separate borders and no
setCellAlignment(int cellAlignment)
Indicates the alignment of the cells see label alignment for details
setCollapseBorder(boolean collapseBorder)
Indicates whether the borders of the cells should collapse to form a one lin
setDrawBorder(boolean drawBorder)
823
void
Indicates whether empty cells should have borders (relevant only for separ
setIncludeHeader(boolean includeHeader)
void
Indicates whether the table should render a table header as the first row
setInnerBorderMode(int innerBorder)
Sets how to draw the inner border (All of it, only rows/columns, none, grou
other than NONE/ALL will result in the border drawing as collapsed whethe
void
setModel(TableModel model)
void
String
Sets a new value to the given property, returns an error message if failed a
setTitleAlignment(int titleAlignment)
void
Indicates the alignment of the title see label alignment for details
protected boolean
shouldDrawInnerBorderAfterRow(int row)
Returns whether an inner border should be drawn after the specified row.
824
Field Detail
INNER_BORDERS_NONE
public static final int INNER_BORDERS_NONE
Constructor Detail
Table
public Table()
Constructor for usage by GUI builder and automated tools, normally one should use
the version that accepts the model
825
Method Detail
getSelectedRow
public int getSelectedRow()
This method can be overriden by a component to draw on top of itself or its children
after the component or the children finished drawing in a similar way to the glass
pane but more refined per component
Overrides:
paintGlass in class Container
Parameters:
g - the graphics context
createCell
protected Component createCell(Object value,
int row,
int column,
boolean editable)
Constructor Detail
826
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
deinitialize
public void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
setModel
public void setModel(TableModel model)
Sets how to draw the inner border (All of it, only rows/columns, none, groups) Note
that setting to any mode other than NONE/ALL will result in the border drawing as
collapsed whether this is a collpased border or not
Parameters:
innerBorder - one of the INNER_BORDER_* constants
getInnerBorderMode
public int getInnerBorderMode()
Method Detail
827
Returns whether an inner border should be drawn after the specified row. This allows
customization in subclasses to create for example the effects of segments in atable,
i.e. instead of a line after each row - lines after "chunks" of rows. Note that this is
queried only when the inner border mode is set to INNER_BORDER_ROWS
Parameters:
row - The row in question
Returns:
true to draw inner border, false otherwise
setCollapseBorder
public void setCollapseBorder(boolean collapseBorder)
Indicates whether the borders of the cells should collapse to form a one line border
Parameters:
collapseBorder - true to collapse (default), false for separate borders
setDrawEmptyCellsBorder
public void setDrawEmptyCellsBorder(boolean drawEmptyCellsBorder)
Indicates whether empty cells should have borders (relevant only for separate
borders and not for collapsed)
Parameters:
drawEmptyCellsBorder - - true to draw (default), false otherwise
setBorderSpacing
public void setBorderSpacing(int horizontal,
int vertical)
Sets the spacing of cells border (relevant only for separate borders and not for
collapsed)
Parameters:
horizontal - - The horizontal spacing
vertical - - The vertical spacing
getTitleAlignment
public int getTitleAlignment()
Indicates the alignment of the title see label alignment for details
Returns:
the title alignment
See Also:
Label.setAlignment(int)
setTitleAlignment
public void setTitleAlignment(int titleAlignment)
Indicates the alignment of the title see label alignment for details
Parameters:
titleAlignment - the title alignment
See Also:
Label.setAlignment(int)
getCellColumn
public int getCellColumn(Component cell)
Method Detail
828
Indicates the alignment of the cells see label alignment for details
Returns:
the cell alignment
See Also:
Label.setAlignment(int)
setCellAlignment
public void setCellAlignment(int cellAlignment)
Indicates the alignment of the cells see label alignment for details
Parameters:
cellAlignment - the table cell alignment
See Also:
Label.setAlignment(int)
isIncludeHeader
public boolean isIncludeHeader()
Indicates whether the table should render a table header as the first row
Returns:
the includeHeader
setIncludeHeader
public void setIncludeHeader(boolean includeHeader)
Indicates whether the table should render a table header as the first row
Parameters:
includeHeader - the includeHeader to set
createCellConstraint
protected TableLayout.Constraint createCellConstraint(Object value,
int row,
int column)
Creates the table cell constraint for the given cell, this method can be overriden for
the purposes of modifying the table constraints.
Parameters:
value - the value of the cell
row - the table row
column - the table column
Returns:
the table constraint
getPropertyNames
public String[] getPropertyNames()
Method Detail
829
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
830
Class DefaultTableModel
java.lang.Object
com.codename1.ui.table.DefaultTableModel
All Implemented Interfaces:
TableModel
public class
extends Object
implements TableModel
Class DefaultTableModel
831
Constructor Summary
Constructor and Description
DefaultTableModel(String[] columnNames, Object[][] data)
Method Summary
Modifier and Type
void
void
int
String
int
Object
void
boolean
void
void
Constructor Summary
Inserts the given row to the table data at the given offset
isCellEditable(int row, int column)
832
void
Constructor Detail
DefaultTableModel
public DefaultTableModel(String[] columnNames,
Object[][] data)
Method Detail
getRowCount
public int getRowCount()
Method Summary
833
Method Detail
834
Inserts the given row to the table data at the given offset
Parameters:
offset - position within the table that is 0 or larger yet smaller than the row
count
row - array or row items, notice that row.length should match the column
count exactly!
removeRow
public void removeRow(int offset)
Method Detail
835
Class TimeSpinner
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.spinner.BaseSpinner
com.codename1.ui.spinner.TimeSpinner
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
Direct Known Subclasses:
DateTimeSpinner
public class
extends BaseSpinner
Field Summary
Constructor Summary
Constructor and Description
TimeSpinner()
Default constructor
Method Summary
Modifier
and Type
int
int
getCurrentMinute()
int
getMinuteStep()
getPropertyNames()
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
Returns the current value of the property name, this method is used by the GUI
builder
boolean
isCurrentMeridiem()
isDurationMode()
boolean
Class TimeSpinner
Duration mode uses the time spinner to indicate a duration in hours and
minutes
836
isShowMeridiem()
setCurrentHour(int currentHour)
void
void
setCurrentMeridiem(boolean currentMeridiem)
void
setCurrentMinute(int currentMinute)
setDurationMode(boolean durationMode)
void
Duration mode uses the time spinner to indicate a duration in hours and
minutes
void
setMinuteStep(int minuteStep)
setPropertyValue(String name, Object value)
String
Sets a new value to the given property, returns an error message if failed and
null if successful.
setShowMeridiem(boolean showMeridiem)
void
Method Summary
837
Constructor Detail
TimeSpinner
public TimeSpinner()
Default constructor
Method Detail
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
838
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
getMinuteStep
public int getMinuteStep()
Returns:
the minuteStep
setMinuteStep
public void setMinuteStep(int minuteStep)
Parameters:
minuteStep
isShowMeridiem
public boolean isShowMeridiem()
Returns:
the showMeridiem
setShowMeridiem
public void setShowMeridiem(boolean showMeridiem)
Returns:
the currentMinute
Method Detail
839
Parameters:
currentMinute
isCurrentMeridiem
public boolean isCurrentMeridiem()
Returns:
the currentMeridiem
setCurrentMeridiem
public void setCurrentMeridiem(boolean currentMeridiem)
Parameters:
currentMeridiem
isDurationMode
public boolean isDurationMode()
Duration mode uses the time spinner to indicate a duration in hours and minutes
Returns:
the durationMode
setDurationMode
public void setDurationMode(boolean durationMode)
Duration mode uses the time spinner to indicate a duration in hours and minutes
Parameters:
durationMode - the durationMode to set
Method Detail
840
Class Picker
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.Button
com.codename1.ui.spinner.Picker
All Implemented Interfaces:
Animation, StyleListener
public class
extends Button
is a component and API that allows either popping up a spinner or using the native picker API
when applicable. This is quite important for some platforms where the native spinner behavior is very
hard to replicate.
Picker
Class Picker
841
Class Picker
842
Field Summary
Constructor Summary
Constructor and Description
Picker()
Default constructor
Method Summary
Modifier and
Type
Date
SimpleDateFormat
int
int
Field Summary
Returns the date, this value is used both for type date/date and time.
getFormatter()
843
Object
getSelectedString()
String
String[]
getStrings()
This value is only used for time type and is ignored in the case of date
and time where both are embedded within the date.
int
getType()
int
boolean
isShowMeridiem()
void
Sets the date, this value is used both for type date/date and time.
setFormatter(SimpleDateFormat formatter)
void
void
void
void
setSelectedString(String str)
void
void
void
This value is only used for time type and is ignored in the case of date
and time where both are embedded within the date.
void
void
void
updateValue()
protected void
Updates the display value of the picker, subclasses can override this to
invoke set text with the right value
Method Summary
844
Constructor Detail
845
Default constructor
Method Detail
setType
public void setType(int type)
Returns the date, this value is used both for type date/date and time. Notice that this
value isn't used for time
Returns:
the date object
setDate
public void setDate(Date d)
Sets the date, this value is used both for type date/date and time. Notice that this
value isn't used for time. Notice that this value will have no effect if the picker is
currently showing.
Parameters:
d - the new date
setStrings
public void setStrings(String... strs)
Constructor Detail
846
Updates the display value of the picker, subclasses can override this to invoke set
text with the right value
setTime
public void setTime(int time)
This value is only used for time type and is ignored in the case of date and time
where both are embedded within the date.
Parameters:
time - the time value as minutes since midnight e.g. 630 is 10:30am
setTime
public void setTime(int hour,
int minute)
This value is only used for time type and is ignored in the case of date and time
where both are embedded within the date.
Returns:
the time value as minutes since midnight e.g. 630 is 10:30am
isShowMeridiem
public boolean isShowMeridiem()
When using a lightweight spinner this will be used as the rendering prototype
Returns:
the renderingPrototype
setRenderingPrototype
public void setRenderingPrototype(Object renderingPrototype)
When using a lightweight spinner this will be used as the rendering prototype
Parameters:
renderingPrototype - the renderingPrototype to set
Method Detail
847
The preferred width of the popup dialog for the picker. This will only be used on
devices where the popup width and height are configurable, such as the iPad or
tablets. On iPhone, the picker always spans the width of the screen along the bottom.
Parameters:
width - The preferred width of the popup.
setPreferredPopupHeight
public void setPreferredPopupHeight(int height)
The preferred height of the popup dialog for the picker. This will only be used on
devices where the popup width and height are configurable, such as the iPad or
tablets. On iPhone, the picker always spans the width of the screen along the bottom.
Parameters:
width - The preferred width of the popup.
getPreferredPopupWidth
public int getPreferredPopupWidth()
The preferred width of the popup dialog. This will only be used on devices where the
popup width and height are configurable, such as the iPad or tablets. On iPhone, the
picker always spans the width of the screen along the bottom.
Returns:
getPreferredPopupHeight
public int getPreferredPopupHeight()
The preferred height of the popup dialog. This will only be used on devices where the
popup width and height are configurable, such as the iPad or tablets. On iPhone, the
picker always spans the width of the screen along the bottom.
Returns:
Method Detail
848
Class NumericSpinner
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.spinner.BaseSpinner
com.codename1.ui.spinner.NumericSpinner
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends BaseSpinner
Field Summary
Constructor Summary
Constructor and Description
NumericSpinner()
Default constructor
Method Summary
Modifier
and
Type
double
double
String[]
A component may expose mutable property names for a UI designer to manipulate, this AP
usage internally by the GUI builder code
getPropertyTypeNames()
String[]
Class[]
Object
double
double
Class NumericSpinner
This method is here to workaround an XMLVM array type bug where property types aren't id
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListMod
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI builder
getStep()
849
void
void
String
Sets a new value to the given property, returns an error message if failed and null if success
setStep(double step)
void
void
Method Summary
850
Constructor Detail
NumericSpinner
public NumericSpinner()
Default constructor
Method Detail
getMin
public double getMin()
851
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Method Detail
852
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
853
Class GenericSpinner
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.spinner.BaseSpinner
com.codename1.ui.spinner.GenericSpinner
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends BaseSpinner
A spinner class that allows arbitrary values, this is effectively a combo box replacement for platforms
where a combo box is not available
Field Summary
Constructor Summary
Constructor and Description
GenericSpinner()
Default constructor
Method Summary
Modifier and
Type
int
Object
Some components may optionally generate a state which can then be restored usi
ListModel
getModel()
ListModel
getModel(int offset)
getPropertyNames()
String[]
String[]
Class[]
Object
Class GenericSpinner
This method is here to workaround an XMLVM array type bug where property type
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI bu
854
getRenderingPrototype()
void
void
If getComponentState returned a value the setter can update the value and restore
void
void
setModel(ListModel model)
String
Sets a new value to the given property, returns an error message if failed and null
void
void
setRenderer(ListCellRenderer renderer)
setRenderingPrototype(int column, String pr)
void
void
void
void
Method Summary
855
Constructor Detail
GenericSpinner
public GenericSpinner()
Default constructor
Method Detail
setColumns
public void setColumns(int columns)
856
Method Detail
857
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
getModel
public ListModel getModel()
Returns:
the model
getModel
public ListModel getModel(int offset)
Returns:
the model
Method Detail
858
Parameters:
model
setModel
public void setModel(int offset,
ListModel model)
Parameters:
model
getRenderer
public ListCellRenderer getRenderer(int offset)
Returns:
the renderer
setRenderer
public void setRenderer(int offset,
ListCellRenderer renderer)
Parameters:
renderer
getRenderer
public ListCellRenderer getRenderer()
Returns:
the renderer
setRenderer
public void setRenderer(ListCellRenderer renderer)
Parameters:
renderer - the renderer to set
getComponentState
public Object getComponentState()
Some components may optionally generate a state which can then be restored using
setCompnentState(). This method is used by the UIBuilder.
Overrides:
getComponentState in class Component
Returns:
the component state or null for undefined state.
setComponentState
public void setComponentState(Object state)
If getComponentState returned a value the setter can update the value and restore
the prior state.
Overrides:
setComponentState in class Component
Parameters:
state - the non-null state
Method Detail
859
Class DateTimeSpinner
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.spinner.BaseSpinner
com.codename1.ui.spinner.TimeSpinner
com.codename1.ui.spinner.DateTimeSpinner
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends TimeSpinner
The date and time spinner extends the time spinner by allowing to pick a specific day as well
Field Summary
Constructor Summary
Constructor and Description
DateTimeSpinner()
Default constructor
Method Summary
Modifier
and Type
Date
getCurrentDate()
Date
getEndDate()
getPropertyNames()
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
Returns the current value of the property name, this method is used by the
GUI builder
Date
getStartDate()
boolean
isIncludeYear()
boolean
isMarkToday()
void
setCurrentDate(Date currentDate)
void
setEndDate(Date endDate)
void
setIncludeYear(boolean includeYear)
Class DateTimeSpinner
860
setMarkToday(boolean markToday)
setPropertyValue(String name, Object value)
String
Sets a new value to the given property, returns an error message if failed and
null if successful.
void
setStartDate(Date startDate)
Method Summary
861
Constructor Detail
DateTimeSpinner
public DateTimeSpinner()
Default constructor
Method Detail
getCurrentDate
public Date getCurrentDate()
Returns:
the currentDate
setCurrentDate
public void setCurrentDate(Date currentDate)
Parameters:
currentDate
getStartDate
public Date getStartDate()
Returns:
the startDate
setStartDate
public void setStartDate(Date startDate)
Parameters:
startDate
getEndDate
public Date getEndDate()
Returns:
the endDate
862
Parameters:
endDate
isMarkToday
public boolean isMarkToday()
Returns:
the markToday
setMarkToday
public void setMarkToday(boolean markToday)
Parameters:
markToday
isIncludeYear
public boolean isIncludeYear()
Returns:
the includeYear
setIncludeYear
public void setIncludeYear(boolean includeYear)
Parameters:
includeYear
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class TimeSpinner
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class TimeSpinner
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Method Detail
863
Method Detail
864
Class DateSpinner
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.spinner.BaseSpinner
com.codename1.ui.spinner.DateSpinner
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends BaseSpinner
A date spinner allows selecting a date value within the given date range
Field Summary
Constructor Summary
Constructor and Description
DateSpinner()
Default constructor
Method Summary
Modifier
and Type
int
getCurrentDay()
int
getCurrentMonth()
int
getCurrentYear()
int
getEndYear()
getPropertyNames()
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
Returns the current value of the property name, this method is used by the GUI
builder
int
getStartYear()
boolean
isMonthDayYear()
boolean
isNumericMonths()
void
setCurrentDay(int currentDay)
Class DateSpinner
865
setCurrentMonth(int currentMonth)
void
setCurrentYear(int currentYear)
void
setEndYear(int endYear)
void
setMonthDayYear(boolean monthDayYear)
setMonthRenderingPrototype(String monthPrototype)
void
Sets the Month Rendering Prototype to be used, useful when the language is
changed and you need the month spinner to be wider.
void
setNumericMonths(boolean numericMonths)
setPropertyValue(String name, Object value)
String
Sets a new value to the given property, returns an error message if failed and
null if successful.
void
setStartYear(int startYear)
Method Summary
866
Constructor Detail
DateSpinner
public DateSpinner()
Default constructor
Method Detail
getStartYear
public int getStartYear()
Returns:
the startYear
setStartYear
public void setStartYear(int startYear)
Parameters:
startYear
getEndYear
public int getEndYear()
Returns:
the endYear
setEndYear
public void setEndYear(int endYear)
Parameters:
endYear
getCurrentYear
public int getCurrentYear()
Returns:
867
Parameters:
currentYear
getCurrentDay
public int getCurrentDay()
Returns:
the currentDay
setCurrentDay
public void setCurrentDay(int currentDay)
Parameters:
currentDay
getCurrentMonth
public int getCurrentMonth()
Returns:
the currentMonth
setCurrentMonth
public void setCurrentMonth(int currentMonth)
Parameters:
currentMonth
isMonthDayYear
public boolean isMonthDayYear()
Returns:
the monthDayYear
setMonthDayYear
public void setMonthDayYear(boolean monthDayYear)
Parameters:
monthDayYear
isNumericMonths
public boolean isNumericMonths()
Returns:
the numericMonths
setNumericMonths
public void setNumericMonths(boolean numericMonths)
Parameters:
numericMonths
getPropertyNames
public String[] getPropertyNames()
Method Detail
868
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
setMonthRenderingPrototype
public void setMonthRenderingPrototype(String monthPrototype)
Sets the Month Rendering Prototype to be used, useful when the language is
changed and you need the month spinner to be wider.
Parameters:
monthPrototype - a prototype to be used to calc the month cell size
Method Detail
869
Class BaseSpinner
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.spinner.BaseSpinner
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
Direct Known Subclasses:
DateSpinner, GenericSpinner, NumericSpinner, TimeSpinner
Field Summary
Constructor Summary
Constructor and Description
BaseSpinner()
Default constructor
Method Summary
Modifier and
Type
protected
Dimension
calcPreferredSize()
protected
void
initComponent()
protected
void
Makes sure the component is up to date with the current theme, ONLY
INVOKE THIS METHOD IF YOU CHANGED THE THEME!
void
setUIID(String id)
void
Class BaseSpinner
870
871
Constructor
Detail
BaseSpinner
public BaseSpinner()
Default constructor
Method Detail
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Container
Returns:
the calculated preferred size based on component content
initComponent
protected void initComponent()
Default constructor
Overrides:
initComponent
in class Component
setUIID
public void setUIID(String id)
This method sets the Component the Unique identifier. This method should be used
before a component has been initialized
Overrides:
setUIID in class Component
Parameters:
id - UIID unique identifier for component type
refreshTheme
public void refreshTheme(boolean merge)
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Container
Parameters:
merge - indicates if the current styles should be merged with the new styles
paintGlass
protected void paintGlass(Graphics g)
This method can be overriden by a component to draw on top of itself or its children
after the component or the children finished drawing in a similar way to the glass
pane but more refined per component
Overrides:
paintGlass in class Container
Parameters:
g - the graphics context
Constructor Detail
872
Class UIManager
java.lang.Object
com.codename1.ui.plaf.UIManager
public class
extends Object
Central point singleton managing the look of the application, this class allows us to customize the
styles (themes) as well as the look instance.
Method Summary
Modifier and Type
void
void
static UIManager
Map<String,String>
Style
Returns a custom style for the component with the given id, this
method always returns a new instance.
getComponentSelectedStyle(String id)
Style
Style
static UIManager
LookAndFeel
Hashtable
int
String
Image
Object
Method Detail
Deprecated.
this method uses the old resource bundle hashtable, use the new
getBundle() method
getThemeConstant(String constantName, int def)
String
getThemeName()
static Resources
initFirstTheme(String resourceFile)
873
Boolean
boolean
Localizes the given string from the resource bundle if such a String
exists in the resource bundle.
String
removeThemeRefreshListener(ActionListener l)
void
void
void
void
void
setLookAndFeel(LookAndFeel plaf)
void
Deprecated.
this method uses the old resource bundle hashtable, use the new
setBundle() method
void
setThemeProps(Hashtable themeProps)
void
boolean
wasThemeInstalled()
Method Detail
wasThemeInstalled
public boolean wasThemeInstalled()
Method Summary
874
This factory method allows creating a new UIManager instance, this is usefull where
an application has some screens with different context
Returns:
a new UIManager instance
See Also:
Formt#setUIManager(UIManager)
getLookAndFeel
public LookAndFeel getLookAndFeel()
Returns the style of the component with the given id or a new instance of the default
style. This method will always return a new style instance to prevent modification of
the global style object.
Parameters:
id - the component id whose style we want
Returns:
the appropriate style (this method never returns null)
Method Detail
875
Returns the selected style of the component with the given id or a new instance of
the default style. This method will always return a new style instance to prevent
modification of the global style object.
Parameters:
id - the component id whose selected style we want
Returns:
the appropriate style (this method never returns null)
getComponentCustomStyle
public Style getComponentCustomStyle(String id,
String type)
Returns a custom style for the component with the given id, this method always
returns a new instance. Custom styles allow us to install application specific or
component specific style attributes such as pressed, disabled, hover etc.
Parameters:
id - the component id whose custom style we want
type - the style type
Returns:
the appropriate style (this method never returns null)
getThemeName
public String getThemeName()
Returns:
the name of the current theme for theme switching UI's
setThemeProps
public void setThemeProps(Hashtable themeProps)
Adds the given theme properties on top of the existing properties without clearing the
existing theme first
Parameters:
themeProps - the properties of the given theme
getThemeConstant
public int getThemeConstant(String constantName,
int def)
Method Detail
876
Returns a theme constant defined in the resource editor as a boolean value or null if
the constant isn't defined
Parameters:
constantName - the name of the constant
Returns:
the value of the constant or null if the constant isn't in the theme
getThemeImageConstant
public Image getThemeImageConstant(String constantName)
Deprecated. this method uses the old resource bundle hashtable, use the new
getBundle() method
The resource bundle allows us to implicitly localize the UI on the fly, once its installed
all internal application strings query the resource bundle and extract their values from
this table if applicable.
Returns:
the localization bundle
getBundle
public Map<String,String> getBundle()
The resource bundle allows us to implicitly localize the UI on the fly, once its installed
all internal application strings query the resource bundle and extract their values from
this table if applicable.
Returns:
the localization bundle
setBundle
public void setBundle(Map<String,String> bundle)
The resource bundle allows us to implicitly localize the UI on the fly, once its installed
all internal application strings query the resource bundle and extract their values from
this table if applicable.
Parameters:
Method Detail
877
setResourceBundle
public void setResourceBundle(Hashtable resourceBundle)
Deprecated. this method uses the old resource bundle hashtable, use the new
setBundle() method
The resource bundle allows us to implicitly localize the UI on the fly, once its installed
all internal application strings query the resource bundle and extract their values from
this table if applicable.
Parameters:
resourceBundle - the localization bundle
localize
public String localize(String key,
String defaultValue)
Localizes the given string from the resource bundle if such a String exists in the
resource bundle. If no key exists in the bundle then or a bundle is not installed the
default value is returned.
Parameters:
key - The key used to lookup in the resource bundle
defaultValue - the value returned if no such key exists
Returns:
either default value or the appropriate value
addThemeRefreshListener
public void addThemeRefreshListener(ActionListener l)
Adds a Theme refresh listener. The listenres will get a callback when setThemeProps
method is invoked.
Parameters:
l - an ActionListener to be added
removeThemeRefreshListener
public void removeThemeRefreshListener(ActionListener l)
This is a shorthand notation for boilerplate code for initializing the first theme in the
given resource file and catching/doing nothing with the IOException since this would
be invoked too early in the program where we would be out of options if something
like that happens. Effectively this is the same as writing:
try {
theme = Resources.openLayered(resourceFile);
UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResou
} catch(IOException e){
e.printStackTrace();
}
Parameters:
- the name of the resource file starting with / and without the
res extension
Returns:
the resource file or null in case of a failure
initNamedTheme
resourceFile
Method Detail
878
Method Detail
879
Class Style
java.lang.Object
com.codename1.ui.plaf.Style
public class
extends Object
Represents the look of a given component: colors, fonts, transparency, margin and padding &
images.
Each Component contains a Style Object and allows Style modification in Runtime by Using
cmp.getStyle() The style is also used in Themeing, when a Theme is Changed the Styles Objects
are been updated automatically.
When changing a theme the elements changed manually in a style will not be updated by the theme
change by default. There are two ways to change that behavior:
1. Use the set method that accepts a second boolean argument and set it to true.
2. Create a new style object and pass all the options in the constructor (without invoking setters
manually).
The Margin and Padding is inspired by W3 Box Model
**************************
*
Margin
*
* ******************** *
* *
Padding
* *
* *
***********
* *
* *
* Content *
* *
* *
***********
* *
* *
Padding
* *
* ******************** *
*
Margin
*
**************************
Field Summary
Modifier
and Type
static
String
ALIGNMENT
static
String
BACKGROUND_ALIGNMENT
static
String
BACKGROUND_GRADIENT
static byte
static byte
static byte
Indicates the background for the style would use a linear gradient
BACKGROUND_GRADIENT_LINEAR_VERTICAL
Indicates the background for the style would use a linear gradient
BACKGROUND_GRADIENT_RADIAL
Indicates the background for the style would use a radial gradient
BACKGROUND_IMAGE_ALIGNED_BOTTOM
static byte
Indicates the background for the style would use an unscaled image with an
alignment
BACKGROUND_IMAGE_ALIGNED_BOTTOM_LEFT
static byte
Class Style
Indicates the background for the style would use an unscaled image with an
alignment
880
Indicates the background for the style would use an unscaled image with an
alignment
BACKGROUND_IMAGE_ALIGNED_CENTER
static byte
Indicates the background for the style would use an unscaled image with an
alignment
BACKGROUND_IMAGE_ALIGNED_LEFT
static byte
Indicates the background for the style would use an unscaled image with an
alignment
BACKGROUND_IMAGE_ALIGNED_RIGHT
static byte
Indicates the background for the style would use an unscaled image with an
alignment
BACKGROUND_IMAGE_ALIGNED_TOP
static byte
Indicates the background for the style would use an unscaled image with an
alignment
BACKGROUND_IMAGE_ALIGNED_TOP_LEFT
static byte
Indicates the background for the style would use an unscaled image with an
alignment
BACKGROUND_IMAGE_ALIGNED_TOP_RIGHT
static byte
static byte
Indicates the background for the style would use an unscaled image with an
alignment
BACKGROUND_IMAGE_SCALED
Indicates the background for the style would use a scaled image
BACKGROUND_IMAGE_SCALED_FILL
static byte
Indicates the background for the style would use a scaled image that fills all
available space while maintaining aspect ratio
BACKGROUND_IMAGE_SCALED_FIT
static byte
static byte
static byte
static byte
static byte
static byte
static byte
static byte
static byte
static byte
static byte
Field Summary
Indicates the background for the style would use a scaled image that fits to
available space while maintaining aspect ratio
BACKGROUND_IMAGE_TILE_BOTH
Indicates the background for the style would use a tiled image on both axis
BACKGROUND_IMAGE_TILE_HORIZONTAL
Indicates the background for the style would use a horizontal tiled image
BACKGROUND_IMAGE_TILE_HORIZONTAL_ALIGN_BOTTOM
Indicates the background for the style would use a horizontal tiled image
BACKGROUND_IMAGE_TILE_HORIZONTAL_ALIGN_CENTER
Indicates the background for the style would use a horizontal tiled image
BACKGROUND_IMAGE_TILE_HORIZONTAL_ALIGN_TOP
Indicates the background for the style would use a horizontal tiled image
BACKGROUND_IMAGE_TILE_VERTICAL
Indicates the background for the style would use a vertical tiled image
BACKGROUND_IMAGE_TILE_VERTICAL_ALIGN_CENTER
Indicates the background for the style would use a horizontal tiled image
BACKGROUND_IMAGE_TILE_VERTICAL_ALIGN_LEFT
Indicates the background for the style would use a horizontal tiled image
BACKGROUND_IMAGE_TILE_VERTICAL_ALIGN_RIGHT
Indicates the background for the style would use a horizontal tiled image
BACKGROUND_NONE
Indicates the background for the style would use a scaled image
static
String
BACKGROUND_TYPE
static
String
BG_COLOR
static
String
BG_IMAGE
static
String
BORDER
static
String
FG_COLOR
881
FONT
static
String
MARGIN
static
String
MARGIN_UNIT
static
String
OPACITY
static
String
PADDING
static
String
PADDING_UNIT
static
String
PAINTER
static
String
TEXT_DECORATION
static byte
static byte
static byte
static byte
static byte
static byte
static byte
static
String
static byte
Indicates overline
TEXT_DECORATION_STRIKETHRU
Indicates underline
TRANSPARENCY
static byte
Indicates the unit type for padding/margin, the default is in device specific
pixels
UNIT_TYPE_SCREEN_PERCENTAGE
static byte
Indicates the unit type for padding/margin in percentage of the size of the
screen
Constructor Summary
Constructor and Description
Style()
Each component when it draw itself uses this Object to determine in what colors it should
use.
Style(int fgColor, int bgColor, Font f, byte transparency)
Constructor Summary
882
Method Summary
Modifier
and
Type
void
static
Style
int
int
float
float
float
int
byte
int
Image
Creates a "proxy" style whose setter methods map to the methods in the given
styles passed and whose getter methods are meaningless
getAlignment()
Painter
Return the background painter for this style, normally this would be the internal
image/color painter but can be user defined
getBgTransparency()
byte
Border
int
Font
int
int
int
int
int
Returns the transparency (opacity) level of the Component, zero indicates fully
transparent and FF indicates fully opaque.
getBorder()
byte[]
int
int
Method Summary
Indicates the units used for margin elements, if null pixels are used if not this is a 4
element array containing values of UNIT_TYPE_PIXELS, UNIT_TYPE_DIPS or
UNIT_TYPE_SCREEN_PERCENTAGE
getMarginValue(boolean rtl, int orientation)
883
byte[]
int
int
boolean
boolean
Indicates the units used for padding elements, if null pixels are used if not this is a
4 element array containing values of UNIT_TYPE_PIXELS, UNIT_TYPE_DIPS or
UNIT_TYPE_SCREEN_PERCENTAGE
getPaddingValue(boolean rtl, int orientation)
boolean
boolean
boolean
boolean
boolean
Returns true if the style was modified manually after it was created by the look and
feel.
isOverline()
Returns true if the strike through text decoration is on, false otherwise
isUnderline()
void
void
void
void
void
void
void
void
void
Merges the new style with the current style without changing the elements that
were modified.
removeListeners()
Sets the Alignment of the Label to one of: CENTER, LEFT, RIGHT
setAlignment(int align, boolean override)
Sets the Alignment of the Label to one of: CENTER, LEFT, RIGHT
setBackgroundGradientEndColor(int backgroundGradientEndColor)
Method Summary
setBackgroundGradientRelativeSize(float backgroundGradientRelativeSize)
884
void
setBackgroundGradientRelativeX(float backgroundGradientRelativeX)
void
setBackgroundGradientRelativeY(float backgroundGradientRelativeY)
void
setBackgroundGradientStartColor(int backgroundGradientStartColor)
setBackgroundType(byte backgroundType)
void
Defines the background painter for this style, normally this would be the internal
image/color painter but can be user defined
setBgTransparency(byte transparency)
void
void
void
void
void
void
void
void
void
void
void
void
Sets the Component transparency (opacity) level of the Component, zero indicates
fully transparent and FF indicates fully opaque.
setBgTransparency(int transparency)
void
Method Summary
885
setMarginLeft(int gap)
void
void
void
Indicates the units used for margin elements, if null pixels are used if not this is a 4
element array containing values of UNIT_TYPE_PIXELS, UNIT_TYPE_DIPS or
UNIT_TYPE_SCREEN_PERCENTAGE
void
setOpacity(int opacity)
void
void
void
void
void
void
void
void
void
void
Indicates the units used for padding elements, if null pixels are used if not this is a
4 element array containing values of UNIT_TYPE_PIXELS, UNIT_TYPE_DIPS or
UNIT_TYPE_SCREEN_PERCENTAGE
void
setStrikeThru(boolean strikethru)
void
void
void
void
Field Detail
886
Field Detail
887
Indicates the background for the style would use a scaled image
See Also:
Constant Field Values
Field Detail
888
Indicates the background for the style would use a scaled image
See Also:
Constant Field Values
BACKGROUND_IMAGE_TILE_BOTH
public static final byte BACKGROUND_IMAGE_TILE_BOTH
Indicates the background for the style would use a tiled image on both axis
See Also:
Constant Field Values
BACKGROUND_IMAGE_TILE_VERTICAL
public static final byte BACKGROUND_IMAGE_TILE_VERTICAL
Indicates the background for the style would use a vertical tiled image
See Also:
Constant Field Values
BACKGROUND_IMAGE_TILE_HORIZONTAL
public static final byte BACKGROUND_IMAGE_TILE_HORIZONTAL
Indicates the background for the style would use a horizontal tiled image
See Also:
Constant Field Values
BACKGROUND_IMAGE_ALIGNED_TOP
public static final byte BACKGROUND_IMAGE_ALIGNED_TOP
Indicates the background for the style would use an unscaled image with an
alignment
See Also:
Constant Field Values
BACKGROUND_IMAGE_ALIGNED_BOTTOM
public static final byte BACKGROUND_IMAGE_ALIGNED_BOTTOM
Indicates the background for the style would use an unscaled image with an
alignment
See Also:
Constant Field Values
BACKGROUND_IMAGE_ALIGNED_LEFT
public static final byte BACKGROUND_IMAGE_ALIGNED_LEFT
Indicates the background for the style would use an unscaled image with an
alignment
See Also:
Constant Field Values
BACKGROUND_IMAGE_ALIGNED_RIGHT
public static final byte BACKGROUND_IMAGE_ALIGNED_RIGHT
Indicates the background for the style would use an unscaled image with an
alignment
See Also:
Constant Field Values
BACKGROUND_IMAGE_ALIGNED_CENTER
public static final byte BACKGROUND_IMAGE_ALIGNED_CENTER
Indicates the background for the style would use an unscaled image with an
alignment
See Also:
Field Detail
889
Indicates the background for the style would use an unscaled image with an
alignment
See Also:
Constant Field Values
BACKGROUND_IMAGE_ALIGNED_TOP_RIGHT
public static final byte BACKGROUND_IMAGE_ALIGNED_TOP_RIGHT
Indicates the background for the style would use an unscaled image with an
alignment
See Also:
Constant Field Values
BACKGROUND_IMAGE_ALIGNED_BOTTOM_LEFT
public static final byte BACKGROUND_IMAGE_ALIGNED_BOTTOM_LEFT
Indicates the background for the style would use an unscaled image with an
alignment
See Also:
Constant Field Values
BACKGROUND_IMAGE_ALIGNED_BOTTOM_RIGHT
public static final byte BACKGROUND_IMAGE_ALIGNED_BOTTOM_RIGHT
Indicates the background for the style would use an unscaled image with an
alignment
See Also:
Constant Field Values
BACKGROUND_IMAGE_TILE_HORIZONTAL_ALIGN_TOP
public static final byte BACKGROUND_IMAGE_TILE_HORIZONTAL_ALIGN_TOP
Indicates the background for the style would use a horizontal tiled image
See Also:
Constant Field Values
BACKGROUND_IMAGE_TILE_HORIZONTAL_ALIGN_CENTER
public static final byte BACKGROUND_IMAGE_TILE_HORIZONTAL_ALIGN_CENTER
Indicates the background for the style would use a horizontal tiled image
See Also:
Constant Field Values
BACKGROUND_IMAGE_TILE_HORIZONTAL_ALIGN_BOTTOM
public static final byte BACKGROUND_IMAGE_TILE_HORIZONTAL_ALIGN_BOTTOM
Indicates the background for the style would use a horizontal tiled image
See Also:
Constant Field Values
BACKGROUND_IMAGE_TILE_VERTICAL_ALIGN_LEFT
public static final byte BACKGROUND_IMAGE_TILE_VERTICAL_ALIGN_LEFT
Indicates the background for the style would use a horizontal tiled image
See Also:
Constant Field Values
BACKGROUND_IMAGE_TILE_VERTICAL_ALIGN_CENTER
public static final byte BACKGROUND_IMAGE_TILE_VERTICAL_ALIGN_CENTER
Indicates the background for the style would use a horizontal tiled image
See Also:
Field Detail
890
Indicates the background for the style would use a horizontal tiled image
See Also:
Constant Field Values
BACKGROUND_IMAGE_SCALED_FILL
public static final byte BACKGROUND_IMAGE_SCALED_FILL
Indicates the background for the style would use a scaled image that fills all available
space while maintaining aspect ratio
See Also:
Constant Field Values
BACKGROUND_IMAGE_SCALED_FIT
public static final byte BACKGROUND_IMAGE_SCALED_FIT
Indicates the background for the style would use a scaled image that fits to available
space while maintaining aspect ratio
See Also:
Constant Field Values
BACKGROUND_GRADIENT_LINEAR_VERTICAL
public static final byte BACKGROUND_GRADIENT_LINEAR_VERTICAL
Indicates the background for the style would use a linear gradient
See Also:
Constant Field Values
BACKGROUND_GRADIENT_LINEAR_HORIZONTAL
public static final byte BACKGROUND_GRADIENT_LINEAR_HORIZONTAL
Indicates the background for the style would use a linear gradient
See Also:
Constant Field Values
BACKGROUND_GRADIENT_RADIAL
public static final byte BACKGROUND_GRADIENT_RADIAL
Indicates the background for the style would use a radial gradient
See Also:
Constant Field Values
TEXT_DECORATION_NONE
public static final byte TEXT_DECORATION_NONE
Indicates underline
See Also:
Constant Field Values
TEXT_DECORATION_STRIKETHRU
public static final byte TEXT_DECORATION_STRIKETHRU
Field Detail
891
Indicates overline
See Also:
Constant Field Values
TEXT_DECORATION_3D
public static final byte TEXT_DECORATION_3D
Indicates the unit type for padding/margin, the default is in device specific pixels
See Also:
Constant Field Values
UNIT_TYPE_SCREEN_PERCENTAGE
public static final byte UNIT_TYPE_SCREEN_PERCENTAGE
Indicates the unit type for padding/margin in percentage of the size of the screen
See Also:
Constant Field Values
UNIT_TYPE_DIPS
public static final byte UNIT_TYPE_DIPS
Indicates the unit type for padding/margin in device independent pixels. Device
independent pixels try to aim at roghly 1 milimeter of the screen per DIP but make no
guarantee for accuracy.
See Also:
Constant Field Values
Constructor Detail
Style
public Style()
Each component when it draw itself uses this Object to determine in what colors it
should use. When a Component is generated it construct a default Style Object. The
Default values for each Component can be changed by using the UIManager class
Style
public Style(Style style)
Field Detail
892
Method Detail
createProxyStyle
public static Style createProxyStyle(Style... styles)
Creates a "proxy" style whose setter methods map to the methods in the given styles
passed and whose getter methods are meaningless
Parameters:
styles - the styles to which we will proxy
Returns:
a proxy style object
merge
public void merge(Style style)
Merges the new style with the current style without changing the elements that were
modified.
Parameters:
style - new values of styles from the current theme
Constructor Detail
893
Returns true if the style was modified manually after it was created by the look and
feel. If the style was modified manually (by one of the set methods) then it should be
merged rather than overwritten.
Returns:
true if the style was modified
getBgColor
public int getBgColor()
Method Detail
894
Sets the Alignment of the Label to one of: CENTER, LEFT, RIGHT
Parameters:
align - alignment value
See Also:
Component.CENTER, Component.LEFT, Component.RIGHT
setAlignment
public void setAlignment(int align,
boolean override)
Sets the Alignment of the Label to one of: CENTER, LEFT, RIGHT
Parameters:
align - alignment value
override - If set to true allows the look and feel/theme to override the value in
this attribute when changing a theme/look and feel
See Also:
Component.CENTER, Component.LEFT, Component.RIGHT
getAlignment
public int getAlignment()
Method Detail
895
setFgColor
public void setFgColor(int fgColor)
Method Detail
896
Method Detail
897
Returns true if the strike through text decoration is on, false otherwise
Returns:
true if the strike through text decoration is on, false otherwise
getTextDecoration
public int getTextDecoration()
Returns the transparency (opacity) level of the Component, zero indicates fully
transparent and FF indicates fully opaque.
Returns:
the transparency level of the Component
setBgTransparency
public void setBgTransparency(byte transparency)
Sets the Component transparency (opacity) level of the Component, zero indicates
fully transparent and FF indicates fully opaque.
Parameters:
transparency - transparency level as byte
getOpacity
public int getOpacity()
Method Detail
898
Sets the Component transparency level. Valid values should be a number between
0-255
Parameters:
opacity - int value between 0-255
override - If set to true allows the look and feel/theme to override the value in
this attribute when changing a theme/look and feel
setBgTransparency
public void setBgTransparency(int transparency)
Sets the Component transparency level. Valid values should be a number between
0-255
Parameters:
transparency - int value between 0-255
setPadding
public void setPadding(int
int
int
int
top,
bottom,
left,
right)
top,
bottom,
left,
right)
Method Detail
899
Parameters:
gap - number of pixels to pad
setPaddingBottom
public void setPaddingBottom(int gap)
Parameters:
gap - number of pixels to pad
setPaddingLeft
public void setPaddingLeft(int gap)
Parameters:
gap - number of pixels to pad
Method Detail
900
Parameters:
gap - number of pixels to pad
setMarginTop
public void setMarginTop(int gap)
Parameters:
gap - number of pixels to pad
setMarginBottom
public void setMarginBottom(int gap)
Parameters:
gap - number of pixels to pad
setMarginLeft
public void setMarginLeft(int gap)
Parameters:
gap - number of pixels to pad
setMarginRight
public void setMarginRight(int gap)
Parameters:
gap - number of pixels to pad
getPaddingBottom
public int getPaddingBottom()
Method Detail
901
Method Detail
902
Method Detail
903
Sets the Component transparency level. Valid values should be a number between
0-255
Parameters:
transparency - int value between 0-255
override - If set to true allows the look and feel/theme to override the value in
this attribute when changing a theme/look and feel
setPadding
public void setPadding(int orientation,
int gap,
boolean override)
Method Detail
904
Return the background painter for this style, normally this would be the internal
image/color painter but can be user defined
Returns:
the background painter
Method Detail
905
Defines the background painter for this style, normally this would be the internal
image/color painter but can be user defined
Parameters:
bgPainter - new painter to install into the style
getPaddingUnit
public byte[] getPaddingUnit()
Indicates the units used for padding elements, if null pixels are used if not this is a 4
element array containing values of UNIT_TYPE_PIXELS, UNIT_TYPE_DIPS or
UNIT_TYPE_SCREEN_PERCENTAGE
Returns:
the paddingUnit
setPaddingUnit
public void setPaddingUnit(byte... paddingUnit)
Indicates the units used for padding elements, if null pixels are used if not this is a 4
element array containing values of UNIT_TYPE_PIXELS, UNIT_TYPE_DIPS or
UNIT_TYPE_SCREEN_PERCENTAGE
Parameters:
paddingUnit - the paddingUnit to set
getMarginUnit
public byte[] getMarginUnit()
Indicates the units used for margin elements, if null pixels are used if not this is a 4
element array containing values of UNIT_TYPE_PIXELS, UNIT_TYPE_DIPS or
UNIT_TYPE_SCREEN_PERCENTAGE
Returns:
the marginUnit
setMarginUnit
public void setMarginUnit(byte... marginUnit)
Indicates the units used for margin elements, if null pixels are used if not this is a 4
element array containing values of UNIT_TYPE_PIXELS, UNIT_TYPE_DIPS or
UNIT_TYPE_SCREEN_PERCENTAGE
Parameters:
marginUnit - the marginUnit to set
Method Detail
906
Class LookAndFeel
java.lang.Object
com.codename1.ui.plaf.LookAndFeel
Direct Known Subclasses:
DefaultLookAndFeel
Deprecated.
this class is still crucial for some features in Codename One. The deprecation is here to indicate our
desire to reduce usage/reliance on this class.
public abstract class
extends Object
Allows a UI developer to completely customize the look of the application by overriding drawing/sizing
methods appropriately.
Constructor Summary
Constructor and Description
LookAndFeel(UIManager manager)
Deprecated.
Method Summary
Modifier and
Type
void
Deprecated.
Every component binds itself to the look and feel thus allowing the look and feel to
customize the component.
drawButton(Graphics g, Button b)
abstract void
Deprecated.
this method is no longer used by the implementation, we shifted code away to
improve performance
drawCheckBox(Graphics g, Button cb)
abstract void
Deprecated.
Invoked for drawing a checkbox widget
drawComboBox(Graphics g, List cb)
abstract void
void
Deprecated.
Invoked for drawing a combo box widget
drawHorizontalScroll(Graphics g, Component c, float offsetRatio,
float blockSizeRatio)
Deprecated.
Draws a horizontal scroll bar in the given component
drawLabel(Graphics g, Label l)
abstract void
Deprecated.
this method is no longer used by the implementation, we shifted code away to
improve performance
drawList(Graphics g, List l)
abstract void
Deprecated.
Invoked for drawing a list widget
drawPullToRefresh(Graphics g, Component cmp, boolean taskExecuted)
abstract void
Class LookAndFeel
Deprecated.
Paints the pull to refresh
907
Deprecated.
Invoked for drawing the radio button widget
drawTextArea(Graphics g, TextArea ta)
abstract void
Deprecated.
Draw the given text area
drawTextField(Graphics g, TextArea ta)
abstract void
Deprecated.
Draws the text field without its cursor which is drawn in a separate method input
mode indication can also be drawn using this method.
drawTextFieldCursor(Graphics g, TextArea ta)
abstract void
void
abstract
Dimension
abstract
Dimension
abstract
Dimension
Deprecated.
Draws the cursor of the text field, blinking is handled simply by avoiding a call to
this method.
drawVerticalScroll(Graphics g, Component c, float offsetRatio,
float blockSizeRatio)
Deprecated.
Draws a vertical scroll bar in the given component
getButtonPreferredSize(Button b)
Deprecated.
Calculate the preferred size of the component
getCheckBoxPreferredSize(Button cb)
Deprecated.
Calculate the preferred size of the component
getComboBoxPreferredSize(List box)
Deprecated.
Calculate the preferred size of the component
getDefaultDialogTransitionIn()
Transition
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
dialog
getDefaultDialogTransitionOut()
Transition
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a
dialog
getDefaultFormTintColor()
int
Deprecated.
Tint color is set when a form is partially covered be it by a menu or by a dialog.
getDefaultFormTransitionIn()
Transition
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
form
getDefaultFormTransitionOut()
Transition
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a
form
getDefaultMenuTransitionIn()
Transition
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
Menu
getDefaultMenuTransitionOut()
Transition
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a
Menu
getDefaultSmoothScrollingSpeed()
int
Deprecated.
Indicates the default speed for smooth scrolling
getDisableColor()
int
Deprecated.
This color is used to paint disable mode text color.
int
getFadeScrollBarSpeed()
Method Summary
908
Deprecated.
Indicates the width/height of the fading edge to indicate scrolling
getHorizontalScrollHeight()
int
abstract
Dimension
abstract
Dimension
Deprecated.
Returns the default height of a horizontal scroll bar
getLabelPreferredSize(Label l)
Deprecated.
Calculate the preferred size of the component
getListPreferredSize(List l)
Deprecated.
Calculate the preferred size of the component
getMenuBarClass()
Class
Deprecated.
This method returns the MenuBar class.
getMenuIcons()
Image[]
Deprecated.
Simple getter for the menu icons
getMenuRenderer()
ListCellRenderer
Deprecated.
Returns the Menu default renderer
getPullToRefreshHeight()
abstract int
abstract
Dimension
Deprecated.
Returns the required height of the pull to refresh feature
getRadioButtonPreferredSize(Button rb)
Deprecated.
Calculate the preferred size of the component
getTactileTouchDuration()
int
abstract
Dimension
Deprecated.
Allows defining a tactile touch device that vibrates when the user presses a
component that should respond with tactile feedback on a touch device (e.g.
getTextAreaSize(TextArea ta, boolean pref)
Deprecated.
Calculate the preferred size of the component
getTextFieldCursorColor()
int
abstract
Dimension
Deprecated.
The color of the text field cursor
getTextFieldPreferredSize(TextArea ta)
Deprecated.
Calculate the preferred size of the component
getTickerSpeed()
long
Deprecated.
Gets the ticker speed
getVerticalScrollWidth()
int
Deprecated.
Returns the default width of a vertical scroll bar
isBackgroundImageDetermineSize()
boolean
Deprecated.
Indicates if the bg image of a style should determine the minimum preferred size
according to the theme
isDefaultAlwaysTensile()
boolean
Deprecated.
Enable the tensile drag to work even when a component doesn't have a scroll
showable (scrollable flag still needs to be set to true)
isDefaultEndsWith3Points()
boolean
Deprecated.
Indicates whether labels should end with 3 points by default
boolean
isDefaultSmoothScrolling()
Method Summary
909
Deprecated.
Indicates whether scrolling this component should jump to a specific location in a
grid
isDefaultTensileDrag()
boolean
Deprecated.
Indicates whether tensile drag should be active by default
isDefaultTensileHighlight()
boolean
Deprecated.
Indicates whether tensile highlight should be active by default
isFadeScrollBar()
boolean
Deprecated.
Indicates whether the scrollbar should fade when unused
isFadeScrollEdge()
boolean
Deprecated.
Indicates whether the edge of a scrollable area should fade out
isFocusScrolling()
boolean
Deprecated.
Indicates whether lists and containers should scroll only via focus and thus "jump"
when moving to a larger component as was the case in older versions of
Codename One.
isReverseSoftButtons()
boolean
Deprecated.
Indicates whether softbuttons should be reversed from their default orientation
isRTL()
boolean
Deprecated.
Use this to check if the LookAndFeel is in RTL mode
isScrollVisible()
boolean
Deprecated.
isTouchMenus()
boolean
Deprecated.
use Display.getCommandBehavior() ==
Display.COMMAND_BEHAVIOR_TOUCH_MENU
paintTensileHighlight(Component t, Graphics g, boolean top, int opacity)
void
Deprecated.
Paints the tensile hightlight image
refreshTheme(boolean completeClear)
void
Deprecated.
This method is a callback to the LookAndFeel when a theme is being changed in
the UIManager
setBackgroundImageDetermineSize(boolean backgroundImageDetermineSize)
void
Deprecated.
Indicates if the bg image of a style should determine the minimum preferred size
according to the theme
setDefaultAlwaysTensile(boolean defaultAlwaysTensile)
void
Deprecated.
Enable the tensile drag to work even when a component doesn't have a scroll
showable (scrollable flag still needs to be set to true)
setDefaultDialogTransitionIn(Transition defaultDialogTransitionIn)
void
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
dialog
setDefaultDialogTransitionOut(Transition defaultDialogTransitionOut)
void
void
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a
dialog
setDefaultEndsWith3Points(boolean defaultEndsWith3Points)
Deprecated.
Method Summary
910
Deprecated.
Tint color is set when a form is partially covered be it by a menu or by a dialog.
setDefaultFormTransitionIn(Transition defaultFormTransitionIn)
void
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
form
setDefaultFormTransitionOut(Transition defaultFormTransitionOut)
void
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a
form
setDefaultMenuTransitionIn(Transition defaultMenuTransitionIn)
void
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
Menu
setDefaultMenuTransitionOut(Transition defaultMenuTransitionOut)
void
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a
Menu
setDefaultSmoothScrolling(boolean defaultSmoothScrolling)
void
Deprecated.
Indicates whether lists and containers should have smooth scrolling by default
setDefaultSmoothScrollingSpeed(int defaultSmoothScrollingSpeed)
void
Deprecated.
Indicates the default speed for smooth scrolling
setDefaultSnapToGrid(boolean defaultSnapToGrid)
void
Deprecated.
Indicates whether scrolling this component should jump to a specific location in a
grid
setDefaultTensileDrag(boolean defaultTensileDrag)
void
Deprecated.
Indicates whether tensile drag should be active by default
setDisableColor(int disableColor)
void
Deprecated.
Simple setter to disable color
setFadeScrollBar(boolean fadeScrollBar)
void
Deprecated.
Indicates whether the scrollbar should fade when unused
setFadeScrollBarSpeed(int fadeScrollBarSpeed)
void
Deprecated.
setFadeScrollEdge(boolean fadeScrollEdge)
void
Deprecated.
Indicates whether the edge of a scrollable area should fade out
setFadeScrollEdgeLength(int fadeScrollEdgeLength)
void
Deprecated.
Indicates the width/height of the fading edge to indicate scrolling
setFG(Graphics g, Component c)
void
Deprecated.
Sets the foreground color and font for a generic component, reuse-able by most
component drawing code
setFocusScrolling(boolean focusScrolling)
void
Deprecated.
Indicates whether lists and containers should scroll only via focus and thus "jump"
when moving to a larger component as was the case in older versions of
Codename One.
setMenuBarClass(Class menuBar)
void
Method Summary
Deprecated.
Simple setter for the MenuBar Class
911
Deprecated.
Sets globally the Menu icons
void
setMenuRenderer(ListCellRenderer menuRenderer)
Deprecated.
Sets the Menu default renderer
void
setReverseSoftButtons(boolean reverseSoftButtons)
Deprecated.
Indicates whether softbuttons should be reversed from their default orientation
void
setRTL(boolean rtl)
Deprecated.
Sets this LookAndFeel to operate in right-to-left mode.
void
setTactileTouchDuration(int tactileTouchDuration)
Deprecated.
Allows defining a tactile touch device that vibrates when the user presses a
component that should respond with tactile feedback on a touch device (e.g.
void
setTextFieldCursorColor(int textFieldCursorColor)
Deprecated.
The color of the text field cursor
void
setTickerSpeed(long tickerSpeed)
Deprecated.
Sets the ticker speed
void
setTouchMenus(boolean touchMenus)
Deprecated.
use
Display.setCommandBehavior(Display.COMMAND_BEHAVIOR_TOUCH_MENU)
void
uninstall()
Deprecated.
Invoked when a look and feel is removed, allows a look and feel to release
resources related to binding components.
void
Constructor Detail
LookAndFeel
public LookAndFeel(UIManager manager)
Deprecated.
Method Detail
bind
public void bind(Component cmp)
Deprecated.
Every component binds itself to the look and feel thus allowing the look and feel to
customize the component. Binding occurs at the end of the constructor when the
component is in a valid state and ready to be used. Notice that a component might be
bound twice or more and it is the responsibility of the LookAndFeel to protect against
that.
Parameters:
cmp - component instance that may be customized by the look and feel
912
Deprecated.
Invoked when a look and feel is removed, allows a look and feel to release resources
related to binding components.
See Also:
bind(Component)
drawButton
public abstract void drawButton(Graphics g,
Button b)
Deprecated.
Invoked for drawing a checkbox widget
Parameters:
g - graphics context
cb - component to draw
drawComboBox
public abstract void drawComboBox(Graphics g,
List cb)
Deprecated.
Invoked for drawing a combo box widget
Parameters:
g - graphics context
cb - component to draw
drawLabel
public abstract void drawLabel(Graphics g,
Label l)
Deprecated.
Invoked for drawing a list widget
Parameters:
g - graphics context
l - component to draw
drawRadioButton
public abstract void drawRadioButton(Graphics g,
Button rb)
Deprecated.
Invoked for drawing the radio button widget
Method Detail
913
Deprecated.
Draw the given text area
Parameters:
g - graphics context
ta - component to draw
drawTextField
public abstract void drawTextField(Graphics g,
TextArea ta)
Deprecated.
Draws the text field without its cursor which is drawn in a separate method input
mode indication can also be drawn using this method.
Parameters:
g - graphics context
ta - component to draw
drawTextFieldCursor
public abstract void drawTextFieldCursor(Graphics g,
TextArea ta)
Deprecated.
Draws the cursor of the text field, blinking is handled simply by avoiding a call to this
method.
Parameters:
g - graphics context
ta - component to draw
getButtonPreferredSize
public abstract Dimension getButtonPreferredSize(Button b)
Deprecated.
Calculate the preferred size of the component
Parameters:
b - component whose size should be calculated
Returns:
the preferred size for the button
getCheckBoxPreferredSize
public abstract Dimension getCheckBoxPreferredSize(Button cb)
Deprecated.
Calculate the preferred size of the component
Parameters:
cb - component whose size should be calculated
Returns:
the preferred size for the component
getLabelPreferredSize
public abstract Dimension getLabelPreferredSize(Label l)
Deprecated.
Calculate the preferred size of the component
Parameters:
l - component whose size should be calculated
Returns:
the preferred size for the component
Method Detail
914
Deprecated.
Calculate the preferred size of the component
Parameters:
l - component whose size should be calculated
Returns:
the preferred size for the component
getRadioButtonPreferredSize
public abstract Dimension getRadioButtonPreferredSize(Button rb)
Deprecated.
Calculate the preferred size of the component
Parameters:
rb - component whose size should be calculated
Returns:
the preferred size for the component
getTextAreaSize
public abstract Dimension getTextAreaSize(TextArea ta,
boolean pref)
Deprecated.
Calculate the preferred size of the component
Parameters:
ta - component whose size should be calculated
pref - indicates whether preferred or scroll size should be returned
Returns:
the preferred size for the component
getTextFieldPreferredSize
public abstract Dimension getTextFieldPreferredSize(TextArea ta)
Deprecated.
Calculate the preferred size of the component
Parameters:
ta - component whose size should be calculated
Returns:
the preferred size for the component
getComboBoxPreferredSize
public abstract Dimension getComboBoxPreferredSize(List box)
Deprecated.
Calculate the preferred size of the component
Parameters:
box - component whose size should be calculated
Returns:
the preferred size for the component
drawVerticalScroll
public void drawVerticalScroll(Graphics g,
Component c,
float offsetRatio,
float blockSizeRatio)
Deprecated.
Draws a vertical scroll bar in the given component
Parameters:
g - graphics context
c - component to draw on
offsetRatio - ratio of the scroll bar from 0 to 1
blockSizeRatio - block size for the scroll from 0 to 1
Method Detail
915
Deprecated.
Draws a horizontal scroll bar in the given component
Parameters:
g - graphics context
c - component to draw on
offsetRatio - ratio of the scroll bar from 0 to 1
blockSizeRatio - block size for the scroll from 0 to 1
setFG
public void setFG(Graphics g,
Component c)
Deprecated.
Sets the foreground color and font for a generic component, reuse-able by most
component drawing code
Parameters:
g - graphics context
c - component from which fg styles should be set
getVerticalScrollWidth
public int getVerticalScrollWidth()
Deprecated.
Returns the default width of a vertical scroll bar
Returns:
default width of a vertical scroll bar
getHorizontalScrollHeight
public int getHorizontalScrollHeight()
Deprecated.
Returns the default height of a horizontal scroll bar
Returns:
default height of a horizontal scroll bar
getDefaultFormTransitionIn
public Transition getDefaultFormTransitionIn()
Deprecated.
Allows us to define a default animation that will draw the transition for entering a form
Returns:
default transition
setDefaultFormTransitionIn
public void setDefaultFormTransitionIn(Transition defaultFormTransitionIn)
Deprecated.
Allows us to define a default animation that will draw the transition for entering a form
Parameters:
defaultFormTransitionIn - the default transition
getDefaultFormTransitionOut
public Transition getDefaultFormTransitionOut()
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a form
Returns:
default transition
Method Detail
916
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a form
Parameters:
defaultFormTransitionOut - the default transition
getDefaultMenuTransitionIn
public Transition getDefaultMenuTransitionIn()
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
Menu
Returns:
default transition
setDefaultMenuTransitionIn
public void setDefaultMenuTransitionIn(Transition defaultMenuTransitionIn)
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
Menu
Parameters:
defaultMenuTransitionIn - the default transition
getDefaultMenuTransitionOut
public Transition getDefaultMenuTransitionOut()
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a Menu
Returns:
default transition
setDefaultMenuTransitionOut
public void setDefaultMenuTransitionOut(Transition defaultMenuTransitionOut)
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a Menu
Parameters:
defaultMenuTransitionOut - the default transition
getDefaultDialogTransitionIn
public Transition getDefaultDialogTransitionIn()
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
dialog
Returns:
default transition
setDefaultDialogTransitionIn
public void setDefaultDialogTransitionIn(Transition defaultDialogTransitionIn)
Deprecated.
Allows us to define a default animation that will draw the transition for entering a
dialog
Parameters:
defaultDialogTransitionIn - the default transition
getDefaultDialogTransitionOut
public Transition getDefaultDialogTransitionOut()
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a dialog
Returns:
Method Detail
917
Deprecated.
Allows us to define a default animation that will draw the transition for exiting a dialog
Parameters:
defaultDialogTransitionOut - the default transition
getDefaultFormTintColor
public int getDefaultFormTintColor()
Deprecated.
Tint color is set when a form is partially covered be it by a menu or by a dialog. A look
and feel can override this default value.
Returns:
default tint color
setDefaultFormTintColor
public void setDefaultFormTintColor(int defaultFormTintColor)
Deprecated.
Tint color is set when a form is partially covered be it by a menu or by a dialog. A look
and feel can override this default value.
Parameters:
defaultFormTintColor - the default tint color
getDisableColor
public int getDisableColor()
Deprecated.
This color is used to paint disable mode text color.
Returns:
the color value
setDisableColor
public void setDisableColor(int disableColor)
Deprecated.
Simple setter to disable color
Parameters:
disableColor - the disable color value
isDefaultSmoothScrolling
public boolean isDefaultSmoothScrolling()
Deprecated.
Indicates whether lists and containers should have smooth scrolling by default
Returns:
true if smooth scrolling should be on by default
setDefaultSmoothScrolling
public void setDefaultSmoothScrolling(boolean defaultSmoothScrolling)
Deprecated.
Indicates whether lists and containers should have smooth scrolling by default
Parameters:
defaultSmoothScrolling - true if smooth scrolling should be on by default
getDefaultSmoothScrollingSpeed
public int getDefaultSmoothScrollingSpeed()
Deprecated.
Indicates the default speed for smooth scrolling
Returns:
speed for smooth scrollin
Method Detail
918
Deprecated.
Indicates the default speed for smooth scrolling
Parameters:
defaultSmoothScrollingSpeed - speed for smooth scrollin
isReverseSoftButtons
public boolean isReverseSoftButtons()
Deprecated.
Indicates whether softbuttons should be reversed from their default orientation
Returns:
true if softbuttons should be reversed
setReverseSoftButtons
public void setReverseSoftButtons(boolean reverseSoftButtons)
Deprecated.
Indicates whether softbuttons should be reversed from their default orientation
Parameters:
reverseSoftButtons - true if softbuttons should be reversed
getMenuBarClass
public Class getMenuBarClass()
Deprecated.
This method returns the MenuBar class.
Returns:
the MenuBar class.
setMenuBarClass
public void setMenuBarClass(Class menuBar)
Deprecated.
Simple setter for the MenuBar Class
Parameters:
menuBar getMenuRenderer
public ListCellRenderer getMenuRenderer()
Deprecated.
Returns the Menu default renderer
Returns:
default renderer for the menu
setMenuRenderer
public void setMenuRenderer(ListCellRenderer menuRenderer)
Deprecated.
Sets the Menu default renderer
Parameters:
menuRenderer - default renderer for the menu
setMenuIcons
public void setMenuIcons(Image select,
Image cancel,
Image menu)
Deprecated.
Sets globally the Menu icons
Parameters:
select - select icon
cancel - cancel icon
Method Detail
919
Deprecated.
Simple getter for the menu icons
Returns:
an Image array at size of 3, where the first is the select image the second is
the cancel image and the last is the menu image.
getTickerSpeed
public long getTickerSpeed()
Deprecated.
Gets the ticker speed
Returns:
ticker speed in milliseconds
setTickerSpeed
public void setTickerSpeed(long tickerSpeed)
Deprecated.
Sets the ticker speed
Parameters:
tickerSpeed
refreshTheme
public void refreshTheme(boolean completeClear)
Deprecated.
This method is a callback to the LookAndFeel when a theme is being changed in the
UIManager
Parameters:
completeClear - indicates that the theme is set and not added
isTouchMenus
public boolean isTouchMenus()
Deprecated. use
Display.setCommandBehavior(Display.COMMAND_BEHAVIOR_TOUCH_MENU)
Indicates whether the menu UI should target a touch based device or a standard cell
phone
Parameters:
touchMenus - true to enable touch menus false to disable
setRTL
public void setRTL(boolean rtl)
Deprecated.
Sets this LookAndFeel to operate in right-to-left mode.
Parameters:
rtl - - true if right-to-left, false if left-to-right
Method Detail
920
Deprecated.
Use this to check if the LookAndFeel is in RTL mode
Returns:
true if the LookAndFeel is in right-to-left mode, false otherwise
getTactileTouchDuration
public int getTactileTouchDuration()
Deprecated.
Allows defining a tactile touch device that vibrates when the user presses a
component that should respond with tactile feedback on a touch device (e.g. vibrate).
Setting this to 0 disables tactile feedback completely
Returns:
the tactileTouchDuration
setTactileTouchDuration
public void setTactileTouchDuration(int tactileTouchDuration)
Deprecated.
Allows defining a tactile touch device that vibrates when the user presses a
component that should respond with tactile feedback on a touch device (e.g. vibrate).
Setting this to 0 disables tactile feedback completely
Parameters:
tactileTouchDuration - the duration of vibration
isDefaultEndsWith3Points
public boolean isDefaultEndsWith3Points()
Deprecated.
Indicates whether labels should end with 3 points by default
Returns:
whether labels should end with 3 points by default
setDefaultEndsWith3Points
public void setDefaultEndsWith3Points(boolean defaultEndsWith3Points)
Deprecated.
Indicates whether labels should end with 3 points by default
Parameters:
defaultEndsWith3Points - True to indicates that labels should end with 3
points by default
isDefaultTensileDrag
public boolean isDefaultTensileDrag()
Deprecated.
Indicates whether tensile drag should be active by default
Returns:
whether tensile drag should be active by default
setDefaultTensileDrag
public void setDefaultTensileDrag(boolean defaultTensileDrag)
Deprecated.
Indicates whether tensile drag should be active by default
Parameters:
defaultTensileDrag - true if tensile drag should be active by default
isFocusScrolling
public boolean isFocusScrolling()
Deprecated.
Method Detail
921
Deprecated.
Indicates whether lists and containers should scroll only via focus and thus "jump"
when moving to a larger component as was the case in older versions of Codename
One.
Parameters:
focusScrolling - true to enable focus scrolling
isFadeScrollEdge
public boolean isFadeScrollEdge()
Deprecated.
Indicates whether the edge of a scrollable area should fade out
Returns:
the fadeScrollEdge
setFadeScrollEdge
public void setFadeScrollEdge(boolean fadeScrollEdge)
Deprecated.
Indicates whether the edge of a scrollable area should fade out
Parameters:
fadeScrollEdge - the fadeScrollEdge to set
isFadeScrollBar
public boolean isFadeScrollBar()
Deprecated.
Indicates whether the scrollbar should fade when unused
Returns:
the fadeScrollBar
setFadeScrollBar
public void setFadeScrollBar(boolean fadeScrollBar)
Deprecated.
Indicates whether the scrollbar should fade when unused
Parameters:
fadeScrollBar - the fadeScrollBar to set
getFadeScrollEdgeLength
public int getFadeScrollEdgeLength()
Deprecated.
Indicates the width/height of the fading edge to indicate scrolling
Returns:
the fadeScrollEdgeLength
setFadeScrollEdgeLength
public void setFadeScrollEdgeLength(int fadeScrollEdgeLength)
Deprecated.
Indicates the width/height of the fading edge to indicate scrolling
Parameters:
fadeScrollEdgeLength - the fadeScrollEdgeLength to set
Method Detail
922
Deprecated.
The color of the text field cursor
Returns:
the textFieldCursorColor
setTextFieldCursorColor
public void setTextFieldCursorColor(int textFieldCursorColor)
Deprecated.
The color of the text field cursor
Parameters:
textFieldCursorColor - the textFieldCursorColor to set
isDefaultSnapToGrid
public boolean isDefaultSnapToGrid()
Deprecated.
Indicates whether scrolling this component should jump to a specific location in a grid
Returns:
the defaultSnapToGrid
setDefaultSnapToGrid
public void setDefaultSnapToGrid(boolean defaultSnapToGrid)
Deprecated.
Indicates whether scrolling this component should jump to a specific location in a grid
Parameters:
defaultSnapToGrid - the defaultSnapToGrid to set
isDefaultAlwaysTensile
public boolean isDefaultAlwaysTensile()
Deprecated.
Enable the tensile drag to work even when a component doesn't have a scroll
showable (scrollable flag still needs to be set to true)
Returns:
the defaultAlwaysTensile
setDefaultAlwaysTensile
public void setDefaultAlwaysTensile(boolean defaultAlwaysTensile)
Deprecated.
Enable the tensile drag to work even when a component doesn't have a scroll
showable (scrollable flag still needs to be set to true)
Parameters:
defaultAlwaysTensile - the defaultAlwaysTensile to set
isDefaultTensileHighlight
public boolean isDefaultTensileHighlight()
Deprecated.
Indicates whether tensile highlight should be active by default
Returns:
the defaultTensileHighlight
paintTensileHighlight
public void paintTensileHighlight(Component t,
Graphics g,
boolean top,
int opacity)
Deprecated.
Paints the tensile hightlight image
Method Detail
923
Deprecated.
Returns:
the fadeScrollBarSpeed
isScrollVisible
public boolean isScrollVisible()
Deprecated.
Returns:
scrollVisible
setFadeScrollBarSpeed
public void setFadeScrollBarSpeed(int fadeScrollBarSpeed)
Deprecated.
Parameters:
fadeScrollBarSpeed - the fadeScrollBarSpeed to set
isBackgroundImageDetermineSize
public boolean isBackgroundImageDetermineSize()
Deprecated.
Indicates if the bg image of a style should determine the minimum preferred size
according to the theme
Returns:
the backgroundImageDetermineSize
setBackgroundImageDetermineSize
public void setBackgroundImageDetermineSize(boolean backgroundImageDetermineSize)
Deprecated.
Indicates if the bg image of a style should determine the minimum preferred size
according to the theme
Parameters:
backgroundImageDetermineSize - the backgroundImageDetermineSize to set
drawPullToRefresh
public abstract void drawPullToRefresh(Graphics g,
Component cmp,
boolean taskExecuted)
Deprecated.
Paints the pull to refresh
Parameters:
g - graphics context
cmp - the Component which we draw the pull to refresh beneath it
taskExecuted - an indication if the refresh task is currently running
getPullToRefreshHeight
public abstract int getPullToRefreshHeight()
Deprecated.
Returns the required height of the pull to refresh feature
Method Detail
924
Class DefaultLookAndFeel
java.lang.Object
com.codename1.ui.plaf.LookAndFeel
com.codename1.ui.plaf.DefaultLookAndFeel
All Implemented Interfaces:
FocusListener
Deprecated.
this class is still crucial for some features in Codename One. The deprecation is here to indicate our
desire to reduce usage/reliance on this class.
public class
extends LookAndFeel
implements FocusListener
Constructor Summary
Constructor and Description
DefaultLookAndFeel(UIManager manager)
Deprecated.
Creates a new instance of DefaultLookAndFeel
Method Summary
Modifier and
Type
void
Deprecated.
Every component binds itself to the look and feel thus allowing the look and
feel to customize the component.
drawButton(Graphics g, Button b)
void
Deprecated.
this method is no longer used by the implementation, we shifted code away to
improve performance
drawCheckBox(Graphics g, Button cb)
void
Deprecated.
Invoked for drawing a checkbox widget
drawComboBox(Graphics g, List cb)
void
Deprecated.
Invoked for drawing a combo box widget
drawLabel(Graphics g, Label l)
void
protected
int
Deprecated.
this method is no longer used by the implementation, we shifted code away to
improve performance
drawLabelText(Graphics g, Label l, String text, int x, int y,
int textSpaceW)
Deprecated.
Draws the text of a label
drawList(Graphics g, List l)
void
Deprecated.
Invoked for drawing a list widget
void
Deprecated.
Class DefaultLookAndFeel
925
Deprecated.
Invoked for drawing the radio button widget
drawTextArea(Graphics g, TextArea ta)
void
Deprecated.
Draw the given text area
drawTextField(Graphics g, TextArea ta)
void
Deprecated.
Draws the text field without its cursor which is drawn in a separate method
input mode indication can also be drawn using this method.
drawTextFieldCursor(Graphics g, TextArea ta)
void
Deprecated.
Draws the cursor of the text field, blinking is handled simply by avoiding a call
to this method.
focusGained(Component cmp)
void
Deprecated.
Invoked when component gains focus
focusLost(Component cmp)
void
Deprecated.
Invoked when component loses focus
getButtonPreferredSize(Button b)
Dimension
Deprecated.
Calculate the preferred size of the component
getCheckBoxFocusImages()
Image[]
Deprecated.
Returns the images used to represent the checkbox when focused
getCheckBoxImages()
Image[]
Deprecated.
Returns the images used to represent the checkbox (selected followed by
unselected).
getCheckBoxPreferredSize(Button cb)
Dimension
Deprecated.
Calculate the preferred size of the component
getComboBoxPreferredSize(List cb)
Dimension
Deprecated.
Calculate the preferred size of the component
getLabelPreferredSize(Label l)
Dimension
Deprecated.
Calculate the preferred size of the component
getListPreferredSize(List l)
Dimension
Deprecated.
Calculate the preferred size of the component
getPullToRefreshHeight()
int
Deprecated.
Returns the required height of the pull to refresh feature
getRadioButtonFocusImages()
Image[]
Deprecated.
Returns the images used to represent the radio button when in focused mode
getRadioButtonImages()
Image[]
Deprecated.
Returns the images used to represent the radio button (selected followed by
unselected).
getRadioButtonPreferredSize(Button rb)
Dimension
Deprecated.
Calculate the preferred size of the component
getTextAreaSize(TextArea ta, boolean pref)
Dimension
Deprecated.
Calculate the preferred size of the component
Dimension
getTextFieldPreferredSize(TextArea ta)
Method Summary
926
getTextFieldString(TextArea ta)
Deprecated.
Similar to getText() but works properly with password fields
isTickWhenFocused()
boolean
Deprecated.
This method allows to set all Labels, Buttons, CheckBoxes, RadioButtons to
start ticking when the text is too long.
refreshTheme(boolean b)
Deprecated.
This method is a callback to the LookAndFeel when a theme is being changed
in the UIManager
void
void
Deprecated.
Sets images for checkbox when in focused mode
setCheckBoxImages(Image checkedX, Image uncheckedX)
Deprecated.
Sets images for checkbox checked/unchecked modes
void
void
Deprecated.
Sets images for checkbox checked/unchecked modes
setComboBoxImage(Image picker)
Deprecated.
Sets image for the combo box dropdown drawing
void
setPasswordChar(char c)
Deprecated.
Sets the password character to display in the TextArea and the TextField
void
Deprecated.
Sets images for radio button selected/unselected and disabled modes, when
the radio button has focus, these are entirely optional
void
Deprecated.
Sets images for radio button selected/unselected modes
void
void
Deprecated.
Sets images for radio button selected/unselected modes
setTickWhenFocused(boolean tickWhenFocused)
Deprecated.
This method allows to set all Labels, Buttons, CheckBoxes, RadioButtons to
start ticking when the text is too long.
void
927
Constructor Detail
DefaultLookAndFeel
public DefaultLookAndFeel(UIManager manager)
Deprecated.
Creates a new instance of DefaultLookAndFeel
Method Detail
bind
public void bind(Component cmp)
Deprecated.
Every component binds itself to the look and feel thus allowing the look and feel to
customize the component. Binding occurs at the end of the constructor when the
component is in a valid state and ready to be used. Notice that a component might be
bound twice or more and it is the responsibility of the LookAndFeel to protect against
that.
Overrides:
bind in class LookAndFeel
Parameters:
cmp - component instance that may be customized by the look and feel
setTickWhenFocused
public void setTickWhenFocused(boolean tickWhenFocused)
Deprecated.
This method allows to set all Labels, Buttons, CheckBoxes, RadioButtons to start
ticking when the text is too long.
Parameters:
tickWhenFocused isTickWhenFocused
public boolean isTickWhenFocused()
Deprecated.
This method allows to set all Labels, Buttons, CheckBoxes, RadioButtons to start
ticking when the text is too long.
Returns:
tickWhenFocused
setCheckBoxImages
public void setCheckBoxImages(Image checkedX,
Image uncheckedX)
Deprecated.
Sets images for checkbox checked/unchecked modes
928
setCheckBoxImages
public void setCheckBoxImages(Image
Image
Image
Image
checkedX,
uncheckedX,
disabledChecked,
disabledUnchecked)
Deprecated.
Sets images for checkbox checked/unchecked modes
Parameters:
checkedX - the image to draw in order to represent a checked checkbox
uncheckedX - the image to draw in order to represent an uncheck checkbox
disabledChecked - same as checked for the disabled state
disabledUnchecked - same as unchecked for the disabled state
setCheckBoxFocusImages
public void setCheckBoxFocusImages(Image
Image
Image
Image
checkedX,
uncheckedX,
disabledChecked,
disabledUnchecked)
Deprecated.
Sets images for checkbox when in focused mode
Parameters:
checkedX - the image to draw in order to represent a checked checkbox
uncheckedX - the image to draw in order to represent an uncheck checkbox
disabledChecked - same as checked for the disabled state
disabledUnchecked - same as unchecked for the disabled state
setComboBoxImage
public void setComboBoxImage(Image picker)
Deprecated.
Sets image for the combo box dropdown drawing
Parameters:
picker - picker image
setRadioButtonImages
public void setRadioButtonImages(Image selected,
Image unselected)
Deprecated.
Sets images for radio button selected/unselected modes
Parameters:
selected - the image to draw in order to represent a selected radio button
unselected - the image to draw in order to represent an unselected radio
button
setRadioButtonImages
public void setRadioButtonImages(Image
Image
Image
Image
selected,
unselected,
disabledSelected,
disabledUnselected)
Deprecated.
Sets images for radio button selected/unselected modes
Parameters:
selected - the image to draw in order to represent a selected radio button
unselected - the image to draw in order to represent an unselected radio
button
disabledSelected - same as selected for the disabled state
disabledUnselected - same as unselected for the disabled state
Method Detail
929
selected,
unselected,
disabledSelected,
disabledUnselected)
Deprecated.
Sets images for radio button selected/unselected and disabled modes, when the
radio button has focus, these are entirely optional
Parameters:
selected - the image to draw in order to represent a selected radio button
unselected - the image to draw in order to represent an unselected radio
button
disabledSelected - same as selected for the disabled state
disabledUnselected - same as unselected for the disabled state
setPasswordChar
public void setPasswordChar(char c)
Deprecated.
Sets the password character to display in the TextArea and the TextField
Parameters:
the - char to display
getRadioButtonImages
public Image[] getRadioButtonImages()
Deprecated.
Returns the images used to represent the radio button (selected followed by
unselected).
Returns:
images representing the radio button or null for using the default drawing
getRadioButtonFocusImages
public Image[] getRadioButtonFocusImages()
Deprecated.
Returns the images used to represent the radio button when in focused mode
Returns:
images representing the radio button or null for using the default drawing
getCheckBoxImages
public Image[] getCheckBoxImages()
Deprecated.
Returns the images used to represent the checkbox (selected followed by
unselected).
Returns:
images representing the check box or null for using the default drawing
getCheckBoxFocusImages
public Image[] getCheckBoxFocusImages()
Deprecated.
Returns the images used to represent the checkbox when focused
Returns:
images representing the check box or null for using the default drawing
drawButton
public void drawButton(Graphics g,
Button b)
Method Detail
930
Deprecated.
Invoked for drawing a checkbox widget
Specified by:
drawCheckBox in class LookAndFeel
Parameters:
g - graphics context
cb - component to draw
drawLabel
public void drawLabel(Graphics g,
Label l)
Deprecated.
Invoked for drawing the radio button widget
Specified by:
drawRadioButton in class LookAndFeel
Parameters:
g - graphics context
rb - component to draw
drawComboBox
public void drawComboBox(Graphics g,
List cb)
Deprecated.
Invoked for drawing a combo box widget
Specified by:
drawComboBox in class LookAndFeel
Parameters:
g - graphics context
cb - component to draw
drawList
public void drawList(Graphics g,
List l)
Deprecated.
Invoked for drawing a list widget
Specified by:
drawList in class LookAndFeel
Parameters:
g - graphics context
l - component to draw
Method Detail
931
Deprecated.
Draw the given text area
Specified by:
drawTextArea in class LookAndFeel
Parameters:
g - graphics context
ta - component to draw
getButtonPreferredSize
public Dimension getButtonPreferredSize(Button b)
Deprecated.
Calculate the preferred size of the component
Specified by:
getButtonPreferredSize in class LookAndFeel
Parameters:
b - component whose size should be calculated
Returns:
the preferred size for the button
getCheckBoxPreferredSize
public Dimension getCheckBoxPreferredSize(Button cb)
Deprecated.
Calculate the preferred size of the component
Specified by:
getCheckBoxPreferredSize in class LookAndFeel
Parameters:
cb - component whose size should be calculated
Returns:
the preferred size for the component
getLabelPreferredSize
public Dimension getLabelPreferredSize(Label l)
Deprecated.
Calculate the preferred size of the component
Specified by:
getLabelPreferredSize in class LookAndFeel
Parameters:
l - component whose size should be calculated
Returns:
the preferred size for the component
getListPreferredSize
public Dimension getListPreferredSize(List l)
Deprecated.
Calculate the preferred size of the component
Specified by:
getListPreferredSize in class LookAndFeel
Parameters:
l - component whose size should be calculated
Returns:
the preferred size for the component
getRadioButtonPreferredSize
public Dimension getRadioButtonPreferredSize(Button rb)
Deprecated.
Calculate the preferred size of the component
Specified by:
Method Detail
932
Deprecated.
Calculate the preferred size of the component
Specified by:
getTextAreaSize in class LookAndFeel
Parameters:
ta - component whose size should be calculated
pref - indicates whether preferred or scroll size should be returned
Returns:
the preferred size for the component
drawLabelText
protected int drawLabelText(Graphics g,
Label l,
String text,
int x,
int y,
int textSpaceW)
Deprecated.
Draws the text of a label
Parameters:
g - graphics context
l - label component
text - the text for the label
x - position for the label
y - position for the label
textSpaceW - the width available for the component
Returns:
the space used by the drawing
getComboBoxPreferredSize
public Dimension getComboBoxPreferredSize(List cb)
Deprecated.
Calculate the preferred size of the component
Specified by:
getComboBoxPreferredSize in class LookAndFeel
Parameters:
cb - component whose size should be calculated
Returns:
the preferred size for the component
getTextFieldString
protected String getTextFieldString(TextArea ta)
Deprecated.
Similar to getText() but works properly with password fields
drawTextField
public void drawTextField(Graphics g,
TextArea ta)
Deprecated.
Draws the text field without its cursor which is drawn in a separate method input
mode indication can also be drawn using this method.
Specified by:
drawTextField in class LookAndFeel
Method Detail
933
Deprecated.
Calculate the preferred size of the component
Specified by:
getTextFieldPreferredSize in class LookAndFeel
Parameters:
ta - component whose size should be calculated
Returns:
the preferred size for the component
drawTextFieldCursor
public void drawTextFieldCursor(Graphics g,
TextArea ta)
Deprecated.
Draws the cursor of the text field, blinking is handled simply by avoiding a call to this
method.
Specified by:
drawTextFieldCursor in class LookAndFeel
Parameters:
g - graphics context
ta - component to draw
drawPullToRefresh
public void drawPullToRefresh(Graphics g,
Component cmp,
boolean taskExecuted)
Deprecated.
Paints the pull to refresh
Specified by:
drawPullToRefresh in class LookAndFeel
Parameters:
g - graphics context
cmp - the Component which we draw the pull to refresh beneath it
taskExecuted - an indication if the refresh task is currently running
getPullToRefreshHeight
public int getPullToRefreshHeight()
Deprecated.
Returns the required height of the pull to refresh feature
Specified by:
getPullToRefreshHeight in class LookAndFeel
focusGained
public void focusGained(Component cmp)
Deprecated.
Invoked when component gains focus
Specified by:
focusGained in interface FocusListener
Parameters:
cmp - the component that gains focus
focusLost
public void focusLost(Component cmp)
Deprecated.
Invoked when component loses focus
Specified by:
Method Detail
934
Deprecated.
This method is a callback to the LookAndFeel when a theme is being changed in the
UIManager
Overrides:
refreshTheme in class LookAndFeel
Parameters:
b - indicates that the theme is set and not added
Method Detail
935
Class Border
java.lang.Object
com.codename1.ui.plaf.Border
public class
extends Object
Base class that allows us to render a border for a component, a border is drawn before the
component and is drawn within the padding region of the component. It is the responsibility of the
component not to draw outside of the border line.
This class can be extended to provide additional border types and custom made border types.
A border can optionally paint the background of the component, this depends on the border type and
is generally required for rounded borders that "know" the area that should be filled.
Constructor Summary
Modifier
protected
Prevents usage of new operator, use the factory methods in the class or
subclass to create new border types.
Method Summary
Modifier
and Type
void
void
static
Border
static
Border
static
Border
static
Border
static
Border
Class Border
Cleans the tile tracking state allowing the garbage collector to pick up the
component and the image data
createBevelLowered()
Creates a lowered bevel border with default colors, highlight is derived from the
component and shadow is a plain dark color
createBevelLowered(int highlightOuter, int highlightInner,
int shadowOuter, int shadowInner)
Creates a lowered bevel border with default colors, highlight is derived from the
component and shadow is a plain dark color
createBevelRaised(int highlightOuter, int highlightInner,
int shadowOuter, int shadowInner)
Creates a border that is comprised of multiple border types so one border type
can be used on top while another one can be used at the bottom.
static
Border
createDashedBorder(int thickness)
static
Border
static
Border
createDottedBorder(int thickness)
Creates a dashed border with the specified thickness and the theme colors
Creates a dashed border with the specified thickness and color
Creates a dotted border with the specified thickness and the theme colors
936
static
Border
createDoubleBorder(int thickness)
static
Border
static
Border
static
Border
static
Border
static
Border
Creates an empty border, this is useful where we don't want a border for a
component but want a focus border etc...
createEtchedLowered()
Creates a lowered etched border with default colors, highlight is derived from the
component and shadow is a plain dark color
createEtchedLowered(int highlight, int shadow)
Creates a lowered etched border with default colors, highlight is derived from the
component and shadow is a plain dark color
static
Border
static
Border
createGrooveBorder(int thickness)
static
Border
static
Border
static
Border
static
Border
static
Border
The given images are tiled appropriately across the matching side of the border,
rotated and placed as expected in the four corners.
createImageBorder(Image top, Image bottom, Image left, Image right,
Image topLeft, Image topRight, Image bottomLeft, Image bottomRight,
Image background)
The given top/bottom/left/right images are tiled appropriately across the matching
sides of the border and the corners are placed as expected in the four corners.
createImageScaledBorder(Image top, Image bottom, Image left,
Image right, Image topLeft, Image topRight, Image bottomLeft,
Image bottomRight, Image background)
static
Border
createInsetBorder(int thickness)
static
Border
static
Border
Creates an inset border with the specified thickness and theme colors
Creates an inset border with the specified thickness and color
createLineBorder(int thickness)
Creates a line border that uses the color of the component foreground for
drawing
static
Border
static
Border
static
Border
static
Border
createOutsetBorder(int thickness)
static
Border
Creates a line border that uses the given color for the component
Creates a line border that uses the given color for the component
Creates a line border with the specified title
Creates an outset border with the specified thickness and theme colors
Creates an outset border with the specified thickness and color
createPressedVersion()
Border
When applied to buttons borders produce a version that reverses the effects of
the border providing a pressed feel
createRidgeBorder(int thickness)
Method Summary
937
Creates a ridge border with the specified thickness and theme colors
static
Border
static
Border
Deprecated.
the performance of round rect borders is REALLY slow, we recommend people
use image borders which are faster, more portable and better looking
createRoundBorder(int arcWidth, int arcHeight, boolean outline)
static
Border
Deprecated.
the performance of round rect borders is REALLY slow, we recommend people
use image borders which are faster, more portable and better looking
createRoundBorder(int arcWidth, int arcHeight, int color)
static
Border
Deprecated.
the performance of round rect borders is REALLY slow, we recommend people
use image borders which are faster, more portable and better looking
createRoundBorder(int arcWidth, int arcHeight, int color,
boolean outline)
static
Border
Deprecated.
the performance of round rect borders is REALLY slow, we recommend people
use image borders which are faster, more portable and better looking
static
Border
boolean
Border[]
static
Border
static
Border
Deprecated.
use createEmpty instead
getFocusedInstance()
Border
Deprecated.
use the getSelectedStyle() method in the component class
getMinimumHeight()
int
Returns the minimum size required to properly display this border, normally this
is 0 but a border might deem itself undisplayable with too small a size e.g.
getMinimumWidth()
int
Border
Object
Returns the minimum size required to properly display this border, normally this
is 0 but a border might deem itself undisplayable with too small a size e.g.
getPressedInstance()
Returns the pressed version of the border if one is set by the user
getProperty(String n)
int
This method returns how thick is the border in pixels, notice this doesn't apply to
most border types
isBackgroundPainter()
boolean
boolean
Returns true if installing this border will override the painting of the component
background
isEmptyBorder()
boolean
boolean
void
Method Summary
Allows toggling the order in which the outer and inner borders are painted for the
Outer border type
isRectangleType()
938
Draws the border for the given component, this method is called before a call to
background painting is made.
void
paintBorderBackground(Graphics g, Component c)
Has effect when the border demands responsibility for background painting
normally the painter will perform this work but in this case the border might do it
instead.
void
static
void
setDefaultBorder(Border border)
Deprecated.
use the getSelectedStyle() method in the component class
void
This method is designed mainly for the purpose of creating an arrow that will
track a specific component using the image border the tile given would be an
arrow like image just like the ones used for the top/bottom/left/right images.
void
This method is designed mainly for the purpose of creating an arrow that will
track a specific component using the image border the tile given would be an
arrow like image just like the ones used for the top/bottom/left/right images.
void
setPaintOuterBorderFirst(boolean paintOuterBorderFirst)
Allows toggling the order in which the outer and inner borders are painted for the
Outer border type
void
setPressedInstance(Border pressed)
void
Allows us to define a border that will act as the pressed version of this border
setThickness(int thickness)
This method returns sets the border thickness in pixels, notice this doesn't apply
to most border types
void
unlock()
void
Constructor Detail
Border
protected Border()
Prevents usage of new operator, use the factory methods in the class or subclass to
create new border types.
Method Detail
mirrorBorder
public Border mirrorBorder()
939
This method is designed mainly for the purpose of creating an arrow that will track a
specific component using the image border the tile given would be an arrow like
image just like the ones used for the top/bottom/left/right images. This image would
be positioned so it points at the center of the track component
Parameters:
tileTop - an image that will replace one of the tiles on the top if the track
component is there
tileBottom - an image that will replace one of the tiles on the bottom if the
track component is there
tileLeft - an image that will replace one of the tiles on the left if the track
component is there
tileRight - an image that will replace one of the tiles on the right if the track
component is there
trackComponent - the component that will be tracked for the positioning of the
tile
setImageBorderSpecialTile
public void setImageBorderSpecialTile(Image tileTop,
Image tileBottom,
Image tileLeft,
Image tileRight,
Rectangle trackComponent)
This method is designed mainly for the purpose of creating an arrow that will track a
specific component using the image border the tile given would be an arrow like
image just like the ones used for the top/bottom/left/right images. This image would
be positioned so it points at the center of the track component
Parameters:
tileTop - an image that will replace one of the tiles on the top if the track
component is there
tileBottom - an image that will replace one of the tiles on the bottom if the
track component is there
tileLeft - an image that will replace one of the tiles on the left if the track
component is there
tileRight - an image that will replace one of the tiles on the right if the track
component is there
trackComponent - the component that will be tracked for the positioning of the
tile
clearImageBorderSpecialTile
public void clearImageBorderSpecialTile()
Cleans the tile tracking state allowing the garbage collector to pick up the component
and the image data
addOuterBorder
public void addOuterBorder(Border outer)
Method Detail
940
Returns the minimum size required to properly display this border, normally this is 0
but a border might deem itself undisplayable with too small a size e.g. for the case of
an image border the minimum height would be top + bottom and the minimum width
would be left+right
Returns:
0 if not applicable or a dimension if it is.
getEmpty
public static Border getEmpty()
Creates an empty border, this is useful where we don't want a border for a
component but want a focus border etc...
Returns:
a border than draws nothing
isEmptyBorder
public boolean isEmptyBorder()
top,
bottom,
left,
right,
topLeft,
topRight,
bottomLeft,
bottomRight,
background)
The given top/bottom/left/right images are tiled appropriately across the matching
sides of the border and the corners are placed as expected in the four corners. The
background image is optional and it will be tiled in the background if necessary.
By default this border does not override background unless a background image is
specified
Parameters:
top - the image of the top line
bottom - the image of the bottom line
left - the image of the left line
right - the image of the right line
topLeft - the image of the top left corner
topRight - the image of the top right corner
bottomLeft - the image of the bottom left corner
bottomRight - the image of the bottom right corner
Method Detail
941
top,
bottom,
left,
right,
topLeft,
topRight,
bottomLeft,
bottomRight,
background)
The given top/bottom/left/right images are scaled appropriately across the matching
sides of the border and the corners are placed as expected in the four corners. The
background image is optional and it will be tiled in the background if necessary.
By default this border does not override background unless a background image is
specified
Parameters:
top - the image of the top line
bottom - the image of the bottom line
left - the image of the left line
right - the image of the right line
topLeft - the image of the top left corner
topRight - the image of the top right corner
bottomLeft - the image of the bottom left corner
bottomRight - the image of the bottom right corner
background - the image of the background (optional)
Returns:
new border instance
createHorizonalImageBorder
public static Border createHorizonalImageBorder(Image left,
Image right,
Image center)
The given images are tiled appropriately across the matching side of the border,
rotated and placed as expected in the four corners. The background image is optional
and it will be tiled in the background if necessary.
Method Detail
942
Creates a line border that uses the color of the component foreground for drawing
Parameters:
thickness - thickness of the border in pixels
Returns:
new border instance
createDottedBorder
public static Border createDottedBorder(int thickness,
int color)
Creates a dotted border with the specified thickness and the theme colors
Parameters:
thickness - The border thickness in pixels
Returns:
The border
Method Detail
943
Creates a dashed border with the specified thickness and the theme colors
Parameters:
thickness - The border thickness in pixels
Returns:
The border
createDoubleBorder
public static Border createDoubleBorder(int thickness)
Creates an outset border with the specified thickness and theme colors
Parameters:
thickness - The border thickness in pixels
Returns:
The border
createOutsetBorder
public static Border createOutsetBorder(int thickness,
int color)
Creates an inset border with the specified thickness and theme colors
Parameters:
thickness - The border thickness in pixels
Returns:
The border
createInsetBorder
public static Border createInsetBorder(int thickness,
int color)
Creates a groove border with the specified thickness and theme colors
Parameters:
thickness - The border thickness in pixels
Returns:
The border
Method Detail
944
Creates a ridge border with the specified thickness and theme colors
Parameters:
thickness - The border thickness in pixels
Returns:
The border
createRidgeBorder
public static Border createRidgeBorder(int thickness,
int color)
Creates a line border that uses the given color for the component
Parameters:
thickness - thickness of the border in pixels
color - the color for the border
title - The border's title
Returns:
new border instance
createLineBorder
public static Border createLineBorder(int thickness,
int color)
Creates a line border that uses the given color for the component
Parameters:
thickness - thickness of the border in pixels
color - the color for the border
Returns:
new border instance
Method Detail
945
Returns:
new border instance
createRoundBorder
public static Border createRoundBorder(int arcWidth,
int arcHeight,
boolean outline)
Returns:
new border instance
createRoundBorder
public static Border createRoundBorder(int arcWidth,
int arcHeight,
int color)
Returns:
new border instance
createRoundBorder
public static Border createRoundBorder(int arcWidth,
int arcHeight,
int color,
boolean outline)
Method Detail
946
Returns:
new border instance
createEtchedLowered
public static Border createEtchedLowered()
Creates a lowered etched border with default colors, highlight is derived from the
component and shadow is a plain dark color
Returns:
new border instance
createEtchedLowered
public static Border createEtchedLowered(int highlight,
int shadow)
Creates a lowered etched border with default colors, highlight is derived from the
component and shadow is a plain dark color
Returns:
new border instance
createEtchedRaised
public static Border createEtchedRaised(int highlight,
int shadow)
{Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
Method Detail
947
top,
bottom,
left,
right)
Creates a border that is comprised of multiple border types so one border type can
be used on top while another one can be used at the bottom. Notice that this doesn't
work well with all border types (e.g. image borders)
Parameters:
top - the top border
bottom - the bottom border
left - the left border
right - the right border
Returns:
a compound border
isBackgroundPainter
public boolean isBackgroundPainter()
Returns true if installing this border will override the painting of the component
background
Returns:
true if this border replaces the painter
isRectangleType
public boolean isRectangleType()
Creates a lowered bevel border with default colors, highlight is derived from the
component and shadow is a plain dark color
Returns:
new border instance
createBevelLowered
public static Border createBevelLowered(int
int
int
int
highlightOuter,
highlightInner,
shadowOuter,
shadowInner)
Creates a lowered bevel border with default colors, highlight is derived from the
component and shadow is a plain dark color
Returns:
new border instance
Method Detail
948
highlightOuter,
highlightInner,
shadowOuter,
shadowInner)
Allows us to define a border that will act as the pressed version of this border
Parameters:
pressed - a border that will be returned by the pressed version method
setFocusedInstance
public void setFocusedInstance(Border focused)
Returns the pressed version of the border if one is set by the user
Returns:
the pressed instance of this border
createPressedVersion
public Border createPressedVersion()
When applied to buttons borders produce a version that reverses the effects of the
border providing a pressed feel
Returns:
a border that will make the button feel pressed
paintBorderBackground
public void paintBorderBackground(Graphics g,
Component c)
Has effect when the border demands responsibility for background painting normally
the painter will perform this work but in this case the border might do it instead.
Parameters:
g - graphics context to draw onto
c - component whose border should be drawn
Method Detail
949
Draws the border for the given component, this method is called before a call to
background painting is made.
Parameters:
g - graphics context to draw onto
c - component whose border should be drawn
setDefaultBorder
public static void setDefaultBorder(Border border)
This method returns how thick is the border in pixels, notice this doesn't apply to most
border types
Returns:
the Border thickness
setThickness
public void setThickness(int thickness)
This method returns sets the border thickness in pixels, notice this doesn't apply to
most border types
Parameters:
thickness - the Border thickness
setPaintOuterBorderFirst
public void setPaintOuterBorderFirst(boolean paintOuterBorderFirst)
Allows toggling the order in which the outer and inner borders are painted for the
Outer border type
Parameters:
paintOuterBorderFirst - whether the outside border should be painter first
isPaintOuterBorderFirst
public boolean isPaintOuterBorderFirst()
Allows toggling the order in which the outer and inner borders are painted for the
Outer border type
Returns:
whether the outside border should be painter first
getCompoundBorders
public Border[] getCompoundBorders()
This method returns the Compound Borders array. The array size is 4 and the
borders arranged as follows : Border[] borders = getCompoundBorders(); Border top
= borders[Component.TOP]; Border bottom = borders[Component.BOTTOM]; Border
left = borders[Component.LEFT]; Border right = borders[Component.RIGHT];
Returns:
the borders array or null if this is not a Compound Border
Method Detail
950
This callback indicates that a component pointing at this border is initialized, this
method is useful for image borders whose lock methods are implicitly invoked. This
method may be invoked multiple times.
unlock
public void unlock()
This callback indicates that a component pointing at this border is now deinitilized
This method may be invoked multiple times.
getProperty
public Object getProperty(String n)
Method Detail
951
Class PainterChain
java.lang.Object
com.codename1.ui.painter.PainterChain
All Implemented Interfaces:
Painter
public class
extends Object
implements Painter
A painter chain allows us to chain together several painters to provide a "layer" effect where each
painter only draws one element.
Constructor Summary
Constructor and Description
PainterChain(Painter painter)
Create a new painter chain which will paint all of the elements in the chain in sequence from
0 to the last element
PainterChain(Painter[] chain)
Create a new painter chain which will paint all of the elements in the chain in sequence from
0 to the last element
Method Summary
Modifier and
Type
PainterChain
Painter[]
Creates a new chain based on the existing chain with the new element
added at the end
getChain()
static void
Installs a glass pane on the given form making sure to make it a painter
chain only if required by existing painter
paint(Graphics g, Rectangle rect)
void
PainterChain
Creates a new chain based on the existing chain with the new element
added at the beginning
removeGlassPane(Form f, Painter p)
static void
Removes a glass pane from the given form, this is the opposite operation
for the install glass pane
Constructor Detail
Class PainterChain
952
Create a new painter chain which will paint all of the elements in the chain in
sequence from 0 to the last element
Parameters:
chain - the chain of components in the painter
PainterChain
public PainterChain(Painter painter)
Create a new painter chain which will paint all of the elements in the chain in
sequence from 0 to the last element
Parameters:
painter - the chain first Painter
Method Detail
addPainter
public PainterChain addPainter(Painter p)
Creates a new chain based on the existing chain with the new element added at the
end
Parameters:
p - new painter
Returns:
new chain element
prependPainter
public PainterChain prependPainter(Painter p)
Creates a new chain based on the existing chain with the new element added at the
beginning
Parameters:
p - new painter
Returns:
new chain element
paint
public void paint(Graphics g,
Rectangle rect)
Installs a glass pane on the given form making sure to make it a painter chain only if
required by existing painter
Parameters:
f - form on which to install the chain
p - painter to install
getChain
public Painter[] getChain()
Constructor Detail
953
Removes a glass pane from the given form, this is the opposite operation for the
install glass pane
Parameters:
f - form from which to remove the chain
p - painter to remove
Method Detail
954
Class BackgroundPainter
java.lang.Object
com.codename1.ui.painter.BackgroundPainter
All Implemented Interfaces:
Painter
public class
extends Object
implements Painter
Constructor Summary
Constructor and Description
BackgroundPainter(Component parent)
Method Summary
Modifier and Type
void
Constructor Detail
BackgroundPainter
public BackgroundPainter(Component parent)
Method Detail
paint
public void paint(Graphics g,
Rectangle rect)
Class BackgroundPainter
955
Class MultiList
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.List
com.codename1.ui.list.MultiList
All Implemented Interfaces:
Animation, StyleListener
public class
extends List
A list with a MultiButton renderer. This simplifies the process of working with the list and its model as
the renderer comes pre-configured for common use cases.
private void showMultiList() {
Form hi = new Form("MultiList", new BorderLayout());
ArrayList<Map<String, Object>> data = new ArrayList<>();
data.add(createListEntry("A Game of Thrones", "1996"), icon1);
data.add(createListEntry("A Clash Of Kings", "1998"), icon2);
data.add(createListEntry("A Storm Of Swords", "2000"), icon3);
data.add(createListEntry("A Feast For Crows", "2005"), icon4);
data.add(createListEntry("A Dance With Dragons", "2011"), icon5);
data.add(createListEntry("The Winds of Winter", "2016 (please, please, please)"), icon6);
data.add(createListEntry("A Dream of Spring", "Ugh"), icon7);
DefaultListModel<Map<String, Object>> model = new DefaultListModel<>(data);
MultiList ml = new MultiList(model);
hi.add(BorderLayout.CENTER, ml);
hi.show();
}
private Map<String, Object> createListEntry(String name, String date, Image icon) {
Map<String, Object> entry = new HashMap<>();
entry.put("Line1", name);
entry.put("Line2", date);
entry.put("icon", icon);
return entry;
}
Method Detail
956
Summary
Constructor Summary
Constructor and Description
MultiList()
Method Summary
Modifier and
Type
protected
void
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the
GUI builder
Object
getSelectedButton()
MultiButton
MultiButton
protected
void
String
Sets a new value to the given property, returns an error message if failed
and null if successful.
Field Summary
957
958
Detail
MultiList
public MultiList(ListModel model)
Method Detail
initComponent
protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
deinitialize
protected void deinitialize()
Constructor Detail
959
getPropertyTypes
public Class[] getPropertyTypes()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
960
Interface ListModel<T>
All Known Implementing Classes:
CloudListModel, ContactsModel, DefaultListModel, FilterProxyListModel
public interface
Represents the data structure of the list, thus allowing a list to represent any potential data source by
referencing different implementations of this interface. E.g. a list model can be implemented in such a
way that it retrieves data directly from storage (although caching would be recommended).
It is the responsibility of the list to notify observers (specifically the view List of any changes to its
state (items removed/added/changed etc.) thus the data would get updated on the view.
class GRMMModel implements ListModel<Map<String,Object>> {
{@literal @}Override
public Map<String, Object> getItemAt(int index) {
int idx = index % 7;
switch(idx) {
case 0:
return createListEntry("A Game of Thrones " + index, "1996");
case 1:
return createListEntry("A Clash Of Kings " + index, "1998");
case 2:
return createListEntry("A Storm Of Swords " + index, "2000");
case 3:
return createListEntry("A Feast For Crows " + index, "2005");
case 4:
return createListEntry("A Dance With Dragons " + index, "2011");
case 5:
return createListEntry("The Winds of Winter " + index, "2016 (please, please, please)");
default:
return createListEntry("A Dream of Spring " + index, "Ugh");
}
}
{@literal @}Override
public int getSize() {
return 1000000;
}
{@literal @}Override
public int getSelectedIndex() {
return 0;
}
{@literal @}Override
public void setSelectedIndex(int index) {
}
{@literal @}Override
public void addDataChangedListener(DataChangedListener l) {
}
{@literal @}Override
public void removeDataChangedListener(DataChangedListener l) {
}
{@literal @}Override
public void addSelectionListener(SelectionListener l) {
}
{@literal @}Override
public void removeSelectionListener(SelectionListener l) {
}
{@literal @}Override
public void addItem(Map<String, Object> item) {
}
{@literal @}Override
public void removeItem(int index) {
}
}
Interface ListModel<T>
961
A ListModel can be used in conjunction with an ImageViewer to fetch images dynamically into the
view:
Form hi = new Form("ImageViewer", new BorderLayout());
final EncodedImage placeholder = EncodedImage.createFromImage(
FontImage.createMaterial(FontImage.MATERIAL_SYNC, s).
scaled(300, 300), false);
class ImageList implements ListModel<Image> {
private int selection;
private String[] imageURLs = {
"http://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/300px-AGameOfThrones.jpg",
"http://awoiaf.westeros.org/images/thumb/3/39/AClashOfKings.jpg/300px-AClashOfKings.jpg",
"http://awoiaf.westeros.org/images/thumb/2/24/AStormOfSwords.jpg/300px-AStormOfSwords.jpg",
"http://awoiaf.westeros.org/images/thumb/a/a3/AFeastForCrows.jpg/300px-AFeastForCrows.jpg",
"http://awoiaf.westeros.org/images/7/79/ADanceWithDragons.jpg"
};
private Image[] images;
private EventDispatcher listeners = new EventDispatcher();
public ImageList() {
this.images = new EncodedImage[imageURLs.length];
}
public Image getItemAt(final int index) {
if(images[index] == null) {
images[index] = placeholder;
Util.downloadUrlToStorageInBackground(imageURLs[index], "list" + index, (e) -> {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("list" + index));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch(IOException err) {
err.printStackTrace();
}
});
}
return images[index];
}
public int getSize() {
return imageURLs.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
Interface ListModel<T>
962
Method Summary
Modifier and Type
void
void
void
T
int
int
void
Method Summary
963
void
void
void
Method Detail
getItemAt
T getItemAt(int index)
Method Detail
964
Adds the specified item to the end of this list. An optional operation for mutable lists, it
can throw an unsupported operation exception if a list model is not mutable.
Parameters:
item - the item to be added
removeItem
void removeItem(int index)
Method Detail
965
Interface ListCellRenderer<T>
All Known Implementing Classes:
DefaultListCellRenderer, GenericListCellRenderer
public interface
A "rubber stamp" tool that allows us to extract a component (often the same component instance for
all invocations) that is initialized to the value of the current item extracted from the model, this
component is drawn on the list and discarded. No state of the component is kept and the component
is essentially discarded.
This is a very advanced interface it is recommended that you use either the
DefaultListCellRenderer or GenericListCellRenderer whenever possible to avoid mistakes.
An instance of a renderer can be developed as such:
public class MyYesNoRenderer extends Label implements ListCellRenderer {
Label label = new label(" ");
public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected) {
if( ((Boolean)value).booleanValue() ) {
setText("Yes");
} else {
setText("No");
}
return this;
}
public Component getListFocusComponent(List list) {
return label;
}
}
Method Summary
Modifier and
Type
Component
Method Detail
getListCellRendererComponent
Component getListCellRendererComponent(List list,
T value,
int index,
boolean isSelected)
Returns a component instance that is already set to render "value". While it is not a
requirement many renderes often derive from a component (such as a label) and
return "this". Notice that a null value for the value argument might be sent when
refreshing the theme of the list.
Parameters:
list - the list component
value - the value to render
index - the index in the list
isSelected - whether the entry is selected
Returns:
Interface ListCellRenderer<T>
966
Returns a component instance that is painted under the currently focused renderer
and is animated to provide smooth scrolling. When the selection moves, this
component is drawn above/bellow the list items - it is recommended to give this
component some level of transparency (see above code example). This method is
optional an implementation can choose to return null.
Parameters:
list - the parent list
Returns:
a component to use as focus
See Also:
Component.setSmoothScrolling(boolean)
Method Detail
967
Class GenericListCellRenderer<T>
java.lang.Object
com.codename1.ui.list.GenericListCellRenderer<T>
All Implemented Interfaces:
CellRenderer<T>, ListCellRenderer<T>
public class
extends Object
implements ListCellRenderer<T>, CellRenderer<T>
The generic list cell renderer can display containers or arbitrary Codename One components as items
in a list. It relies on the source data being a Map object. It extracts values from the Map using the
component name as an indication to the Map key lookup.
This renderer supports label tickering, check boxes/radio buttons etc. seamlessly.
Please notice that you must use at least two distinct instances of the component when passing them
to the constructor, reusing the same instance WILL NOT WORK!
Furthermore, the renderer instance cannot be reused for multiple lists, each list will need a new
instance of this renderer!
Sample usage for this renderer follows:
com.codename1.ui.List list = new com.codename1.ui.List(createGenericListCellRendererModelData());
list.setRenderer(new GenericListCellRenderer(createGenericRendererContainer(), createGenericRendererContainer()));
Class GenericListCellRenderer<T>
968
Field Summary
Modifier and
Type
Field Summary
969
If this flag exists in a Map of data the renderer will enable/disable the entries,
the flag assumes either Boolean.TRUE or Boolean.FALSE.
SELECT_ALL_FLAG
Put this flag as a Map key to indicate that a checkbox entry rendered by this
renderer should act as a "select all" entry and toggle all other entries.
Constructor Summary
Constructor and Description
GenericListCellRenderer(Component selected, Component unselected)
Constructs a generic renderer with the given selected/unselected components for odd/even
values allowing a "pinstripe" effect
Method Summary
Modifier and Type
Button
URLImage.ImageAdapter
Component
static
URLImage.ImageAdapter
Component
Component
Component
Component
getSelected()
Component
getSelectedEven()
Component
getUnselected()
Component
getUnselectedEven()
isFisheye()
boolean
boolean
isSelectionListener()
void
static void
setAdapter(URLImage.ImageAdapter adapter)
void
void
setSelectionListener(boolean selectionListener)
void
updateIconPlaceholders()
Constructor Summary
970
Field Detail
ENABLED
public static final String ENABLED
If this flag exists in a Map of data the renderer will enable/disable the entries, the flag
assumes either Boolean.TRUE or Boolean.FALSE. Notice that just setting it to false
when necessary will not work, when its used it must be applied to all entries
otherwise the reuse of the renderer component will break this feature.
See Also:
Constant Field Values
SELECT_ALL_FLAG
public static final String SELECT_ALL_FLAG
Put this flag as a Map key to indicate that a checkbox entry rendered by this renderer
should act as a "select all" entry and toggle all other entries. The value for this entry is
ignored
See Also:
Constant Field Values
Constructor Detail
GenericListCellRenderer
public GenericListCellRenderer(Component selected,
Component unselected)
odd,
oddUnselected,
even,
evenUnselected)
Method Detail
Method Summary
971
Updates the placeholder instances, this is useful for changing the URLImage
placeholder in runtime as might happen in the designer
extractLastClickedComponent
public Button extractLastClickedComponent()
Allows partitioning the renderer into "areas" that can be clicked. When receiving an
action event in the list this method allows a developer to query the renderer to "see"
whether a button within the component was "touched" by the user on a touch screen
device. This method will reset the value to null after returning a none-null value!
Returns:
a button or null
getCellRendererComponent
public Component getCellRendererComponent(Component list,
Object model,
T value,
int index,
boolean isSelected)
Returns a component instance that is already set to render "value". While it is not a
requirement many renderes often derive from a component (such as a label) and
return "this". Notice that a null value for the value argument might be sent when
refreshing the theme of the list.
Specified by:
getCellRendererComponent in interface CellRenderer<T>
Parameters:
list - the list component
model - the model behind the render
value - the value to render
index - the index in the list
isSelected - whether the entry is selected
Returns:
a component to paint within the list
getListCellRendererComponent
public Component getListCellRendererComponent(List list,
T value,
int index,
boolean isSelected)
Returns a component instance that is already set to render "value". While it is not a
requirement many renderes often derive from a component (such as a label) and
return "this". Notice that a null value for the value argument might be sent when
refreshing the theme of the list.
Specified by:
getListCellRendererComponent in interface ListCellRenderer<T>
Parameters:
Method Detail
972
is selected
Returns:
a component to paint within the list
getListFocusComponent
public Component getListFocusComponent(List list)
Returns a component instance that is painted under the currently focused renderer
and is animated to provide smooth scrolling. When the selection moves, this
component is drawn above/bellow the list items - it is recommended to give this
component some level of transparency (see above code example). This method is
optional an implementation can choose to return null.
Specified by:
getListFocusComponent in interface ListCellRenderer<T>
Parameters:
list - the parent list
Returns:
a component to use as focus
See Also:
Component.setSmoothScrolling(boolean)
getFocusComponent
public Component getFocusComponent(Component list)
Returns a component instance that is painted under the currently focused renderer
and is animated to provide smooth scrolling. When the selection moves, this
component is drawn above/bellow the list items - it is recommended to give this
component some level of transparency (see above code example). This method is
optional an implementation can choose to return null.
Specified by:
getFocusComponent in interface CellRenderer<T>
Parameters:
list - the parent list
Returns:
a component to use as focus
See Also:
Component.setSmoothScrolling(boolean)
isSelectionListener
public boolean isSelectionListener()
Returns:
the selectionListener
setSelectionListener
public void setSelectionListener(boolean selectionListener)
Parameters:
selectionListener
getSelected
public Component getSelected()
Returns:
the selected
getUnselected
public Component getUnselected()
Returns:
the unselected
Method Detail
973
Returns:
the selectedEven
getUnselectedEven
public Component getUnselectedEven()
Returns:
the unselectedEven
isFisheye
public boolean isFisheye()
Method Detail
974
Class FilterProxyListModel<T>
java.lang.Object
com.codename1.ui.list.FilterProxyListModel<T>
All Implemented Interfaces:
DataChangedListener, ListModel<T>
public class
extends Object
implements ListModel<T>, DataChangedListener
This class allows filtering/sorting a list model dynamically using a text field
Field Summary
Constructor Summary
Constructor and Description
FilterProxyListModel(ListModel<T> underlying)
Method Summary
Modifier
and Type
void
void
void
protected
boolean
protected
int
void
void
T
int
int
Class FilterProxyListModel<T>
975
getUnderlying()
Returns the underlying model which is needed to perform mutations on the list.
install(TextField search, ContainerList l)
Installs a search field on a list making sure the filter method is invoked properly
install(TextField search, List l)
Installs a search field on a list making sure the filter method is invoked properly
isStartsWithMode()
boolean
When enabled this makes the filter check that the string starts with rather than
within the index
removeDataChangedListener(DataChangedListener l)
void
void
void
void
When enabled this makes the filter check that the string starts with rather than
within the index
void
sort(boolean ascending)
This method performs a sort of the list, to determine the sort order this class
should be derived and the compare() method should be overriden
void
Constructor Detail
FilterProxyListModel
public FilterProxyListModel(ListModel<T> underlying)
Method Detail
sort
public void sort(boolean ascending)
This method performs a sort of the list, to determine the sort order this class should
be derived and the compare() method should be overriden
Parameters:
ascending - sort in ascending order
compare
protected int compare(Object a,
Object b,
boolean ascending)
This method can be overriden by subclasses to allow sorting arbitrary objects within
the list, it follows the traditional contract of the compare method in Java
Parameters:
a - first object
b - second object
ascending - direction of sort
Method Summary
976
Returns the underlying model which is needed to perform mutations on the list.
Returns:
the underlying model
check
protected boolean check(Object o,
String str)
Checks whether the filter condition is matched, receives an uppercase version of the
filter string to match against
Parameters:
o - the object being compared
str - the string
Returns:
true if match is checked
filter
public void filter(String str)
Method Detail
977
Adds the specified item to the end of this list. An optional operation for mutable lists, it
can throw an unsupported operation exception if a list model is not mutable.
Specified by:
addItem in interface ListModel<T>
Parameters:
item - the item to be added
removeItem
public void removeItem(int index)
Method Detail
978
Installs a search field on a list making sure the filter method is invoked properly
install
public static void install(TextField search,
ContainerList l)
Installs a search field on a list making sure the filter method is invoked properly
isStartsWithMode
public boolean isStartsWithMode()
When enabled this makes the filter check that the string starts with rather than within
the index
Returns:
the startsWithMode
setStartsWithMode
public void setStartsWithMode(boolean startsWithMode)
When enabled this makes the filter check that the string starts with rather than within
the index
Parameters:
startsWithMode - the startsWithMode to set
Method Detail
979
Class DefaultListModel<T>
java.lang.Object
com.codename1.ui.list.DefaultListModel<T>
All Implemented Interfaces:
ListModel<T>
Direct Known Subclasses:
ContactsModel
public class
extends Object
implements ListModel<T>
Default implementation of the list model based on a List of elements. The list model is an observable
set of objects that List uses to pull the data to display.
private void showMultiList() {
Form hi = new Form("MultiList", new BorderLayout());
ArrayList<Map<String, Object>> data = new ArrayList<>();
data.add(createListEntry("A Game of Thrones", "1996"), icon1);
data.add(createListEntry("A Clash Of Kings", "1998"), icon2);
data.add(createListEntry("A Storm Of Swords", "2000"), icon3);
data.add(createListEntry("A Feast For Crows", "2005"), icon4);
data.add(createListEntry("A Dance With Dragons", "2011"), icon5);
data.add(createListEntry("The Winds of Winter", "2016 (please, please, please)"), icon6);
data.add(createListEntry("A Dream of Spring", "Ugh"), icon7);
DefaultListModel<Map<String, Object>> model = new DefaultListModel<>(data);
MultiList ml = new MultiList(model);
hi.add(BorderLayout.CENTER, ml);
hi.show();
}
private Map<String, Object> createListEntry(String name, String date, Image icon) {
Map<String, Object> entry = new HashMap<>();
entry.put("Line1", name);
entry.put("Line2", date);
entry.put("icon", icon);
return entry;
}
Class DefaultListModel<T>
980
Constructor
Summary
Method Summary
Modifier and
Type
void
void
void
void
protected void
List<T>
Returns the internal list of items which makes traversal using iterators
easier.
getSelectedIndex()
int
int
void
void
void
void
void
void
Constructor Detail
Constructor Summary
981
Method Detail
getItemAt
public T getItemAt(int index)
Adds the specified item to the end of this list. An optional operation for mutable lists, it
can throw an unsupported operation exception if a list model is not mutable.
Constructor Detail
982
in interface ListModel<T>
Parameters:
item
setItem
public void setItem(int index,
T item)
Method Detail
983
Returns the internal list of items which makes traversal using iterators easier.
Returns:
the list, notice that you shouldn't modify it
Method Detail
984
Class DefaultListCellRenderer<T>
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.list.DefaultListCellRenderer<T>
All Implemented Interfaces:
Animation, StyleListener, CellRenderer<T>, ListCellRenderer<T>
public class
extends Label
implements ListCellRenderer<T>, CellRenderer<T>
Default implementation of the renderer based on a label see the ListCellRenderer for more
information about the use and purpose of this class
Field Summary
Constructor Summary
Constructor and Description
DefaultListCellRenderer()
Method Summary
Modifier
and Type
Component
Component
int
Style
Returns the current Component Style allowing code to draw the current
component, you should normally use getUnselected/Pressed/DisabledStyle()
Class DefaultListCellRenderer<T>
985
initLaf(UIManager uim)
boolean
boolean
isRightAlignNumbers()
boolean
static
boolean
isShowNumbers()
Indicate whether numbering should exist for the default cell renderer
isShowNumbersDefault()
Inidicates whether the default list cell renderer will show numbers by default
when constructed
refreshTheme(boolean merge)
Makes sure the component is up to date with the current theme, ONLY INVOKE
THIS METHOD IF YOU CHANGED THE THEME!
void
repaint()
void
setAlwaysRenderSelection(boolean alwaysRenderSelection)
void
void
setRightAlignNumbers(boolean rightAlignNumbers)
setSelectionTransparency(int selectionTransparency)
void
void
Indicate whether numbering should exist for the default cell renderer
static
void
setShowNumbersDefault(boolean def)
Inidicates whether the default list cell renderer will show numbers by default
when constructed
Method Summary
986
Constructor Detail
DefaultListCellRenderer
public DefaultListCellRenderer()
Method Detail
initLaf
protected void initLaf(UIManager uim)
987
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Component
Parameters:
merge - indicates if the current styles should be merged with the new styles
getCellRendererComponent
public Component getCellRendererComponent(Component list,
Object model,
T value,
int index,
boolean isSelected)
Returns a component instance that is already set to render "value". While it is not a
requirement many renderes often derive from a component (such as a label) and
return "this". Notice that a null value for the value argument might be sent when
refreshing the theme of the list.
Specified by:
getCellRendererComponent in interface CellRenderer<T>
Parameters:
list - the list component
model - the model behind the render
value - the value to render
index - the index in the list
isSelected - whether the entry is selected
Returns:
a component to paint within the list
getStyle
public Style getStyle()
Returns the current Component Style allowing code to draw the current component,
you should normally use getUnselected/Pressed/DisabledStyle() and not this method
since it will return different values based on component state.
Overrides:
getStyle in class Component
Returns:
the component Style object
getListCellRendererComponent
public Component getListCellRendererComponent(List list,
T value,
int index,
boolean isSelected)
Returns a component instance that is already set to render "value". While it is not a
requirement many renderes often derive from a component (such as a label) and
return "this". Notice that a null value for the value argument might be sent when
refreshing the theme of the list.
Specified by:
getListCellRendererComponent in interface ListCellRenderer<T>
Parameters:
list - the list component
value - the value to render
index - the index in the list
isSelected - whether the entry is selected
Returns:
a component to paint within the list
Method Detail
988
Returns a component instance that is painted under the currently focused renderer
and is animated to provide smooth scrolling. When the selection moves, this
component is drawn above/bellow the list items - it is recommended to give this
component some level of transparency (see above code example). This method is
optional an implementation can choose to return null.
Specified by:
getListFocusComponent in interface ListCellRenderer<T>
Parameters:
list - the parent list
Returns:
a component to use as focus
See Also:
Component.setSmoothScrolling(boolean)
repaint
public void repaint()
isShowNumbers
public boolean isShowNumbers()
Indicate whether numbering should exist for the default cell renderer
Returns:
true if numers are shown by the numbers
setShowNumbers
public void setShowNumbers(boolean showNumbers)
Indicate whether numbering should exist for the default cell renderer
Parameters:
showNumbers - indicate whether numbering should exist for the default cell
renderer
getSelectionTransparency
public int getSelectionTransparency()
Inidicates whether the default list cell renderer will show numbers by default when
constructed
Parameters:
def - true to show numbers for all renderers created in the future
Method Detail
989
Inidicates whether the default list cell renderer will show numbers by default when
constructed
Returns:
true when showing numbers, false otherwise
getFocusComponent
public Component getFocusComponent(Component list)
Returns a component instance that is painted under the currently focused renderer
and is animated to provide smooth scrolling. When the selection moves, this
component is drawn above/bellow the list items - it is recommended to give this
component some level of transparency (see above code example). This method is
optional an implementation can choose to return null.
Specified by:
getFocusComponent in interface CellRenderer<T>
Parameters:
list - the parent list
Returns:
a component to use as focus
See Also:
Component.setSmoothScrolling(boolean)
isRightAlignNumbers
public boolean isRightAlignNumbers()
Returns:
the rightAlignNumbers
setRightAlignNumbers
public void setRightAlignNumbers(boolean rightAlignNumbers)
Parameters:
rightAlignNumbers
isAlwaysRenderSelection
public boolean isAlwaysRenderSelection()
Indicates that selection should always be rendered regardless of the status of the
shouldRenderSelection flag
Returns:
the alwaysRenderSelection
setAlwaysRenderSelection
public void setAlwaysRenderSelection(boolean alwaysRenderSelection)
Indicates that selection should always be rendered regardless of the status of the
shouldRenderSelection flag
Parameters:
alwaysRenderSelection - the alwaysRenderSelection to set
Method Detail
990
Class ContainerList
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.list.ContainerList
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
Deprecated.
the performance of ContainerList is worse than the performance of List or Container. The
API/behaviors are problematic and we don't think its the right choice for any project. It is our
recommendation that you use Container, InfiniteContainer etc.
public class
extends Container
This is a "list component" implemented as a container with a layout manager which provides some of
the ui advantages of a Container and some of a list while pulling out some of the drawbacks of both.
This container uses the model/renderer approach for populating itself, adding/removing entries will
probably break it. It still provides most of the large size advantages a list offers since the components
within it are very simple and don't contain any actual state other than layout information. The big
advantage with this class is the ability to leverage elaborate CodenameOne layouts such as Grid,
Table & flow layout to provide other ways of rendering the content of a list model.
Field Summary
Constructor Summary
Constructor and Description
ContainerList()
Deprecated.
Default constructor
ContainerList(Layout l, ListModel m)
Deprecated.
Constructs a container list with the given model and layout
ContainerList(ListModel m)
Deprecated.
Constructs a container list with the given model
Method Summary
Modifier and
Type
void
Deprecated.
Allows binding a listener to user selection actions
deinitialize()
Class ContainerList
991
protected
void
Deprecated.
Invoked to indicate that the component initialization is being reversed since the compon
the container hierarchy.
fireActionEvent(ActionEvent evt)
Deprecated.
Triggers the event to the listeners
getActionListeners()
Vector
Deprecated.
use getListeners instead
getDragRegionStatus(int x, int y)
protected
int
Deprecated.
Indicates if the section within the X/Y area is a "drag region" where we expect people to
case we can instantly start dragging making perceived performance faster.
getListeners()
Collection
Deprecated.
This method allows extracting the action listeners from the current list
getModel()
ListModel
Deprecated.
Returns the list model
getPropertyNames()
String[]
Deprecated.
A component may expose mutable property names for a UI designer to manipulate, this
usage internally by the GUI builder code
getPropertyTypeNames()
String[]
Deprecated.
This method is here to workaround an XMLVM array type bug where property types are
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],Lis
getPropertyTypes()
Class[]
Deprecated.
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
Deprecated.
Returns the current value of the property name, this method is used by the GUI builder
getRenderer()
CellRenderer
Deprecated.
The renderer used to draw the container list elements
getSelectedIndex()
int
Deprecated.
Returns the current selected offset in the list
getSelectedItem()
Object
Deprecated.
Returns the current/last selected item
getSelectedRect()
Rectangle
protected
void
Deprecated.
Returns the component bounds with absolute screen coordinates, for components that
selection behavior and are not containers (currently only List) this method allows return
selection itself which is useful for things such as the popup dialog and similar UI's that n
position of the selection externally
initComponent()
Deprecated.
Allows subclasses to bind functionality that relies on fully initialized and "ready for actio
removeActionListener(ActionListener l)
void
Deprecated.
Allows binding a listener to user selection actions
setModel(ListModel model)
void
Deprecated.
Set the model for the container list
setPropertyValue(String name, Object value)
String
Method Summary
Deprecated.
Sets a new value to the given property, returns an error message if failed and null if suc
992
Deprecated.
The renderer used to draw the container list elements
void
setSelectedIndex(int index)
Deprecated.
Sets the current selected offset in the list, by default this implementation will scroll the li
selection is outside of the screen
void
993
Constructor Detail
ContainerList
public ContainerList()
Deprecated.
Default constructor
ContainerList
public ContainerList(ListModel m)
Deprecated.
Constructs a container list with the given model
Parameters:
m - the model
ContainerList
public ContainerList(Layout l,
ListModel m)
Deprecated.
Constructs a container list with the given model and layout
Parameters:
l - layout manager
m - the model
Method Detail
setRenderer
public void setRenderer(CellRenderer r)
Deprecated.
The renderer used to draw the container list elements
Parameters:
r - renderer instance
getRenderer
public CellRenderer getRenderer()
Deprecated.
The renderer used to draw the container list elements
getModel
public ListModel getModel()
Deprecated.
Returns the list model
Returns:
the list model
994
Deprecated.
Allows binding a listener to user selection actions
Parameters:
l - the action listener to be added
getActionListeners
public Vector getActionListeners()
Deprecated.
This method allows extracting the action listeners from the current list
Returns:
Collection containing the action listeners on the list
removeActionListener
public void removeActionListener(ActionListener l)
Deprecated.
Allows binding a listener to user selection actions
Parameters:
l - the action listener to be removed
initComponent
protected void initComponent()
Deprecated.
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
deinitialize
protected void deinitialize()
Deprecated.
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
setModel
public void setModel(ListModel model)
Deprecated.
Set the model for the container list
Parameters:
model - a model class that is mapped into the internal components
getSelectedItem
public Object getSelectedItem()
Deprecated.
Returns the current/last selected item
Returns:
Method Detail
995
Deprecated.
Returns the current selected offset in the list
Returns:
the current selected offset in the list
setSelectedIndex
public void setSelectedIndex(int index)
Deprecated.
Sets the current selected offset in the list, by default this implementation will scroll the
list to the selection if the selection is outside of the screen
Parameters:
index - the current selected offset in the list
fireActionEvent
protected void fireActionEvent(ActionEvent evt)
Deprecated.
Triggers the event to the listeners
Parameters:
evt - the event to fire
getPropertyNames
public String[] getPropertyNames()
Deprecated.
A component may expose mutable property names for a UI designer to manipulate,
this API is designed for usage internally by the GUI builder code
Overrides:
getPropertyNames in class Component
Returns:
the property names allowing mutation
getPropertyTypes
public Class[] getPropertyTypes()
Deprecated.
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
Deprecated.
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Deprecated.
Returns the current value of the property name, this method is used by the GUI
builder
Method Detail
996
in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Deprecated.
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
getSelectedRect
public Rectangle getSelectedRect()
Deprecated.
Description copied from class: Component
Returns the component bounds with absolute screen coordinates, for components
that include an internal selection behavior and are not containers (currently only List)
this method allows returning the position of the selection itself which is useful for
things such as the popup dialog and similar UI's that need to reference the position of
the selection externally
Overrides:
getSelectedRect in class Component
Returns:
the bounds of the component with absolute screen coordinates
getDragRegionStatus
protected int getDragRegionStatus(int x,
int y)
Deprecated.
Indicates if the section within the X/Y area is a "drag region" where we expect people
to drag or press in which case we can instantly start dragging making perceived
performance faster. This is invoked by the implementation code to optimize drag start
behavior
Overrides:
getDragRegionStatus in class Component
Parameters:
x - x location for the touch
y - y location for the touch
Returns:
one of the DRAG_REGION_* values
Method Detail
997
Interface CellRenderer<T>
All Known Implementing Classes:
DefaultListCellRenderer, GenericListCellRenderer
Deprecated.
this interface was added for ContainerList which is now deprecated. Use GenericListCellRenderer or
ListCellRenderer instead
public interface
This class is geared to replace the ListCellRenderer in the long run to provide a more generic
rendering API. A "rubber stamp" tool that allows us to extract a component (often the same
component instance for all invocations) that is initialized to the value of the current item extracted from
the model, this component is drawn on the list and discarded. No state of the component is kept and
the component is essentially discarded.
An instance of a renderer can be developed as such:
It is recommended that the component whose values are manipulated would not support features
such as repaint(). This is accomplished by overriding repaint in the subclass with an empty
implementation. This is advised for performance reasons, otherwise every change made to the
component might trigger a repaint that wouldn't do anything but still cost in terms of processing.
See Also:
GenericListCellRenderer, ListCellRenderer
Method Summary
Modifier and
Type
Component
Deprecated.
Returns a component instance that is already set to render "value".
getFocusComponent(Component list)
Component
Deprecated.
Returns a component instance that is painted under the currently focused
renderer and is animated to provide smooth scrolling.
Method Detail
Interface CellRenderer<T>
998
Deprecated.
Returns a component instance that is already set to render "value". While it is not a
requirement many renderes often derive from a component (such as a label) and
return "this". Notice that a null value for the value argument might be sent when
refreshing the theme of the list.
Parameters:
list - the list component
model - the model behind the render
value - the value to render
index - the index in the list
isSelected - whether the entry is selected
Returns:
a component to paint within the list
getFocusComponent
Component getFocusComponent(Component list)
Deprecated.
Returns a component instance that is painted under the currently focused renderer
and is animated to provide smooth scrolling. When the selection moves, this
component is drawn above/bellow the list items - it is recommended to give this
component some level of transparency (see above code example). This method is
optional an implementation can choose to return null.
Parameters:
list - the parent list
Returns:
a component to use as focus
See Also:
Component.setSmoothScrolling(boolean)
Method Detail
999
Class UnitValue
java.lang.Object
com.codename1.ui.layouts.mig.UnitValue
Field Summary
Modifier and Type
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
Class UnitValue
1000
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
Constructor Summary
Constructor and Description
UnitValue(float value)
UnitValue(float value, int unit, String createString)
Method Summary
Modifier and Type
static void
String
Adds a global unit converter that can convert from some unit to pixels.
getConstraintString()
static int
Deprecated.
Use PlatformDefaults.getDefaultHorizontalUnit() and
PlatformDefaults.getDefaultVerticalUnit() instead.
static
UnitConverter[]
getGlobalUnitConverters()
int
getOperation()
int
Field Summary
UnitValue[]
getSubUnits()
int
getUnit()
String
getUnitString()
float
getValue()
1001
int
boolean
static boolean
isHorizontal()
removeGlobalUnitConverter(UnitConverter unit)
static void
Deprecated.
Use PlatformDefaults.setDefaultHorizontalUnit(int) and
PlatformDefaults.setDefaultVerticalUnit(int) instead.
toString()
String
Field Detail
STATIC
public static final int STATIC
Method Summary
1002
Field Detail
1003
Field Detail
1004
Field Detail
1005
Detail
UnitValue
public UnitValue(float value)
UnitValue
public UnitValue(float value,
int unit,
String createString)
Method Detail
getPixels
public final int getPixels(float refValue,
ContainerWrapper parent,
ComponentWrapper comp)
getUnit
public final int getUnit()
getUnitString
public final String getUnitString()
getOperation
public final int getOperation()
getValue
public final float getValue()
isHorizontal
public final boolean isHorizontal()
Constructor Detail
1006
Adds a global unit converter that can convert from some unit to pixels.
This converter will be asked before the platform converter so the values for it (e.g.
"related" and "unrelated") can be overridden. It is however not possible to override
the built in ones (e.g. "mm", "pixel" or "lp").
Parameters:
conv - The converter. Not null.
removeGlobalUnitConverter
public static boolean removeGlobalUnitConverter(UnitConverter unit)
Method Detail
1007
Returns the global converters currently registered. The platform converter will not be
in this list.
Returns:
The converters. Never null.
getDefaultUnit
public static int getDefaultUnit()
Method Detail
1008
Class UnitConverter
java.lang.Object
com.codename1.ui.layouts.mig.UnitConverter
Field Summary
Modifier and
Type
static int
Value to return if this converter can not handle the unit sent in as an
argument to the convert method.
Constructor Summary
Constructor and Description
UnitConverter()
Method Summary
Modifier and
Type
Field Detail
UNABLE
public static final int UNABLE
Value to return if this converter can not handle the unit sent in as an argument to the
convert method.
See Also:
Constant Field Values
Constructor Detail
UnitConverter
public UnitConverter()
Class UnitConverter
1009
Detail
convertToPixels
public abstract int convertToPixels(float value,
String unit,
boolean isHor,
float refValue,
ContainerWrapper parent,
ComponentWrapper comp)
Method Detail
1010
Class PlatformDefaults
java.lang.Object
com.codename1.ui.layouts.mig.PlatformDefaults
Field Summary
Modifier and
Type
static int
I value indicating that the size of the font for the container of the component
will be used as a base for calculating the logical pixel size.
BASE_REAL_PIXEL
static int
I value indicating that the size of a logical pixel should always be a real pixel
and thus no compensation will be made.
BASE_SCALE_FACTOR
static int
I value indicating that the screen DPI will be used as a base for calculating
the logical pixel size.
static int
GNOME
static int
MAC_OSX
static
String
static int
VISUAL_PADDING_PROPERTY
Method Summary
Modifier and Type
static String
static int
static int
static int
static boolean
static int
static int[]
static UnitValue
static
InCellGapProvider
static BoundSize
Class PlatformDefaults
Returns the order for the typical buttons in a standard button bar.
getCurrentPlatform()
Returns the current gap provider or null if none is set and "related"
should always be used.
getGridGapX()
1011
static Float
The forced scale factor that all screen relative units (e.g.
getLabelAlignPercentage()
static float
static int
static UnitValue
static int
static UnitValue
static int
static int
static UnitValue
static UnitValue
static Float
The forced scale factor that all screen relative units (e.g.
invalidate()
void
static void
static void
static void
static void
static void
static void
static void
Sets the order for the typical buttons in a standard button bar.
setDefaultDPI(Integer dpi)
setGapProvider(InCellGapProvider provider)
Sets the current gap provider or null if none is set
and "related"
Method Summary
setGridCellGap(UnitValue x, UnitValue y)
The forced scale factor that all screen relative units (e.g.
setIndentGap(UnitValue x, UnitValue y)
1012
setParagraphGap(UnitValue x, UnitValue y)
The forced scale factor that all screen relative units (e.g.
Field Detail
VISUAL_PADDING_PROPERTY
public static String VISUAL_PADDING_PROPERTY
Property to use in LAF settings and as JComponent client property to specify the
visual padding.
WINDOWS_XP
public static final int WINDOWS_XP
See Also:
Constant Field Values
MAC_OSX
public static final int MAC_OSX
See Also:
Constant Field Values
GNOME
public static final int GNOME
See Also:
Constant Field Values
BASE_FONT_SIZE
public static final int BASE_FONT_SIZE
I value indicating that the size of the font for the container of the component will be
used as a base for calculating the logical pixel size. This is much as how Windows
calculated DLU (dialog units).
See Also:
net.miginfocom.layout.UnitValue#LPX,
net.miginfocom.layout.UnitValue#LPY, setLogicalPixelBase(int),
Constant Field Values
1013
I value indicating that the screen DPI will be used as a base for calculating the logical
pixel size.
This is the default value.
See Also:
net.miginfocom.layout.UnitValue#LPX,
net.miginfocom.layout.UnitValue#LPY, setLogicalPixelBase(int),
setVerticalScaleFactor(Float), setHorizontalScaleFactor(Float),
I value indicating that the size of a logical pixel should always be a real pixel and thus
no compensation will be made.
See Also:
net.miginfocom.layout.UnitValue#LPX,
net.miginfocom.layout.UnitValue#LPY, setLogicalPixelBase(int),
Constant Field Values
Method Detail
getCurrentPlatform
public static int getCurrentPlatform()
getDefaultVisualPadding
public static int[] getDefaultVisualPadding(String key)
Field Detail
1014
getPlatformDPI
public static int getPlatformDPI(int plaf)
getPlatform
public static int getPlatform()
or PlatformDefaults.MAC_OSX
getDefaultDPI
public static int getDefaultDPI()
setDefaultDPI
public static void setDefaultDPI(Integer dpi)
Sets the default platform DPI. Normally this is set in the setPlatform(int) for the
different platforms but it can be tweaked here. For instance SWT on Mac does this.
Note that this is not the actual current DPI, but the base DPI for the toolkit.
Parameters:
dpi - The base DPI. If null the default DPI is reset to the platform base DPI.
getHorizontalScaleFactor
public static Float getHorizontalScaleFactor()
The forced scale factor that all screen relative units (e.g. millimeters, inches and
logical pixels) will be multiplied with. If null this will default to a scale that will scale
the current screen to the default screen resolution (72 DPI for Mac and 92 DPI for
Windows).
Returns:
The forced scale or null for default scaling.
See Also:
getHorizontalScaleFactor(), ComponentWrapper.getHorizontalScreenDPI()
setHorizontalScaleFactor
public static void setHorizontalScaleFactor(Float f)
The forced scale factor that all screen relative units (e.g. millimeters, inches and
logical pixels) will be multiplied with. If null this will default to a scale that will scale
the current screen to the default screen resolution (72 DPI for Mac and 92 DPI for
Windows).
Parameters:
f - The forced scale or null for default scaling.
See Also:
getHorizontalScaleFactor(), ComponentWrapper.getHorizontalScreenDPI()
getVerticalScaleFactor
public static Float getVerticalScaleFactor()
The forced scale factor that all screen relative units (e.g. millimeters, inches and
logical pixels) will be multiplied with. If null this will default to a scale that will scale
the current screen to the default screen resolution (72 DPI for Mac and 92 DPI for
Windows).
Returns:
The forced scale or null for default scaling.
See Also:
getHorizontalScaleFactor(), ComponentWrapper.getVerticalScreenDPI()
setVerticalScaleFactor
public static void setVerticalScaleFactor(Float f)
Method Detail
1015
Method Detail
1016
Sets gap between two cells in the grid. Note that this is not a gap between
component IN a cell, that has to be set on the component constraints. The value will
be the min and preferred size of the gap.
Parameters:
x - The value that will be transformed to pixels. If null the current value will
not change.
y - The value that will be transformed to pixels. If null the current value will
not change.
setMinimumButtonWidth
public static void setMinimumButtonWidth(UnitValue width)
Returns the recommended minimum button width depending on the current set
platform.
Returns:
The recommended minimum button width depending on the current set
platform.
getUnitValueX
public static UnitValue getUnitValueX(String unit)
Returns the unit value associated with the unit. (E.i. "related" or "indent"). Must be
lower case.
Parameters:
unit - The unit string.
Returns:
The unit value associated with the unit. null for unrecognized units.
getUnitValueY
public static UnitValue getUnitValueY(String unit)
Returns the unit value associated with the unit. (E.i. "related" or "indent"). Must be
lower case.
Parameters:
unit - The unit string.
Returns:
The unit value associated with the unit. null for unrecognized units.
setUnitValue
public static void setUnitValue(String[] unitStrings,
UnitValue x,
UnitValue y)
Sets the unit value associated with a unit string. This may be used to store values for
new unit strings or modify old. Note that if a built in unit (such as "related") is modified
all versions of it must be set (I.e. "r", "rel" and "related"). The build in values will be
reset to the default ones if the platform is re-set.
Parameters:
unitStrings - The unit strings. E.g. "mu", "myunit". Will be converted to lower
case and trimmed. Not null.
x - The value for the horizontal dimension. If null the value is not changed.
Method Detail
1017
Returns the order for the typical buttons in a standard button bar. It is one letter per
button type.
Returns:
The button order.
See Also:
setButtonOrder(String)
setButtonOrder
public static void setButtonOrder(String order)
Sets the order for the typical buttons in a standard button bar. It is one letter per
button type.
Letter in upper case will get the minimum button width that the
getMinimumButtonWidth() specifies and letters in lower case will get the width the
current look&feel specifies.
Gaps will never be added to before the first component or after the last component.
However, '+' (push) will be applied before and after as well, but with a minimum size
of 0 if first/last so there will not be a gap before or after.
If gaps are explicitly set on buttons they will never be reduced, but they may be
increased.
These are the characters that can be used:
'L' - Buttons with this style tag will staticall end up on the left end of the bar.
'R' - Buttons with this style tag will staticall end up on the right end of the bar.
'H' - A tag for the "help" button that normally is supposed to be on the right.
'E' - A tag for the "help2" button that normally is supposed to be on the left.
'Y' - A tag for the "yes" button.
'N' - A tag for the "no" button.
'X' - A tag for the "next >" or "forward >" button.
'B' - A tag for the "< back>" or "< previous" button.
'I' - A tag for the "finish".
'A' - A tag for the "apply" button.
'C' - A tag for the "cancel" or "close" button.
'O' - A tag for the "ok" or "done" button.
'U' - All Uncategorized, Other, or "Unknown" buttons. Tag will be "other".
'+' - A glue push gap that will take as much space as it can and at least an
"unrelated" gap. (Platform dependant)
'_' - (underscore) An "unrelated" gap. (Platform dependant)
Even though the style tags are normally applied to buttons this works with all
components.
The normal style for MAC OS X is "L_HE+U+FBI_NYCOA_R", for Windows is
"L_E+U+FBI_YNOCAH_R", and for GNOME is "L_HE+UNYACBXIO_R".
Parameters:
order
getGridGapX
public static BoundSize getGridGapX()
Returns the platform recommended inter-cell gap in the horizontal (x) dimension..
Returns:
The platform recommended inter-cell gap in the horizontal (x) dimension..
Method Detail
1018
Returns the platform recommended inter-cell gap in the vertical (x) dimension..
Returns:
The platform recommended inter-cell gap in the vertical (x) dimension..
getDialogInsets
public static UnitValue getDialogInsets(int side)
top,
left,
bottom,
right)
Sets the default insets for a dialog. Values that are null will not be changed.
Parameters:
top - The top inset. May be null.
left - The left inset. May be null.
bottom - The bottom inset. May be null.
right - The right inset. May be null.
getPanelInsets
public static UnitValue getPanelInsets(int side)
top,
left,
bottom,
right)
Sets the default insets for a dialog. Values that are null will not be changed.
Parameters:
top - The top inset. May be null.
left - The left inset. May be null.
bottom - The bottom inset. May be null.
right - The right inset. May be null.
getLabelAlignPercentage
public static float getLabelAlignPercentage()
Returns the percentage used for alignment for labels (0 is left, 50 is center and 100 is
right).
Returns:
The percentage used for alignment for labels
getGapProvider
public static InCellGapProvider getGapProvider()
Returns the current gap provider or null if none is set and "related" should always be
used.
Returns:
The current gap provider or null if none is set and "related" should always be
used.
Method Detail
1019
Sets the current gap provider or null if none is set and "related" should always be
used.
Parameters:
provider - The current gap provider or null if none is set and "related"
should always be used.
getModCount
public static int getModCount()
Returns how many times the defaults has been changed. This can be used as a light
weight check to see if layout caches needs to be refreshed.
Returns:
How many times the defaults has been changed.
invalidate
public void invalidate()
Returns the current default unit. The default unit is the unit used if no unit is set. E.g.
"width 10".
Returns:
The current default unit.
See Also:
UnitValue.PIXEL, UnitValue.LPX
setDefaultHorizontalUnit
public static void setDefaultHorizontalUnit(int unit)
Sets the default unit. The default unit is the unit used if no unit is set. E.g. "width 10".
Parameters:
unit - The new default unit.
See Also:
UnitValue.PIXEL, UnitValue.LPX
getDefaultVerticalUnit
public static int getDefaultVerticalUnit()
Returns the current default unit. The default unit is the unit used if no unit is set. E.g.
"width 10".
Returns:
The current default unit.
See Also:
UnitValue.PIXEL, UnitValue.LPY
setDefaultVerticalUnit
public static void setDefaultVerticalUnit(int unit)
Sets the default unit. The default unit is the unit used if no unit is set. E.g. "width 10".
Parameters:
unit - The new default unit.
See Also:
UnitValue.PIXEL, UnitValue.LPY
getDefaultRowAlignmentBaseline
public static boolean getDefaultRowAlignmentBaseline()
The default alignment for rows. Pre v3.5 this was false but now it is true.
Returns:
The current value. Default is true.
Method Detail
1020
The default alignment for rows. Pre v3.5 this was false but now it is true.
Parameters:
b - The new value. Default is true from v3.5.
Since:
3.5
Method Detail
1021
Class MigLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.layouts.mig.MigLayout
Deprecated.
this is currently an experimental integration and has known bugs do not rely on this layout for
production
public final class
extends Layout
Constructor Summary
Constructor and Description
MigLayout()
Deprecated.
Constructor with no constraints.
MigLayout(LC layoutConstraints)
Deprecated.
Constructor.
MigLayout(LC layoutConstraints, AC colConstraints)
Deprecated.
Constructor.
MigLayout(LC layoutConstraints, AC colConstraints, AC rowConstraints)
Deprecated.
Constructor.
MigLayout(String layoutConstraints)
Deprecated.
Constructor.
MigLayout(String layoutConstraints, String colConstraints)
Deprecated.
Constructor.
MigLayout(String layoutConstraints, String colConstraints, String rowConstraints)
Deprecated.
Constructor.
Method Summary
Modifier and Type
void
Deprecated.
Adds the callback function that will be called at different stages of
the layout cylce.
addLayoutComponent(Component comp, Object constraints)
void
Deprecated.
void
Deprecated.
Class MigLayout
1022
Deprecated.
getColumnConstraints()
Object
Deprecated.
Returns the column layout constraints either as a String or
net.miginfocom.layout.AC.
getComponentConstraint(Component comp)
Object
Deprecated.
Returns the optional component constraint
getComponentConstraints(Component comp)
Object
Deprecated.
Returns the component constraints as a String representation.
getConstraintMap()
Map<Component,Object>
Deprecated.
Returns a shallow copy of the constraints map.
getLayoutAlignmentX(Container parent)
float
Deprecated.
getLayoutAlignmentY(Container parent)
float
Deprecated.
getLayoutConstraints()
Object
Deprecated.
Returns layout constraints either as a String or
net.miginfocom.layout.LC depending what was sent in to the
constructor or set with setLayoutConstraints(Object).
getPreferredSize(Container parent)
Dimension
Deprecated.
Returns the container preferred size
getRowConstraints()
Object
Deprecated.
Returns the row layout constraints either as a String or
net.miginfocom.layout.AC.
invalidateLayout(Container target)
void
Deprecated.
isConstraintTracking()
boolean
Deprecated.
If this method returns true, the addLayoutComponent method will
be called when replacing a layout for every component within the
container
isManagingComponent(Component c)
boolean
Deprecated.
Returns if this layout manager is currently managing this
component.
layoutContainer(Container parent)
void
Deprecated.
Layout the given parent container children
maximumLayoutSize(Container parent)
Dimension
Deprecated.
minimumLayoutSize(Container parent)
Dimension
Deprecated.
preferredLayoutSize(Container parent)
Dimension
Method Summary
Deprecated.
1023
Deprecated.
Removes the callback if it exists.
void
removeLayoutComponent(Component comp)
Deprecated.
Removes the component from the layout this operation is only
useful if the layout maintains references to components within it
void
setColumnConstraints(Object constr)
Deprecated.
Sets the column layout constraints for the layout manager
instance as a String.
void
Deprecated.
Sets the component constraint for the component that already
must be handled by this layout manager.
void
setConstraintMap(Map<Component,Object> map)
Deprecated.
Sets the constraints map.
void
setLayoutConstraints(Object constr)
Deprecated.
Sets the layout constraints for the layout manager instance as a
String.
void
setRowConstraints(Object constr)
Deprecated.
Sets the row layout constraints for the layout manager instance as
a String.
void
Constructor Detail
MigLayout
public MigLayout()
Deprecated.
Constructor with no constraints.
MigLayout
public MigLayout(String layoutConstraints)
Deprecated.
Constructor.
Parameters:
layoutConstraints
be treated as "".
MigLayout
public MigLayout(String layoutConstraints,
String colConstraints)
Deprecated.
Constructor.
Parameters:
layoutConstraints
be treated as "".
1024
treated as "".
MigLayout
public MigLayout(String layoutConstraints,
String colConstraints,
String rowConstraints)
Deprecated.
Constructor.
Parameters:
layoutConstraints
be treated as "".
colConstraints
treated as "".
rowConstraints
- The constraints for the rows in the grid. null will be treated
as "".
MigLayout
public MigLayout(LC layoutConstraints)
Deprecated.
Constructor.
Parameters:
- The constraints that concern the whole layout. null will
be treated as an empty constraint.
MigLayout
layoutConstraints
Deprecated.
Constructor.
Parameters:
- The constraints that concern the whole layout. null will
be treated as an empty constraint.
colConstraints - The constraints for the columns in the grid. null will be
treated as an empty constraint.
MigLayout
layoutConstraints
Deprecated.
Constructor.
Parameters:
- The constraints that concern the whole layout. null will
be treated as an empty constraint.
colConstraints - The constraints for the columns in the grid. null will be
treated as an empty constraint.
rowConstraints - The constraints for the rows in the grid. null will be treated
as an empty constraint.
layoutConstraints
Method Detail
getLayoutConstraints
public Object getLayoutConstraints()
Deprecated.
Returns layout constraints either as a String or net.miginfocom.layout.LC
depending what was sent in to the constructor or set with
setLayoutConstraints(Object).
Returns:
Constructor Detail
1025
Deprecated.
Sets the layout constraints for the layout manager instance as a String.
See the class JavaDocs for information on how this string is formatted.
Parameters:
- The layout constraints as a String pr net.miginfocom.layout.LC
representation. null is converted to "" for storage.
constr
Throws:
RuntimeException
getColumnConstraints
public Object getColumnConstraints()
Deprecated.
Returns the column layout constraints either as a String or
net.miginfocom.layout.AC.
Returns:
The column constraints either as a String or net.miginfocom.layout.AC
depending what was sent in to the constructor or set with
setColumnConstraints(Object). Never null.
setColumnConstraints
public void setColumnConstraints(Object constr)
Deprecated.
Sets the column layout constraints for the layout manager instance as a String.
See the class JavaDocs for information on how this string is formatted.
Parameters:
constr - The column layout constraints as a String or
net.miginfocom.layout.AC representation. null is converted
to "" for
storage.
Throws:
RuntimeException
getRowConstraints
public Object getRowConstraints()
Deprecated.
Returns the row layout constraints either as a String or net.miginfocom.layout.AC.
Returns:
The row constraints either as a String or net.miginfocom.layout.AC
depending what was sent in to the constructor or set with
setRowConstraints(Object). Never null.
setRowConstraints
public void setRowConstraints(Object constr)
Deprecated.
Sets the row layout constraints for the layout manager instance as a String.
See the class JavaDocs for information on how this string is formatted.
Parameters:
- The row layout constraints as a String or net.miginfocom.layout.AC
representation. null is converted to "" for storage.
constr
Throws:
Method Detail
1026
getConstraintMap
public Map<Component,Object> getConstraintMap()
Deprecated.
Returns a shallow copy of the constraints map.
Returns:
A shallow copy of the constraints map. Never null.
setConstraintMap
public void setConstraintMap(Map<Component,Object> map)
Deprecated.
Sets the constraints map.
Parameters:
map - The map. Will be copied.
getComponentConstraints
public Object getComponentConstraints(Component comp)
Deprecated.
Returns the component constraints as a String representation. This string is the exact
string as set with #setComponentConstraints(java.awt.Component, Object) or set
when adding the component to the parent component.
See the class JavaDocs for information on how this string is formatted.
Parameters:
comp - The component to return the constraints for.
Returns:
The component constraints as a String representation or null if the
component is not registered with this layout manager. The returned values is
either a String or a net.miginfocom.layout.CC depending on what constraint
was sent in when the component was added. May be null.
setComponentConstraints
public void setComponentConstraints(Component comp,
Object constr)
Deprecated.
Sets the component constraint for the component that already must be handled by
this layout manager.
See the class JavaDocs for information on how this string is formatted.
Parameters:
constr - The component constraints as a String or
net.miginfocom.layout.CC. null is ok.
comp - The component to set the constraints for.
Throws:
RuntimeException - if the constraint was not valid.
IllegalArgumentException - If the component is not
isManagingComponent
public boolean isManagingComponent(Component c)
Deprecated.
Returns if this layout manager is currently managing this component.
Parameters:
c - The component to check. If null then false will be returned.
Returns:
If this layout manager is currently managing this component.
Method Detail
1027
Deprecated.
Adds the callback function that will be called at different stages of the layout cylce.
Parameters:
callback - The callback. Not null.
removeLayoutCallback
public void removeLayoutCallback(LayoutCallback callback)
Deprecated.
Removes the callback if it exists.
Parameters:
callback - The callback. May be null.
layoutContainer
public void layoutContainer(Container parent)
Deprecated.
Description copied from class: Layout
Layout the given parent container children
Specified by:
layoutContainer in class Layout
Parameters:
parent - the given parent container
findType
public static <E> E findType(Class<E> clazz,
Component comp)
Deprecated.
minimumLayoutSize
public Dimension minimumLayoutSize(Container parent)
Deprecated.
preferredLayoutSize
public Dimension preferredLayoutSize(Container parent)
Deprecated.
maximumLayoutSize
public Dimension maximumLayoutSize(Container parent)
Deprecated.
getLayoutAlignmentX
public float getLayoutAlignmentX(Container parent)
Deprecated.
getLayoutAlignmentY
public float getLayoutAlignmentY(Container parent)
Deprecated.
addLayoutComponent
public void addLayoutComponent(Object value,
Component comp,
Container c)
Deprecated.
Description copied from class: Layout
Some layouts can optionally track the addition of elements with meta-data that allows
the user to "hint" on object positioning.
Method Detail
1028
in class Layout
Parameters:
value - optional meta data information, like
comp - the added component to the layout
c - the parent container
alignment orientation
addLayoutComponent
public void addLayoutComponent(Component comp,
Object constraints)
Deprecated.
isConstraintTracking
public boolean isConstraintTracking()
Deprecated.
Description copied from class: Layout
If this method returns true, the addLayoutComponent method will be called when
replacing a layout for every component within the container
Overrides:
isConstraintTracking in class Layout
Returns:
false by default
getComponentConstraint
public Object getComponentConstraint(Component comp)
Deprecated.
Description copied from class: Layout
Returns the optional component constraint
Overrides:
getComponentConstraint in class Layout
Parameters:
comp - the component whose constraint should be returned
Returns:
the optional component constraint
removeLayoutComponent
public void removeLayoutComponent(Component comp)
Deprecated.
Description copied from class: Layout
Removes the component from the layout this operation is only useful if the layout
maintains references to components within it
Overrides:
removeLayoutComponent in class Layout
Parameters:
comp - the removed component from layout
invalidateLayout
public void invalidateLayout(Container target)
Deprecated.
getPreferredSize
public Dimension getPreferredSize(Container parent)
Deprecated.
Description copied from class: Layout
Returns the container preferred size
Specified by:
getPreferredSize in class Layout
Parameters:
parent - the parent container
Returns:
the container preferred size
Method Detail
1029
Class LinkHandler
java.lang.Object
com.codename1.ui.layouts.mig.LinkHandler
Field Summary
Modifier and Type Field and Description
static int
HEIGHT
static int
WIDTH
static int
static int
X2
static int
static int
Y2
Method Summary
Modifier and
Type
static boolean
static void
This method clear any weak references right away instead of waiting for
the GC.
static Integer
static boolean
Field Detail
X
public static final int X
See Also:
Constant Field Values
Y
public static final int Y
See Also:
Constant Field Values
Class LinkHandler
1030
See Also:
Constant Field Values
HEIGHT
public static final int HEIGHT
See Also:
Constant Field Values
X2
public static final int X2
See Also:
Constant Field Values
Y2
public static final int Y2
See Also:
Constant Field Values
Method Detail
getValue
public static Integer getValue(Object layout,
String key,
int type)
setBounds
public static boolean setBounds(Object layout,
String key,
int x,
int y,
int width,
int height)
This method clear any weak references right away instead of waiting for the GC. This
might be advantageous if lots of layout are created and disposed of quickly to keep
memory consumption down.
Since:
3.7.4
clearBounds
public static boolean clearBounds(Object layout,
String key)
Field Detail
1031
Class LayoutUtil
java.lang.Object
com.codename1.ui.layouts.mig.LayoutUtil
Field Summary
Modifier and Type
static boolean
HAS_BEANS
static int
HORIZONTAL
static int
INF
static int
MAX
static int
MIN
static int
PREF
static int
VERTICAL
Method Summary
Modifier and
Type
static int
static int
static Object
static int
static String
static boolean
static boolean
static void
static void
static void
static void
Method Detail
1032
Field Detail
INF
public static final int INF
A substitute value for aa really large value. Integer.MAX_VALUE is not used since
that means a lot of defensive code for potential overflow must exist in many places.
This value is large enough for being unreasonable yet it is hard to overflow.
See Also:
Constant Field Values
MIN
public static final int MIN
See Also:
Constant Field Values
PREF
public static final int PREF
See Also:
Constant Field Values
MAX
public static final int MAX
See Also:
Constant Field Values
HORIZONTAL
public static final int HORIZONTAL
See Also:
Constant Field Values
VERTICAL
public static final int VERTICAL
See Also:
Constant Field Values
HAS_BEANS
public static final boolean HAS_BEANS
Method Detail
getVersion
public static String getVersion()
If global debug should be on or off. If > 0 then debug is turned on for all MigLayout
instances.
1033
setGlobalDebugMillis
public static void setGlobalDebugMillis(int millis)
If global debug should be on or off. If > 0 then debug is turned on for all MigLayout
instances.
Note! This is a passive value and will be read by panels when the needed, which is
normally when they repaint/layout.
Parameters:
- The new debug milliseconds. 0 turns of global debug and leaves
debug up to every individual panel.
See Also:
millis
LC.setDebugMillis(int)
setDesignTime
public static void setDesignTime(ContainerWrapper cw,
boolean b)
Method Detail
1034
Returns if left-to-right orientation is used. If not set explicitly in the layout constraints
the Locale of the parent is used.
Parameters:
lc - The constraint if there is one. Can be null.
container - The parent that may be used to get the left-to-right if ffc does not
specify this.
Returns:
If left-to-right orientation is currently used.
setSerializedObject
public static void setSerializedObject(Object caller,
Object o)
Returns the serialized object that are associated with caller. It also removes it from
the list.
Parameters:
caller - The original creator of the object.
Returns:
The object.
Method Detail
1035
Class LayoutCallback
java.lang.Object
com.codename1.ui.layouts.mig.LayoutCallback
A class to extend if you want to provide more control over where a component is placed or the size of
it.
Note! Returned arrays from this class will never be altered. This means that caching of arrays in these
methods is OK.
Constructor Summary
Constructor and Description
LayoutCallback()
Method Summary
Modifier and
Type
void
UnitValue[]
getPosition(ComponentWrapper comp)
BoundSize[]
Constructor Detail
LayoutCallback
public LayoutCallback()
Method Detail
getPosition
public UnitValue[] getPosition(ComponentWrapper comp)
Class LayoutCallback
1036
getSize
public BoundSize[] getSize(ComponentWrapper comp)
Returns a size similar to the "width" and "height" in the component constraint.
Parameters:
comp - The component wrapper that holds the actual component
(JComponent is Swing and Control in SWT). Should not be altered.
Returns:
The [width, height] as explained in the documentation for "width" and
"height". If null is returned nothing is done and this is the default.
See Also:
net.miginfocom.layout.BoundSize,
net.miginfocom.layout.ConstraintParser#parseBoundSize(String,
boolean, boolean)
correctBounds
public void correctBounds(ComponentWrapper comp)
A last minute change of the bounds. The bound for the layout cycle has been set and
you can correct there after any set of rules you like.
Parameters:
comp - The component wrapper that holds the actual component
(JComponent is Swing and Control in SWT).
Method Detail
1037
Class LC
java.lang.Object
com.codename1.ui.layouts.mig.LC
Constructor Summary
Constructor and Description
LC()
Empty constructor.
Method Summary
Modifier and
Type
LC
LC
Same functionality as
setAlignX(ConstraintParser.parseUnitValueOrAlign(unitValue, true))
only this method returns this for chaining multiple calls.
alignY(String align)
LC
Same functionality as
setAlignY(ConstraintParser.parseUnitValueOrAlign(align, false))
this method returns this for chaining multiple calls.
only
bottomToTop()
LC
LC
debug()
Calls debug(int)
LC
debug(int repaintMillis)
Same functionality as setDebugMillis(int repaintMillis)
returns this for chaining multiple calls.
fill()
LC
LC
LC
LC
LC
Class LC
1038
If the laid out components' bounds in total is less than the final size of the
container these align values will be used to align the components in the
parent.
getAlignY()
UnitValue
int
If the laid out components' bounds in total is less than the final size of the
container these align values will be used to align the components in the
parent.
getDebugMillis()
If > 0 the debug decorations
BoundSize
getGridGapX()
If non-null (null
BoundSize
getGridGapY()
If non-null (null
BoundSize
int
UnitValue[]
Boolean
BoundSize
Returns the "pack height" for the window that this container is located in.
getPackHeightAlign()
float
BoundSize
Returns the "pack width" for the window that this container is located in.
getPackWidthAlign()
float
BoundSize
int
LC
Returns after what cell the grid should always auto wrap.
gridGap(String gapx, String gapy)
LC
Same functionality as
setGridGapX(ConstraintParser.parseBoundSize(boundsSize, true, true))
only this method returns this for chaining multiple calls.
gridGapY(String boundsSize)
LC
Same functionality as
setGridGapY(ConstraintParser.parseBoundSize(boundsSize, true, false))
only this method returns this for chaining multiple calls.
height(String height)
LC
The height for the container as a min and/or preferred and/or maximum
height.
hideMode(int mode)
LC
LC
Method Summary
1039
boolean
If the layout should always claim the whole bounds of the laid out container
even if the preferred size is smaller.
isFillY()
boolean
boolean
If the layout should always claim the whole bounds of the laid out container
even if the preferred size is smaller.
isFlowX()
boolean
boolean
boolean
If the layout should go from the default top-to-bottom in the grid instead of the
optinal bottom-to-top.
isVisualPadding()
boolean
LC
maxHeight(String height)
LC
LC
LC
LC
LC
LC
LC
void
void
Method Summary
If the laid out components' bounds in total is less than the final size of the
container these align values will be used to align the components in the
parent.
setAlignY(UnitValue uv)
1040
setDebugMillis(int millis)
If > 0 the debug decorations will
setFillX(boolean b)
void
If the layout should always claim the whole bounds of the laid out container
even if the preferred size is smaller.
setFillY(boolean b)
void
void
If the layout should always claim the whole bounds of the laid out container
even if the preferred size is smaller.
setFlowX(boolean b)
void
setGridGapX(BoundSize x)
If non-null (null is default)
void
setGridGapY(BoundSize y)
If non-null (null is default)
void
void
void
void
Sets the minimum/preferred/maximum size for the container that this layout
constraint is set for.
setHideMode(int mode)
void
void
void
Sets the "pack height" for the window that this container is located in.
setPackHeightAlign(float align)
void
void
Sets the "pack width" for the window that this container is located in.
setPackWidthAlign(float align)
void
void
If the layout should go from the default top-to-bottom in the grid instead of the
optinal bottom-to-top.
setVisualPadding(boolean b)
void
void
void
LC
Sets the minimum/preferred/maximum size for the container that this layout
constraint is set for.
setWrapAfter(int count)
Sets after what cell the grid should always auto wrap.
topToBottom()
Method Summary
1041
LC
The width for the container as a min and/or preferred and/or maximum width.
wrap()
LC
wrapAfter(int count)
Same functionality as setWrapAfter(int)
LC
Constructor Detail
LC
public LC()
Empty constructor.
Method Detail
isNoCache
public boolean isNoCache()
If components have sizes or positions linked to the bounds of the parent in some way
(as for instance the "%" unit has) the cache must be turned off for the panel. If
components does not get the correct or expected size or position try to set this
property to true.
Returns:
true means no cache and slightly slower layout.
setNoCache
public void setNoCache(boolean b)
If components have sizes or positions linked to the bounds of the parent in some way
(as for instance the "%" unit has) the cache must be turned off for the panel. If
components does not get the correct or expected size or position try to set this
property to true.
Parameters:
b - true means no cache and slightly slower layout.
getAlignX
public final UnitValue getAlignX()
If the laid out components' bounds in total is less than the final size of the container
these align values will be used to align the components in the parent. null is default
and that means top/left alignment. The relative distances between the components
will not be affected by this property.
Returns:
The current alignment.
setAlignX
public final void setAlignX(UnitValue uv)
If the laid out components' bounds in total is less than the final size of the container
these align values will be used to align the components in the parent. null is default
and that means top/left alignment. The relative distances between the components
will not be affected by this property.
1042
to create the
getAlignY
public final UnitValue getAlignY()
If the laid out components' bounds in total is less than the final size of the container
these align values will be used to align the components in the parent. null is default
and that means top/left alignment. The relative distances between the components
will not be affected by this property.
Returns:
The current alignment.
setAlignY
public final void setAlignY(UnitValue uv)
If the laid out components' bounds in total is less than the final size of the container
these align values will be used to align the components in the parent. null is default
and that means top/left alignment. The relative distances between the components
will not be affected by this property.
Parameters:
uv - The new alignment. Use
ConstraintParser.parseAlignKeywords(String, boolean) to create the
UnitValue. May be null.
getDebugMillis
public final int getDebugMillis()
If > 0 the debug decorations will be repainted every millis. No debug information if
<= 0 (default).
Returns:
The current debug repaint interval.
setDebugMillis
public final void setDebugMillis(int millis)
If > 0 the debug decorations will be repainted every millis. No debug information if
<= 0 (default).
Parameters:
millis - The new debug repaint interval.
isFillX
public final boolean isFillX()
If the layout should always claim the whole bounds of the laid out container even if
the preferred size is smaller.
Returns:
true means fill. false is default.
setFillX
public final void setFillX(boolean b)
If the layout should always claim the whole bounds of the laid out container even if
the preferred size is smaller.
Parameters:
b - true means fill. false is default.
isFillY
public final boolean isFillY()
If the layout should always claim the whole bounds of the laid out container even if
the preferred size is smaller.
Returns:
true means fill. false is default.
Method Detail
1043
If the layout should always claim the whole bounds of the laid out container even if
the preferred size is smaller.
Parameters:
b - true means fill. false is default.
isFlowX
public final boolean isFlowX()
The default flow direction. Normally (which is true) this is horizontal and that means
that the "next" component will be put in the cell to the right (or to the left if left-to-right
is false).
Returns:
true is the default flow horizontally.
See Also:
setLeftToRight(Boolean)
setFlowX
public final void setFlowX(boolean b)
The default flow direction. Normally (which is true) this is horizontal and that means
that the "next" component will be put in the cell to the right (or to the left if left-to-right
is false).
Parameters:
b - true is the default flow horizontally.
See Also:
setLeftToRight(Boolean)
getGridGapX
public final BoundSize getGridGapX()
If non-null (null is default) these value will be used as the default gaps between the
columns in the grid.
Returns:
The default grid gap between columns in the grid. null if the platform default
is used.
setGridGapX
public final void setGridGapX(BoundSize x)
If non-null (null is default) these value will be used as the default gaps between the
columns in the grid.
Parameters:
x - The default grid gap between columns in the grid. If null the platform
default is used.
getGridGapY
public final BoundSize getGridGapY()
If non-null (null is default) these value will be used as the default gaps between the
rows in the grid.
Returns:
The default grid gap between rows in the grid. null if the platform default is
used.
setGridGapY
public final void setGridGapY(BoundSize y)
If non-null (null is default) these value will be used as the default gaps between the
rows in the grid.
Parameters:
y - The default grid gap between rows in the grid. If null the platform default
is used.
Method Detail
1044
The insets for the layed out panel. The insets will be an empty space around the
components in the panel. null values means that the default panel insets for the
platform is used. See
PlatformDefaults#setDialogInsets(net.miginfocom.layout.UnitValue,
net.miginfocom.layout.UnitValue, net.miginfocom.layout.UnitValue,
net.miginfocom.layout.UnitValue).
Returns:
The insets. Of length 4 (top, left, bottom, right) or null. The elements (1 to 4)
may be null. The array is a copy and can be used freely.
See Also:
net.miginfocom.layout.ConstraintParser#parseInsets(String, boolean)
setInsets
public final void setInsets(UnitValue[] ins)
The insets for the layed out panel. The insets will be an empty space around the
components in the panel. null values means that the default panel insets for the
platform is used. See
PlatformDefaults#setDialogInsets(net.miginfocom.layout.UnitValue,
net.miginfocom.layout.UnitValue, net.miginfocom.layout.UnitValue,
net.miginfocom.layout.UnitValue).
Parameters:
ins - The new insets. Must be of length 4 (top, left, bottom, right) or null. The
elements (1 to 4) may be null to use the platform default for that side. The
array is copied for storage.
See Also:
net.miginfocom.layout.ConstraintParser#parseInsets(String, boolean)
getLeftToRight
public final Boolean getLeftToRight()
Method Detail
1045
If the whole layout should be non grid based. It is the same as setting the "nogrid"
property on every row/column in the grid.
Returns:
true means not grid based. false is default.
setNoGrid
public final void setNoGrid(boolean b)
If the whole layout should be non grid based. It is the same as setting the "nogrid"
property on every row/column in the grid.
Parameters:
b - true means no grid. false is default.
isTopToBottom
public final boolean isTopToBottom()
If the layout should go from the default top-to-bottom in the grid instead of the optinal
bottom-to-top.
Returns:
true for the default top-to-bottom.
setTopToBottom
public final void setTopToBottom(boolean b)
If the layout should go from the default top-to-bottom in the grid instead of the optinal
bottom-to-top.
Parameters:
b - true for the default top-to-bottom.
isVisualPadding
public final boolean isVisualPadding()
If visual padding should be automatically used and compensated for by this layout
instance.
Returns:
true if visual padding.
setVisualPadding
public final void setVisualPadding(boolean b)
If visual padding should be automatically used and compensated for by this layout
instance.
Parameters:
b - true turns on visual padding.
getWrapAfter
public final int getWrapAfter()
Returns after what cell the grid should always auto wrap.
Returns:
After what cell the grid should always auto wrap. If 0 the number of
columns/rows in the net.miginfocom.layout.AC is used. LayoutUtil.INF is
used for no auto wrap.
Method Detail
1046
Sets after what cell the grid should always auto wrap.
Parameters:
count - After what cell the grid should always auto wrap. If 0 the number of
columns/rows in the net.miginfocom.layout.AC is used. LayoutUtil.INF is
used for no auto wrap.
getPackWidth
public final BoundSize getPackWidth()
Returns the "pack width" for the window that this container is located in. When the
size of this container changes the size of the window will be corrected to be within
this BoundsSize. It can be used to set the minimum and/or maximum size of the
window as well as the size window should optimally get. This optimal size is normally
its "preferred" size which is why "preferred" is the normal value to set here.
":push" can be appended to the bound size to only push the size bigger and never
shrink it if the preferred size gets smaller.
E.g. "pref", "100:pref", "pref:700", "300::700", "pref:push"
Returns:
The current value. Never null. Check if not set with .isUnset().
Since:
3.5
setPackWidth
public final void setPackWidth(BoundSize size)
Sets the "pack width" for the window that this container is located in. When the size
of this container changes the size of the window will be corrected to be within this
BoundsSize. It can be used to set the minimum and/or maximum size of the window
as well as the size window should optimally get. This optimal size is normally its
"preferred" size which is why "preferred" is the normal value to set here.
":push" can be appended to the bound size to only push the size bigger and never
shrink it if the preferred size gets smaller.
E.g. "pref", "100:pref", "pref:700", "300::700", "pref:push"
Parameters:
size
Since:
3.5
getPackHeight
public final BoundSize getPackHeight()
Returns the "pack height" for the window that this container is located in. When the
size of this container changes the size of the window will be corrected to be within
this BoundsSize. It can be used to set the minimum and/or maximum size of the
window as well as the size window should optimally get. This optimal size is normally
its "preferred" size which is why "preferred" is the normal value to set here.
":push" can be appended to the bound size to only push the size bigger and never
shrink it if the preferred size gets smaller.
E.g. "pref", "100:pref", "pref:700", "300::700", "pref:push"
Returns:
The current value. Never null. Check if not set with .isUnset().
Since:
3.5
Method Detail
1047
Sets the "pack height" for the window that this container is located in. When the size
of this container changes the size of the window will be corrected to be within this
BoundsSize. It can be used to set the minimum and/or maximum size of the window
as well as the size window should optimally get. This optimal size is normally its
"preferred" size which is why "preferred" is the normal value to set here.
":push" can be appended to the bound size to only push the size bigger and never
shrink it if the preferred size gets smaller.
E.g. "pref", "100:pref", "pref:700", "300::700", "pref:push"
Parameters:
size
Since:
3.5
getPackHeightAlign
public final float getPackHeightAlign()
Method Detail
1048
Returns the minimum/preferred/maximum size for the container that this layout
constraint is set for. Any of these sizes that is not null will be returned directly
instead of determining the corresponding size through asking the components in this
container.
Returns:
The width for the container that this layout constraint is set for. Not null but
all sizes can be null.
Since:
3.5
setWidth
public final void setWidth(BoundSize size)
Sets the minimum/preferred/maximum size for the container that this layout constraint
is set for. Any of these sizes that is not null will be returned directly instead of
determining the corresponding size through asking the components in this container.
Parameters:
size - The width for the container that this layout constraint is set for. null is
translated to a bound size containing only null sizes.
Since:
3.5
getHeight
public final BoundSize getHeight()
Returns the minimum/preferred/maximum size for the container that this layout
constraint is set for. Any of these sizes that is not null will be returned directly
instead of determining the corresponding size through asking the components in this
container.
Returns:
The height for the container that this layout constraint is set for. Not null but
all sizes can be null.
Since:
3.5
setHeight
public final void setHeight(BoundSize size)
Sets the minimum/preferred/maximum size for the container that this layout constraint
is set for. Any of these sizes that is not null will be returned directly instead of
determining the corresponding size through asking the components in this container.
Parameters:
size - The height for the container that this layout constraint is set for. null is
translated to a bound size containing only null sizes.
Since:
3.5
pack
public final LC pack()
Method Detail
1049
Since:
3.5
pack
public final LC pack(String width,
String height)
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
Since:
3.5
packAlign
public final LC packAlign(float alignX,
float alignY)
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
Since:
3.5
wrap
public final LC wrap()
Method Detail
1050
wrapAfter
public final LC wrapAfter(int count)
Same functionality as setWrapAfter(int) only this method returns this for chaining
multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- After what cell the grid should always auto wrap. If 0 the number of
columns/rows in the
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
noCache
count
Same functionality as calling setNoCache(boolean) with true only this method returns
this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
flowY
public final LC flowY()
Same functionality as calling setFlowX(boolean) with false only this method returns
this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
flowX
public final LC flowX()
Same functionality as calling setFlowX(boolean) with true only this method returns
this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
fill
public final LC fill()
Method Detail
1051
fillX
public final LC fillX()
Same functionality as calling setFillX(boolean) with true only this method returns
this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
fillY
public final LC fillY()
Same functionality as calling setFillY(boolean) with true only this method returns
this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
leftToRight
public final LC leftToRight(boolean b)
Same functionality as setLeftToRight(false) only this method returns this for chaining
multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
Since:
3.7.2
bottomToTop
public final LC bottomToTop()
Method Detail
1052
topToBottom
public final LC topToBottom()
Since:
3.7.2
noGrid
public final LC noGrid()
Same functionality as calling setNoGrid(boolean) with true only this method returns
this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
noVisualPadding
public final LC noVisualPadding()
insetsAll
public final LC insetsAll(String allSides)
Sets the same inset (expressed as a UnitValue, e.g. "10px" or "20mm") all around.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The unit value to set for all sides. May be null which means that
the default panel insets for the platform is used.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
allSides
setInsets(UnitValue[])
Method Detail
1053
insets
public final LC insets(String
String
String
String
top,
left,
bottom,
right)
Sets the different insets (expressed as a UnitValues, e.g. "10px" or "20mm") for the
corresponding sides.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
top - The top inset. E.g. "10px" or "10mm" or "related". May be null in which
case the default inset for this side for the platform will be used.
left - The left inset. E.g. "10px" or "10mm" or "related". May be null in which
case the default inset for this side for the platform will be used.
bottom - The bottom inset. E.g. "10px" or "10mm" or "related". May be null in
which case the default inset for this side for the platform will be used.
right - The right inset. E.g. "10px" or "10mm" or "related". May be null in
which case the default inset for this side for the platform will be used.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setInsets(UnitValue[])
alignX
public final LC alignX(String align)
Same functionality as
setAlignX(ConstraintParser.parseUnitValueOrAlign(unitValue, true))
method returns this for chaining multiple calls.
only this
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The align keyword or for instance "100px". E.g "left", "right", "leading"
or "trailing".
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
align
setAlignX(UnitValue)
Method Detail
1054
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setAlignY(UnitValue)
align
public final LC align(String ax,
String ay)
setGridGapX(BoundSize)
gridGapY
public final LC gridGapY(String boundsSize)
Method Detail
1055
See Also:
setGridGapY(BoundSize)
gridGap
public final LC gridGap(String gapx,
String gapy)
Sets both grid gaps at the same time. see gridGapX(String) and gridGapY(String).
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The BoundSize of the gap. This is a minimum and/or preferred and/or
maximum size. E.g. "50:100:200" or "100px".
gapy - The BoundSize of the gap. This is a minimum and/or preferred and/or
maximum size. E.g. "50:100:200" or "100px".
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
gridGapX(String), gridGapY(String)
debug
gapx
See Also:
setDebugMillis(int)
debug
public final LC debug(int repaintMillis)
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setDebugMillis(int)
hideMode
public final LC hideMode(int mode)
Same functionality as setHideMode(int mode) only this method returns this for
chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The mode:
0 == Normal. Bounds will be calculated as if the component was visible.
1 == If hidden the size will be 0, 0 but the gaps remain.
2 == If hidden the size will be 0, 0 and gaps set to zero.
mode
Method Detail
1056
minWidth
public final LC minWidth(String width)
The minimum width for the container. The value will override any value that is set on
the container itself.
For a more thorough explanation of what this constraint does see the white paper or
Cheat Sheet at www.migcontainers.com.
Parameters:
width
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
width
public final LC width(String width)
The width for the container as a min and/or preferred and/or maximum width. The
value will override any value that is set on the container itself.
For a more thorough explanation of what this constraint does see the white paper or
Cheat Sheet at www.migcontainers.com.
Parameters:
- The width expressed as a BoundSize. E.g. "50:100px:200mm" or
"100px".
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
maxWidth
width
The maximum width for the container. The value will override any value that is set on
the container itself.
For a more thorough explanation of what this constraint does see the white paper or
Cheat Sheet at www.migcontainers.com.
Parameters:
width
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
minHeight
public final LC minHeight(String height)
The minimum height for the container. The value will override any value that is set on
the container itself.
For a more thorough explanation of what this constraint does see the white paper or
Cheat Sheet at www.migcontainers.com.
Parameters:
height
Returns:
Method Detail
1057
height
public final LC height(String height)
The height for the container as a min and/or preferred and/or maximum height. The
value will override any value that is set on the container itself.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcontainers.com.
Parameters:
- The height expressed as a BoundSize. E.g. "50:100px:200mm" or
"100px".
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
maxHeight
height
The maximum height for the container. The value will override any value that is set on
the container itself.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcontainers.com.
Parameters:
height
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
Method Detail
1058
Interface InCellGapProvider
public interface
An interface to implement if you want to decide the gaps between two types of components within the
same cell.
E.g.:
if (adjacentComp == null || adjacentSide == SwingConstants.LEFT || adjacentSide == SwingConstants.TOP)
return null;
boolean isHor = (adjacentSide == SwingConstants.LEFT || adjacentSide == SwingConstants.RIGHT);
Method Summary
Modifier and
Type
BoundSize
Returns the default gap between two components that are in the same cell.
Method Detail
getDefaultGap
BoundSize getDefaultGap(ComponentWrapper comp,
ComponentWrapper adjacentComp,
int adjacentSide,
String tag,
boolean isLTR)
Returns the default gap between two components that are in the same cell.
Parameters:
comp - The component that the gap is for. Never null.
adjacentComp - The adjacent component if any. May be null.
adjacentSide - What side the adjacentComp is on. SwingConstants.TOP or
SwingConstants.LEFT or SwingConstants.BOTTOM or SwingConstants.RIGHT.
tag - The tag string that the component might be tagged with in the
component constraints. May be null.
isLTR - If it is left-to-right.
Returns:
The default gap between two components or null if there should be no gap.
Interface InCellGapProvider
1059
Class Grid
java.lang.Object
com.codename1.ui.layouts.mig.Grid
Holds components in a grid. Does most of the logic behind the layout manager.
Field Summary
Modifier and Type Field and Description
static boolean
TEST_GAPS
Constructor Summary
Constructor and Description
Grid(ContainerWrapper container, LC lc, AC rowConstr, AC colConstr, Map<? extends
ComponentWrapper,CC> ccMap, ArrayList<LayoutCallback> callbackList)
Constructor.
Method Summary
Modifier and
Type
ContainerWrapper getContainer()
int[]
getHeight()
int[]
getHeight(int refWidth)
int[]
getWidth()
int[]
getWidth(int refHeight)
invalidateContainerSize()
If the container (parent) that this grid is laying out has changed its
bounds, call this method to clear any cached values min/pref/max sizes
of the components and rows/columns.
void
boolean
Deprecated.
since 5.0 Last boolean is not needed and is gotten from the new
net.miginfocom.layout.ComponentWrapper#getContentBias() instead;
void
paintDebug()
Method Detail
1060
Detail
TEST_GAPS
public static final boolean TEST_GAPS
See Also:
Constant Field Values
Constructor Detail
Grid
public Grid(ContainerWrapper container,
LC lc,
AC rowConstr,
AC colConstr,
Map<? extends ComponentWrapper,CC> ccMap,
ArrayList<LayoutCallback> callbackList)
Constructor.
Parameters:
container - The container that will be laid out.
lc - The form flow constraints.
rowConstr - The rows specifications. If more cell
Method Detail
invalidateContainerSize
public void invalidateContainerSize()
If the container (parent) that this grid is laying out has changed its bounds, call this
method to clear any cached values min/pref/max sizes of the components and
rows/columns.
If any component can have changed cell the grid needs to be recreated.
layout
public boolean layout(int[] bounds,
UnitValue alignX,
UnitValue alignY,
boolean debug,
boolean notUsed)
Deprecated. since 5.0 Last boolean is not needed and is gotten from the new
net.miginfocom.layout.ComponentWrapper#getContentBias() instead;
layout
public boolean layout(int[] bounds,
UnitValue alignX,
UnitValue alignY,
boolean debug)
Does the actual layout. Uses many values calculated in the constructor.
Parameters:
Field Detail
1061
getContainer
public ContainerWrapper getContainer()
getWidth
public final int[] getWidth()
getWidth
public final int[] getWidth(int refHeight)
getHeight
public final int[] getHeight()
getHeight
public final int[] getHeight(int refWidth)
Method Detail
1062
Class DimConstraint
java.lang.Object
com.codename1.ui.layouts.mig.DimConstraint
Constructor Summary
Constructor and Description
DimConstraint()
Empty constructor.
Method Summary
Modifier
and Type
UnitValue
Returns the alignment used either as a default value for sub-entities or for this
entity.
UnitValue
getAlignOrDefault(boolean isCols)
getEndGroup()
String
BoundSize
BoundSize
Float
int
Float
int
Returns the end group that this entity should be in for the demension that this
object is describing.
getGapAfter()
BoundSize
Returns the min/preferred/max size for the entity in the dimension that this
object describes.
getSizeGroup()
String
Returns the size group that this entity should be in for the dimension that this
object is describing.
isFill()
boolean
boolean
void
Class DimConstraint
Returns if the component in the row/column that this constraint should default
be grown in the same dimension that this constraint represents (width for
column and height for a row).
isNoGrid()
Returns if the row/column should default to flow and not to grid behaviour.
setAlign(UnitValue uv)
1063
Sets the end group that this entity should be in for the demension that this
object is describing.
void
setFill(boolean b)
Sets if the component in the row/column that this constraint should default be
grown in the same dimension that this constraint represents (width for column
and height for a row).
void
setGapAfter(BoundSize size)
void
void
void
void
void
Sets if the row/column should default to flow and not to grid behaviour.
setShrink(Float weight)
void
void
Sets the min/preferred/max size for the entity in the dimension that this object
describes.
void
setSizeGroup(String s)
Sets the size group that this entity should be in for the dimension that this
object is describing.
void
Constructor Detail
DimConstraint
public DimConstraint()
Empty constructor.
Method Detail
getGrowPriority
public int getGrowPriority()
Returns the grow priority. Relative priority is used for determining which entities gets
the extra space first.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The grow priority.
Method Summary
1064
Sets the grow priority. Relative priority is used for determining which entities gets the
extra space first.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
p - The new grow priority.
getGrow
public Float getGrow()
Returns the shrink priority. Relative priority is used for determining which entities gets
smaller first when space is scarce.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The shrink priority.
setShrinkPriority
public void setShrinkPriority(int p)
Sets the shrink priority. Relative priority is used for determining which entities gets
smaller first when space is scarce.
Method Detail
1065
Returns the shrink priority. Relative priority is used for determining which entities gets
smaller first when space is scarce. Shrink weight is how flexible the entity should be,
relative to other entities, when it comes to shrinking. null or zero mean it will never
shrink (default). An entity that has twice the shrink weight compared to another entity
will get twice as much of available space.
Shrink(Weight) are only compared within the same ShrinkPrio.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current shrink weight.
setShrink
public void setShrink(Float weight)
Sets the shrink priority. Relative priority is used for determining which entities gets
smaller first when space is scarce. Shrink weight is how flexible the entity should be,
relative to other entities, when it comes to shrinking. null or zero mean it will never
shrink (default). An entity that has twice the shrink weight compared to another entity
will get twice as much of available space.
Shrink(Weight) are only compared within the same ShrinkPrio.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
weight - The new shrink weight.
getAlignOrDefault
public UnitValue getAlignOrDefault(boolean isCols)
getAlign
public UnitValue getAlign()
Returns the alignment used either as a default value for sub-entities or for this entity.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The alignment.
setAlign
public void setAlign(UnitValue uv)
Sets the alignment used wither as a default value for sub-entities or for this entity.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
uv - The new shrink priority. E.g. UnitValue.CENTER or
net.miginfocom.layout.UnitValue#LEADING.
Method Detail
1066
Returns the gap after this entity. The gap is an empty space and can have a
min/preferred/maximum size so that it can shrink and grow depending on available
space. Gaps are against other entities' edges and not against other entities' gaps.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The gap after this entity
setGapAfter
public void setGapAfter(BoundSize size)
Sets the gap after this entity. The gap is an empty space and can have a
min/preferred/maximum size so that it can shrink and grow depending on available
space. Gaps are against other entities' edges and not against other entities' gaps.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
size
See Also:
net.miginfocom.layout.ConstraintParser#parseBoundSize(String,
boolean, boolean)
getGapBefore
public BoundSize getGapBefore()
Returns the gap before this entity. The gap is an empty space and can have a
min/preferred/maximum size so that it can shrink and grow depending on available
space. Gaps are against other entities' edges and not against other entities' gaps.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The gap before this entity
setGapBefore
public void setGapBefore(BoundSize size)
Sets the gap before this entity. The gap is an empty space and can have a
min/preferred/maximum size so that it can shrink and grow depending on available
space. Gaps are against other entities' edges and not against other entities' gaps.
See also net.miginfocom.layout.ConstraintParser#parseBoundSize(String,
boolean, boolean). For a more thorough explanation of what this constraint does see
the white paper or cheat Sheet at www.migcomponents.com.
Parameters:
size
getSize
public BoundSize getSize()
Returns the min/preferred/max size for the entity in the dimension that this object
describes.
See also net.miginfocom.layout.ConstraintParser#parseBoundSize(String,
boolean, boolean). For a more thorough explanation of what this constraint does see
the white paper or cheat Sheet at www.migcomponents.com.
Method Detail
1067
Sets the min/preferred/max size for the entity in the dimension that this object
describes.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
size - The new size. May be null.
getSizeGroup
public String getSizeGroup()
Returns the size group that this entity should be in for the dimension that this object is
describing. If this constraint is in a size group that is specified here. null means no
size group and all other values are legal. Comparison with .equals().
Components/columnss/rows in the same size group will have the same
min/preferred/max size; that of the largest in the group for the first two and the
smallest for max.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current size group. May be null.
setSizeGroup
public void setSizeGroup(String s)
Sets the size group that this entity should be in for the dimension that this object is
describing. If this constraint is in a size group that is specified here. null means no
size group and all other values are legal. Comparison with .equals().
Components/columnss/rows in the same size group will have the same
min/preferred/max size; that of the largest in the group for the first two and the
smallest for max.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
s - The new size group. null disables size grouping.
getEndGroup
public String getEndGroup()
Returns the end group that this entity should be in for the demension that this object
is describing. If this constraint is in an end group that is specified here. null means
no end group and all other values are legal. Comparison with .equals(). Components
in the same end group will have the same end coordinate.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current end group. null may be returned.
setEndGroup
public void setEndGroup(String s)
Sets the end group that this entity should be in for the demension that this object is
describing. If this constraint is in an end group that is specified here. null means no
Method Detail
1068
Returns if the component in the row/column that this constraint should default be
grown in the same dimension that this constraint represents (width for column and
height for a row).
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
true
setFill
public void setFill(boolean b)
Sets if the component in the row/column that this constraint should default be grown
in the same dimension that this constraint represents (width for column and height for
a row).
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
b - true means that components should grow.
isNoGrid
public boolean isNoGrid()
Returns if the row/column should default to flow and not to grid behaviour. This
means that the whole row/column will be one cell and all components will end up in
that cell.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
true
setNoGrid
public void setNoGrid(boolean b)
Sets if the row/column should default to flow and not to grid behaviour. This means
that the whole row/column will be one cell and all components will end up in that cell.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
b - true means that the whole row/column should be one cell.
Method Detail
1069
Interface ContainerWrapper
All Superinterfaces:
ComponentWrapper
public interface
extends ComponentWrapper
Field Summary
Method Summary
Modifier and Type
int
ComponentWrapper[]
getComponents()
Object
of this container.
boolean
isLeftToRight()
void
Method Detail
getComponents
ComponentWrapper[] getComponents()
Interface ContainerWrapper
1070
Returns the LayoutHandler (in Swing terms) that is handling the layout of this
container. If there exist no such class the method should return the same as
ComponentWrapper.getComponent(), which is the container itself.
Returns:
The layout handler instance. Never null.
isLeftToRight
boolean isLeftToRight()
x,
y,
width,
height)
Method Detail
1071
Class ConstraintParser
java.lang.Object
com.codename1.ui.layouts.mig.ConstraintParser
Method Summary
Modifier and Type
static BoundSize
static AC
static CC
static
Map<ComponentWrapper,CC>
static UnitValue[]
parseComponentConstraints(Map<ComponentWrapper,String> constrMa
Parses all component constraints and stores the parsed values in the
transient (cache) member variables.
parseInsets(String s, boolean acceptPanel)
Parses insets which consists of 1-4 UnitValues.
parseLayoutConstraint(String s)
static LC
static AC
static UnitValue
static UnitValue
static String
Parses the layout constraints and stores the parsed values in the transi
(cache) member varables.
parseRowConstraints(String s)
Method Detail
parseLayoutConstraint
public static LC parseLayoutConstraint(String s)
Parses the layout constraints and stores the parsed values in the transient (cache)
member varables.
Parameters:
s - The String to parse. Should not be null and must be lower case and
trimmed.
Returns:
Class ConstraintParser
1072
parseRowConstraints
public static AC parseRowConstraints(String s)
Parses the column or rows constraints. They normally looks something like
"[min:pref]rel[10px][]".
Parameters:
s - The string to parse. Not null.
Returns:
An array of DimConstraints that is as many are there exist "[...]" sections in
the string that is parsed.
Throws:
RuntimeException - if the constraint was not valid.
parseColumnConstraints
public static AC parseColumnConstraints(String s)
Parses the column or rows constraints. They normally looks something like
"[min:pref]rel[10px][]".
Parameters:
s - The string to parse. Not null.
Returns:
An array of DimConstraints that is as many are there exist "[...]" sections in
the string that is parsed.
Throws:
RuntimeException - if the constraint was not valid.
parseComponentConstraints
Parses all component constraints and stores the parsed values in the transient
(cache) member variables.
Parameters:
constrMap - The constraints as Strings. Strings must be lower case and
trimmed
Returns:
The parsed constraints. Never null.
parseComponentConstraint
public static CC parseComponentConstraint(String s)
Method Detail
1073
Method Detail
1074
Interface ComponentWrapper
All Known Subinterfaces:
ContainerWrapper
public interface
Field Summary
Modifier and Type Field and Description
static int
TYPE_BUTTON
static int
TYPE_CHECK_BOX
static int
TYPE_COMBO_BOX
static int
TYPE_CONTAINER
static int
TYPE_IMAGE
static int
TYPE_LABEL
static int
TYPE_LIST
static int
TYPE_PANEL
static int
TYPE_PROGRESS_BAR
static int
TYPE_SCROLL_BAR
static int
TYPE_SCROLL_PANE
static int
TYPE_SEPARATOR
static int
TYPE_SLIDER
static int
TYPE_SPINNER
static int
TYPE_TABBED_PANE
static int
TYPE_TABLE
static int
TYPE_TEXT_AREA
static int
TYPE_TEXT_FIELD
static int
TYPE_TREE
static int
TYPE_UNKNOWN
static int
TYPE_UNSET
Interface ComponentWrapper
1075
Method Summary
Modifier and
Type
int
Object
int
Returns the baseline for the component given the suggested height.
getComponent()
int
int
Returns in what way the min/pref/max sizes relates to it's height or width
for the current settings of the component (like wrapText).
getHeight()
int
Returns the DPI (Dots Per Inch) of the screen the component is currently
in or for the default screen if the component is not visible.
getLayoutHashCode()
int
String
int
int
int
int
ContainerWrapper
float
int
int
Returns the pixel unit factor for the horizontal or vertical dimension.
getPreferredHeight(int wHint)
int
Returns the pixel size of the screen that the component is currently in or
for the default screen if the component is not visible or null.
getScreenLocationX()
int
Returns the screen x-coordinate for the upper left coordinate of the
component layout-able bounds.
getScreenLocationY()
int
Returns the screen y-coordinate for the upper left coordinate of the
component layout-able bounds.
getScreenWidth()
int
Returns the pixel size of the screen that the component is currently in or
for the default screen if the component is not visible or null.
getVerticalScreenDPI()
int
int[]
int
Method Summary
Returns the DPI (Dots Per Inch) of the screen the component is currently
in or for the default screen if the component is not visible.
getVisualPadding()
1076
int
int
boolean
boolean
void
void
hasBaseline()
Field Detail
TYPE_UNSET
static final int TYPE_UNSET
See Also:
Constant Field Values
TYPE_UNKNOWN
static final int TYPE_UNKNOWN
See Also:
Constant Field Values
TYPE_CONTAINER
static final int TYPE_CONTAINER
See Also:
Constant Field Values
TYPE_LABEL
static final int TYPE_LABEL
See Also:
Constant Field Values
TYPE_TEXT_FIELD
static final int TYPE_TEXT_FIELD
See Also:
Constant Field Values
TYPE_TEXT_AREA
static final int TYPE_TEXT_AREA
See Also:
Constant Field Values
TYPE_BUTTON
static final int TYPE_BUTTON
See Also:
Constant Field Values
Field Detail
1077
See Also:
Constant Field Values
TYPE_TABLE
static final int TYPE_TABLE
See Also:
Constant Field Values
TYPE_SCROLL_PANE
static final int TYPE_SCROLL_PANE
See Also:
Constant Field Values
TYPE_IMAGE
static final int TYPE_IMAGE
See Also:
Constant Field Values
TYPE_PANEL
static final int TYPE_PANEL
See Also:
Constant Field Values
TYPE_COMBO_BOX
static final int TYPE_COMBO_BOX
See Also:
Constant Field Values
TYPE_SLIDER
static final int TYPE_SLIDER
See Also:
Constant Field Values
TYPE_SPINNER
static final int TYPE_SPINNER
See Also:
Constant Field Values
TYPE_PROGRESS_BAR
static final int TYPE_PROGRESS_BAR
See Also:
Constant Field Values
TYPE_TREE
static final int TYPE_TREE
See Also:
Constant Field Values
TYPE_CHECK_BOX
static final int TYPE_CHECK_BOX
See Also:
Constant Field Values
Field Detail
1078
See Also:
Constant Field Values
TYPE_SEPARATOR
static final int TYPE_SEPARATOR
See Also:
Constant Field Values
TYPE_TABBED_PANE
static final int TYPE_TABBED_PANE
See Also:
Constant Field Values
Method Detail
getComponent
Object getComponent()
Returns the actual object that this wrapper is aggregating. This might be needed for
getting information about the object that the wrapper interface does not provide.
If this is a container the container should be returned instead.
Returns:
The actual object that this wrapper is aggregating. Not null.
getX
int getX()
Returns the screen x-coordinate for the upper left coordinate of the component
layout-able bounds.
Field Detail
1079
Returns the screen y-coordinate for the upper left coordinate of the component
layout-able bounds.
Returns:
The screen y-coordinate for the upper left coordinate of the component
layout-able bounds.
getMinimumWidth
int getMinimumWidth(int hHint)
Method Detail
1080
x,
y,
width,
height)
Returns if the component's visibility is set to true. This should not return if the
component is actually visible, but if the visibility is set to true or not.
Returns:
true means visible.
Method Detail
1081
Returns the baseline for the component given the suggested height.
Parameters:
width - The width to calculate for if other than the current. If -1 the current
size should be used.
height - The height to calculate for if other than the current. If -1 the current
size should be used.
Returns:
The baseline from the top or -1 if not applicable.
hasBaseline
boolean hasBaseline()
Returns if the component has a baseline and if it can be retrieved. Should for
instance return false for Swing before mustang.
Returns:
If the component has a baseline and if it can be retrieved.
getParent
ContainerWrapper getParent()
Returns the pixel unit factor for the horizontal or vertical dimension.
The factor is 1 for both dimensions on the normal font in a JPanel on Windows. The
factor should increase with a bigger "X".
This is the Swing version:
Rectangle2D r = fm.getStringBounds("X", parent.getGraphics());
wFactor = r.getWidth() / 6;
hFactor = r.getHeight() / 13.27734375f;
Parameters:
isHor - If it is the horizontal factor that should be returned.
Returns:
The factor.
getHorizontalScreenDPI
int getHorizontalScreenDPI()
Returns the DPI (Dots Per Inch) of the screen the component is currently in or for the
default screen if the component is not visible.
If headless mode net.miginfocom.layout.PlatformDefaults#getDefaultDPI will be
returned.
Returns:
The DPI.
getVerticalScreenDPI
int getVerticalScreenDPI()
Returns the DPI (Dots Per Inch) of the screen the component is currently in or for the
default screen if the component is not visible.
Method Detail
1082
Returns the pixel size of the screen that the component is currently in or for the
default screen if the component is not visible or null.
If in headless mode 1024 is returned.
Returns:
The screen size. E.g. 1280.
getScreenHeight
int getScreenHeight()
Returns the pixel size of the screen that the component is currently in or for the
default screen if the component is not visible or null.
If in headless mode 768 is returned.
Returns:
The screen size. E.g. 1024.
getLinkId
String getLinkId()
Returns a String id that can be used to reference the component in link constraints.
This value should return the default id for the component. The id can be set for a
component in the constraints and if so the value returned by this method will never be
used. If there are no sensible id for the component null should be returned.
For instance the Swing implementation returns the string returned from
Component.getName().
Returns:
The string link id or null.
getLayoutHashCode
int getLayoutHashCode()
Returns a hash code that should be reasonably different for anything that might
change the layout. This value is used to know if the component layout needs to clear
any caches.
Returns:
A hash code that should be reasonably different for anything that might
change the layout. Returns -1 if the widget is disposed.
getVisualPadding
int[] getVisualPadding()
Method Detail
1083
int getContentBias()
Returns in what way the min/pref/max sizes relates to it's height or width for the
current settings of the component (like wrapText). If the min/pref/max height depends
on it's width return net.miginfocom.layout.LayoutUtil#HORIZONTAL If the
min/pref/max width depends on it's height (not common) return
net.miginfocom.layout.LayoutUtil#VERTICAL If there is no connection between the
preferred min/pref/max and the size of the component return -1.
Since:
5.0
Method Detail
1084
Class CC
java.lang.Object
com.codename1.ui.layouts.mig.CC
Constructor Summary
Constructor and Description
CC()
Empty constructor.
Method Summary
Modifier and
Type
CC
Same functionality as
getHorizontal().setAlign(ConstraintParser.parseUnitValue(unitValue,
true)) only this method returns this for chaining multiple calls.
alignY(String align)
CC
CC
Same functionality as
getVertical().setAlign(ConstraintParser.parseUnitValue(unitValue,
true)) only this method returns this for chaining multiple calls.
cell(int... colRowWidthHeight)
Set the cell(s) that the component should occupy in the grid.
dockEast()
CC
CC
CC
CC
CC
CC
CC
Specifies that the component should be put in the end group s and will thus
share the same ending coordinate as them within the group.
endGroupY(String s)
Class CC
CC
CC
flowX()
1085
CC
CC
CC
CC
CC
CC
CC
CC
CC
The vertical gap before (normally above) and/or after (normally below) the
component.
getCellX()
int
Returns the absolute cell position in the grid or -1 if cell positioning is not
used.
getCellY()
int
DimConstraint
int
Boolean
Returns the absolute cell position in the grid or -1 if cell positioning is not
used.
getDimConstraint(boolean isHor)
int
DimConstraint
String
BoundSize
UnitValue[]
UnitValue[]
Returns the absolute resizing in the last stage of the layout cycle.
getPos()
Float
"pushx" indicates that the column that this component is in (this first if the
component spans) should default to growing.
getPushY()
Float
"pushx" indicates that the row that this component is in (this first if the
component spans) should default to growing.
getSkip()
int
Method Summary
Returns how many cells in the grid that should be skipped before the
component that this constraint belongs to.
1086
Returns the number of cells the cell that this constraint's component will
span in the indicated dimension.
getSpanY()
int
Returns the number of cells the cell that this constraint's component will
span in the indicated dimension.
getSplit()
int
String
DimConstraint
UnitValue[]
BoundSize
CC
CC
CC
CC
CC
CC
CC
CC
CC
CC
CC
CC
Returns in how many parts the current cell (that this constraint's component
will be in) should be split in.
getTag()
Returns the visual padding used when laying out this Component.
getWrapGapSize()
The size for the component as a min and/or preferred and/or maximum size.
hideMode(int mode)
boolean
boolean
boolean
Returns if the flow should wrap to the next line/column before the
component that this constraint belongs to.
isWrap()
boolean
CC
CC
CC
Method Summary
Returns if the flow should wrap to the next line/column after the component
that this constraint belongs to.
maxHeight(String size)
1087
minWidth(String size)
CC
CC
CC
absolute pixels.
pad(String pad)
CC
CC
pos(String x, String y)
Same functionality as x(String x)
CC
push()
CC
CC
Same functionality as setPushX(Float) which means this cell will push the
rest of the row.
pushX(Float weight)
CC
CC
Same functionality as setPushY(Float) which means this cell will push the
rest of the column.
pushY(Float weight)
CC
void
void
void
void
void
If this boolean is true this component is not handled in any way by the layout
manager and the component can have its bounds set by an external handler
which is normally by the use of some component.setBounds(x, y, width,
height) directly (for Swing).
setFlowX(Boolean b)
void
void
void
void
Method Summary
Sets if the flow should wrap to the next line/column before the component
that this constraint belongs to.
1088
setNewlineGapSize(BoundSize s)
Sets the absolute resizing in the last stage of the layout cycle.
setPos(UnitValue[] pos)
void
"pushx" indicates that the column that this component is in (this first if the
component spans) should default to growing.
setPushY(Float weight)
void
"pushx" indicates that the row that this component is in (this first if the
component spans) should default to growing.
setSkip(int cells)
void
Sets how many cells in the grid that should be skipped before the
component that this constraint belongs to.
setSpanX(int cells)
void
Sets the number of cells the cell that this constraint's component will span in
the indicated dimension.
setSpanY(int cells)
void
Sets the number of cells the cell that this constraint's component will span in
the indicated dimension.
setSplit(int parts)
void
void
void
void
Sets in how many parts the current cell (that this constraint's component will
be in) should be split in.
setTag(String tag)
Sets the visual padding used when laying out this Component.
setWrap(boolean b)
void
void
CC
CC
CC
CC
CC
CC
CC
Sets if the flow should wrap to the next line/column after the component that
this constraint belongs to.
setWrapGapSize(BoundSize s)
CC
CC
CC
Specifies that the component should be put in the size group s and will thus
share the same size as them within the group.
sizeGroupY(String s)
CC
Method Summary
1089
CC
spanX()
Same functionality as setSpanX(int) which means this cell will span the rest
of the row.
CC
spanX(int cells)
CC
spanY()
CC
spanY(int cells)
CC
split()
CC
split(int parts)
CC
tag(String tag)
Same functionality as setTag(String tag) only this method returns this for
chaining multiple calls.
CC
width(String size)
CC
The size for the component as a min and/or preferred and/or maximum size.
wrap()
CC
wrap(String gapSize)
Same functionality as setWrapGapSize(BoundSize)
this for chaining multiple calls.
CC
x(String x)
CC
CC
CC
CC
Constructor Detail
CC
public CC()
Empty constructor.
Method Detail
1090
Specifies that the component should be put in the end group s and will thus share the
same ending coordinate as them within the group.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
s - A name to associate on the group that should be the same for other
rows/columns in the same group.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
sizeGroupX
public final CC sizeGroupX(String s)
Specifies that the component should be put in the size group s and will thus share the
same size as them within the group.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
s - A name to associate on the group that should be the same for other
rows/columns in the same group.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
minWidth
public final CC minWidth(String size)
The minimum size for the component. The value will override any value that is set on
the component itself.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
size
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
width
public final CC width(String size)
The size for the component as a min and/or preferred and/or maximum size. The
value will override any value that is set on the component itself.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The size expressed as a BoundSize. E.g. "50:100px:200mm" or
"100px".
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
size
Method Detail
1091
The maximum size for the component. The value will override any value that is set on
the component itself.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
size
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
gapX
public final CC gapX(String before,
String after)
The horizontal gap before and/or after the component. The gap is towards cell
bounds and/or other component bounds.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The size of the gap expressed as a BoundSize. E.g.
"50:100px:200mm" or "100px!".
after - The size of the gap expressed as a BoundSize. E.g.
"50:100px:200mm" or "100px!".
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
alignX
before
Same functionality as
getHorizontal().setAlign(ConstraintParser.parseUnitValue(unitValue, true))
only this method returns this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The align keyword or for instance "100px". E.g "left", "right", "leading"
or "trailing".
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
growPrioX
align
Method Detail
1092
- The new shrink weight and height. 1-2 arguments, never null.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
Since:
3.7.2
growX
public final CC growX()
See Also:
growX(float)
growX
public final CC growX(float w)
grow
public final CC grow(float... widthHeight)
- The new shrink weight and height. 1-2 arguments, never null.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
Since:
3.7.2
shrinkPrioX
public final CC shrinkPrioX(int p)
Method Detail
1093
shrinkPrio
public final CC shrinkPrio(int... widthHeight)
- The new shrink weight and height. 1-2 arguments, never null.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
Since:
3.7.2
shrinkX
public final CC shrinkX(float w)
shrink
public final CC shrink(float... widthHeight)
- The new shrink weight and height. 1-2 arguments, never null.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
Since:
3.7.2
endGroupY
public final CC endGroupY(String s)
Method Detail
1094
endGroup
public final CC endGroup(String... xy)
The minimum size for the component. The value will override any value that is set on
the component itself.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
size
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
Method Detail
1095
The size for the component as a min and/or preferred and/or maximum size. The
value will override any value that is set on the component itself.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The size expressed as a BoundSize. E.g. "50:100px:200mm" or
"100px".
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
maxHeight
size
The maximum size for the component. The value will override any value that is set on
the component itself.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
size
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
gapY
public final CC gapY(String before,
String after)
The vertical gap before (normally above) and/or after (normally below) the
component. The gap is towards cell bounds and/or other component bounds.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The size of the gap expressed as a BoundSize. E.g.
"50:100px:200mm" or "100px!".
after - The size of the gap expressed as a BoundSize. E.g.
"50:100px:200mm" or "100px!".
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
alignY
before
Same functionality as
getVertical().setAlign(ConstraintParser.parseUnitValue(unitValue, true))
only this method returns this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
align
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
Method Detail
1096
growY
public final CC growY()
See Also:
growY(Float)
growY
public final CC growY(Float w)
shrinkPrioY
public final CC shrinkPrioY(int p)
shrinkY
public final CC shrinkY(float w)
Method Detail
1097
hideMode
public final CC hideMode(int mode)
Same functionality as setTag(String tag) only this method returns this for chaining
multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
tag - The new tag. May be null.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setTag(String)
cell
public final CC cell(int... colRowWidthHeight)
Set the cell(s) that the component should occupy in the grid. Same functionality as
setCellX(int col) and setCellY(int row) together with setSpanX(int width) and
setSpanY(int height). This method returns this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Method Detail
1098
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
Since:
3.7.2 Replaces span(int, int).
See Also:
setSpanY(int), setSpanX(int), spanY(), spanX()
gap
public final CC gap(String... args)
Method Detail
1099
Method Detail
1100
See Also:
setSpanY(int), spanY()
spanY
public final CC spanY(int cells)
Same functionality as setSpanY(int) only this method returns this for chaining
multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
cells
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setSpanY(int)
spanX
public final CC spanX()
Same functionality as setSpanX(int) which means this cell will span the rest of the
row. This method returns this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setSpanX(int), spanX()
spanX
public final CC spanX(int cells)
Same functionality as setSpanX(int) only this method returns this for chaining
multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
cells
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setSpanY(int)
push
public final CC push()
Same functionality as pushX().pushY() which means this cell will push in both x and
y dimensions. This method returns this for chaining multiple calls.
Method Detail
1101
See Also:
setPushX(Float), setPushX(Float), pushY(), pushX()
push
public final CC push(Float weightX,
Float weightY)
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setPushY(Float), setPushX(Float), pushY(), pushX()
pushY
public final CC pushY()
Same functionality as setPushY(Float) which means this cell will push the rest of the
column. This method returns this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setPushY(Float)
pushY
public final CC pushY(Float weight)
Same functionality as setPushY(Float weight) only this method returns this for
chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
weight
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setPushY(Float)
pushX
public final CC pushX()
Same functionality as setPushX(Float) which means this cell will push the rest of the
row. This method returns this for chaining multiple calls.
Method Detail
1102
See Also:
setPushX(Float)
pushX
public final CC pushX(Float weight)
Same functionality as setPushX(Float weight) only this method returns this for
chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
weight
Returns:
this so it is possible to chain calls. E.g. new
LayoutConstraint().noGrid().gap().fill().
See Also:
setPushY(Float)
split
public final CC split(int parts)
Same functionality as setSplit(int parts) only this method returns this for
chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
parts
- The number of parts (i.e. component slots) the cell should be divided
into.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
See Also:
setSplit(int)
split
public final CC split()
Since:
3.7.2
See Also:
setSplit(int)
skip
public final CC skip(int cells)
Same functionality as setSkip(int) only this method returns this for chaining
multiple calls.
Method Detail
1103
setSkip(int)
skip
public final CC skip()
Since:
3.7.2
See Also:
setSkip(int)
external
public final CC external()
See Also:
setExternal(boolean)
flowX
public final CC flowX()
See Also:
setFlowX(Boolean)
flowY
public final CC flowY()
Method Detail
1104
See Also:
setFlowX(Boolean)
grow
public final CC grow()
See Also:
growX(), growY()
newline
public final CC newline()
Same functionality as calling setNewline(boolean) with true only this method returns
this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
See Also:
setNewline(boolean)
newline
public final CC newline(String gapSize)
setNewlineGapSize(BoundSize)
wrap
public final CC wrap()
Same functionality as calling setWrap(boolean) with true only this method returns
this for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
Method Detail
1105
wrap
public final CC wrap(String gapSize)
setWrapGapSize(BoundSize)
dockNorth
public final CC dockNorth()
Same functionality as calling setDockSide(int) with 0 only this method returns this
for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
See Also:
setDockSide(int)
dockWest
public final CC dockWest()
Same functionality as calling setDockSide(int) with 1 only this method returns this
for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
See Also:
setDockSide(int)
dockSouth
public final CC dockSouth()
Same functionality as calling setDockSide(int) with 2 only this method returns this
for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
See Also:
setDockSide(int)
Method Detail
1106
Same functionality as calling setDockSide(int) with 3 only this method returns this
for chaining multiple calls.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
See Also:
setDockSide(int)
x
public final CC x(String x)
Sets the x-coordinate for the component. This is used to set the x coordinate position
to a specific value. The component bounds is still precalculated to the grid cell and
this method should be seen as a way to correct the x position.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
x - The x position as a UnitValue. E.g. "10" or "40mm" or "container.x+10".
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
See Also:
setPos(UnitValue[]), setBoundsInGrid(boolean)
y
public final CC y(String y)
Sets the y-coordinate for the component. This is used to set the y coordinate position
to a specific value. The component bounds is still precalculated to the grid cell and
this method should be seen as a way to correct the y position.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
y - The y position as a UnitValue. E.g. "10" or "40mm" or "container.x+10".
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
See Also:
setPos(UnitValue[]), setBoundsInGrid(boolean)
x2
public final CC x2(String x2)
Sets the x2-coordinate for the component (right side). This is used to set the x2
coordinate position to a specific value. The component bounds is still precalculated to
the grid cell and this method should be seen as a way to correct the x position.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
x2 - The x2 side's position as a UnitValue. E.g. "10" or "40mm" or
"container.x2 - 10".
Returns:
Method Detail
1107
See Also:
setPos(UnitValue[]), setBoundsInGrid(boolean)
y2
public final CC y2(String y2)
Sets the y2-coordinate for the component (bottom side). This is used to set the y2
coordinate position to a specific value. The component bounds is still precalculated to
the grid cell and this method should be seen as a way to correct the y position.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
y2 - The y2 side's position as a UnitValue. E.g. "10" or "40mm" or
"container.x2 - 10".
Returns:
this so it is possible to chain calls. E.g. new
ComponentConstraint().noGrid().gap().fill().
See Also:
setPos(UnitValue[]), setBoundsInGrid(boolean)
pos
public final CC pos(String x,
String y)
pos
public final CC pos(String
String
String
String
x,
y,
x2,
y2)
Method Detail
1108
top,
left,
bottom,
right)
pad
public final CC pad(String pad)
getHorizontal
public DimConstraint getHorizontal()
Returns the horizontal dimension constraint for this component constraint. It has
constraints for the horizontal size and grow/shink priorities and weights.
Note! If any changes is to be made it must be made direct when the object is
returned. It is not allowed to save the constraint for later use.
Returns:
The current dimension constraint. Never null.
setHorizontal
public void setHorizontal(DimConstraint h)
Sets the horizontal dimension constraint for this component constraint. It has
constraints for the horizontal size and grow/shrink priorities and weights.
Parameters:
h - The new dimension constraint. If null it will be reset to new
DimConstraint();
Method Detail
1109
Returns the vertical dimension constraint for this component constraint. It has
constraints for the vertical size and grow/shrink priorities and weights.
Note! If any changes is to be made it must be made direct when the object is
returned. It is not allowed to save the constraint for later use.
Returns:
The current dimension constraint. Never null.
setVertical
public void setVertical(DimConstraint v)
Sets the vertical dimension constraint for this component constraint. It has constraints
for the vertical size and grow/shrink priorities and weights.
Parameters:
v - The new dimension constraint. If null it will be reset to new
DimConstraint();
getDimConstraint
public DimConstraint getDimConstraint(boolean isHor)
Returns the absolute positioning of one or more of the edges. This will be applied last
in the layout cycle and will not affect the flow or grid positions. The positioning is
relative to the parent and can not (as padding) be used to adjust the edges relative to
the old value. May be null and elements may be null. null value(s) for the x2 and
y2 will be interpreted as to keep the preferred size and thus the x1 and x2 will just
absolutely positions the component.
Note that setBoundsInGrid(boolean) changes the interpretation of thisproperty
slightly.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value as a new array, free to modify.
setPos
public void setPos(UnitValue[] pos)
Sets absolute positioning of one or more of the edges. This will be applied last in the
layout cycle and will not affect the flow or grid positions. The positioning is relative to
the parent and can not (as padding) be used to adjust the edges relative to the old
value. May be null and elements may be null. null value(s) for the x2 and y2 will be
interpreted as to keep the preferred size and thus the x1 and x2 will just absolutely
positions the component.
Note that setBoundsInGrid(boolean) changes the interpretation of thisproperty
slightly.
Method Detail
1110
Returns if the absolute pos value should be corrections to the component that is in a
normal cell. If false the value of pos is truly absolute in that it will not affect the grid or
have a default bounds in the grid.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value.
See Also:
getPos()
getCellX
public int getCellX()
Returns the absolute cell position in the grid or -1 if cell positioning is not used.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value.
setCellX
public void setCellX(int x)
Set an absolute cell x-position in the grid. If >= 0 this point points to the absolute cell
that this constaint's component should occupy. If there's already a component in that
cell they will split the cell. The flow will then continue after this cell.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
x - The x-position or -1 to disable cell positioning.
getCellY
public int getCellY()
Returns the absolute cell position in the grid or -1 if cell positioning is not used.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value.
setCellY
public void setCellY(int y)
Set an absolute cell x-position in the grid. If >= 0 this point points to the absolute cell
that this constaint's component should occupy. If there's already a component in that
cell they will split the cell. The flow will then continue after this cell.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Method Detail
1111
- -1 or 0-3.
isExternal
public boolean isExternal()
Returns if this component should have its bounds handled by an external source and
not this layout manager.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value.
setExternal
public void setExternal(boolean b)
If this boolean is true this component is not handled in any way by the layout
manager and the component can have its bounds set by an external handler which is
normally by the use of some component.setBounds(x, y, width, height) directly
(for Swing).
The bounds will not affect the minimum and preferred size of the container.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
b - true means that the bounds are not changed.
getFlowX
public Boolean getFlowX()
Returns if the flow in the cell is in the horizontal dimension. Vertical if false. Only the
first component is a cell can set the flow.
If null the flow direction is inherited by from the net.miginfocom.layout.LC.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Method Detail
1112
Sets if the flow in the cell is in the horizontal dimension. Vertical if false. Only the
first component is a cell can set the flow.
If null the flow direction is inherited by from the net.miginfocom.layout.LC.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
b - Boolean.TRUE means horizontal flow in the cell.
getHideMode
public int getHideMode()
Sets how a component that is hidden (not visible) should be treated by default. For a
more thorough explanation of what this constraint does see the white paper or cheat
Sheet at www.migcomponents.com.
Returns:
The mode:
0 == Normal. Bounds will be calculated as if the component was visible.
1 == If hidden the size will be 0, 0 but the gaps remain.
2 == If hidden the size will be 0, 0 and gaps set to zero.
3 == If hidden the component will be disregarded completely and not take up
a cell in the grid..
setHideMode
public void setHideMode(int mode)
Sets how a component that is hidden (not visible) should be treated by default.
Parameters:
mode - The mode:
0 == Normal. Bounds will be calculated as if the component was visible.
1 == If hidden the size will be 0, 0 but the gaps remain.
2 == If hidden the size will be 0, 0 and gaps set to zero.
3 == If hidden the component will be disregarded completely and not take up
a cell in the grid..
getId
public String getId()
Method Detail
1113
Returns the absolute resizing in the last stage of the layout cycle. May be null and
elements may be null.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value. null or of length 4.
setPadding
public void setPadding(UnitValue[] sides)
Sets the absolute resizing in the last stage of the layout cycle. These values are
added to the edges and can thus for instance be used to grow or reduce the size or
move the component an absolute number of pixels. May be null and elements may
be null.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
sides - top, left, bottom right. Must be null or of length 4.
getVisualPadding
public UnitValue[] getVisualPadding()
Returns the visual padding used when laying out this Component. May be null and
elements may be null.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value. null or of length 4.
setVisualPadding
public void setVisualPadding(UnitValue[] sides)
Sets the visual padding used when laying out this Component.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
sides
getSkip
public int getSkip()
Returns how many cells in the grid that should be skipped before the component that
this constraint belongs to.
Note that only the first component will be checked for this property.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value. 0 if no skip.
Method Detail
1114
Sets how many cells in the grid that should be skipped before the component that
this constraint belongs to.
Note that only the first component will be checked for this property.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- How many cells in the grid that should be skipped before the
component that this constraint belongs to
getSpanX
cells
Returns the number of cells the cell that this constraint's component will span in the
indicated dimension. 1 is default and means that it only spans the current cell.
LayoutUtil.INF is used to indicate a span to the end of the column/row.
Note that only the first component will be checked for this property.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value.
setSpanX
public void setSpanX(int cells)
Sets the number of cells the cell that this constraint's component will span in the
indicated dimension. 1 is default and means that it only spans the current cell.
LayoutUtil.INF is used to indicate a span to the end of the column/row.
Note that only the first component will be checked for this property.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
cells
getSpanY
public int getSpanY()
Returns the number of cells the cell that this constraint's component will span in the
indicated dimension. 1 is default and means that it only spans the current cell.
LayoutUtil.INF is used to indicate a span to the end of the column/row.
Note that only the first component will be checked for this property.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value.
setSpanY
public void setSpanY(int cells)
Sets the number of cells the cell that this constraint's component will span in the
indicated dimension. 1 is default and means that it only spans the current cell.
Method Detail
1115
Note that only the first component will be checked for this property.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
cells
getPushX
public Float getPushX()
"pushx" indicates that the column that this component is in (this first if the component
spans) should default to growing. If any other column has been set to grow this push
value on the component does nothing as the column's explicit grow weight will take
precedence. Push is normally used when the grid has not been defined in the layout.
If multiple components in a column has push weights set the largest one will be used
for the column.
Returns:
The current push value. Default is null.
setPushX
public void setPushX(Float weight)
"pushx" indicates that the column that this component is in (this first if the component
spans) should default to growing. If any other column has been set to grow this push
value on the component does nothing as the column's explicit grow weight will take
precedence. Push is normally used when the grid has not been defined in the layout.
If multiple components in a column has push weights set the largest one will be used
for the column.
Parameters:
weight
getPushY
public Float getPushY()
"pushx" indicates that the row that this component is in (this first if the component
spans) should default to growing. If any other row has been set to grow this push
value on the component does nothing as the row's explicit grow weight will take
precedence. Push is normally used when the grid has not been defined in the layout.
If multiple components in a row has push weights set the largest one will be used for
the row.
Returns:
The current push value. Default is null.
setPushY
public void setPushY(Float weight)
"pushx" indicates that the row that this component is in (this first if the component
spans) should default to growing. If any other row has been set to grow this push
value on the component does nothing as the row's explicit grow weight will take
precedence. Push is normally used when the grid has not been defined in the layout.
If multiple components in a row has push weights set the largest one will be used for
the row.
Parameters:
weight
Method Detail
1116
Returns in how many parts the current cell (that this constraint's component will be in)
should be split in. If for instance it is split in two, the next component will also share
the same cell. Note that the cell can also span a number of cells, which means that
you can for instance span three cells and split that big cell for two components. Split
can be set to a very high value to make all components in the same row/column
share the same cell (e.g. LayoutUtil.INF).
Note that only the first component will be checked for this property.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value.
setSplit
public void setSplit(int parts)
Sets in how many parts the current cell (that this constraint's component will be in)
should be split in. If for instance it is split in two, the next component will also share
the same cell. Note that the cell can also span a number of cells, which means that
you can for instance span three cells and split that big cell for two components. Split
can be set to a very high value to make all components in the same row/column
share the same cell (e.g. LayoutUtil.INF).
Note that only the first component will be checked for this property.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
parts
- The number of parts (i.e. component slots) the cell should be divided
into.
getTag
public String getTag()
Tags the component with metadata. Currently only used to tag buttons with for
instance "cancel" or "ok" to make them show up in the correct order depending on
platform. See PlatformDefaults.setButtonOrder(String) for information.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value. May be null.
setTag
public void setTag(String tag)
Optinal tag that gives more context to this constraint's component. It is for instance
used to tag buttons in a button bar with the button type such as "ok", "help" or
"cancel".
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
tag - The new tag. May be null.
Method Detail
1117
Returns if the flow should wrap to the next line/column after the component that this
constraint belongs to.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value.
setWrap
public void setWrap(boolean b)
Sets if the flow should wrap to the next line/column after the component that this
constraint belongs to.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
b - true means wrap after.
getWrapGapSize
public BoundSize getWrapGapSize()
Returns the wrap size if it is a custom size. If wrap was set to true with
setWrap(boolean) then this method will return null since that means that the gap
size should be the default one as defined in the rows spec.
Returns:
The custom gap size. NOTE! Will return null for both no wrap and default
wrap.
Since:
2.4.2
See Also:
isWrap(), setWrap(boolean)
setWrapGapSize
public void setWrapGapSize(BoundSize s)
Returns if the flow should wrap to the next line/column before the component that
this constraint belongs to.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
The current value.
Method Detail
1118
Sets if the flow should wrap to the next line/column before the component that this
constraint belongs to.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
b - true means wrap before.
getNewlineGapSize
public BoundSize getNewlineGapSize()
Returns the newline size if it is a custom size. If newline was set to true with
setNewline(boolean) then this method will return null since that means that the gap
size should be the default one as defined in the rows spec.
Returns:
The custom gap size. NOTE! Will return null for both no newline and default
newline.
Since:
2.4.2
See Also:
isNewline(), setNewline(boolean)
setNewlineGapSize
public void setNewlineGapSize(BoundSize s)
Method Detail
1119
Class BoundSize
java.lang.Object
com.codename1.ui.layouts.mig.BoundSize
public class
extends Object
A size that contains minimum, preferred and maximum size of type UnitValue.
This class is a simple value container and it is immutable.
If a size is missing (i.e., null) that boundary should be considered "not in use".
You can create a BoundSize from a String with the use of
ConstraintParser.parseBoundSize(String, boolean, boolean)
Field Summary
Modifier and Type Field and Description
static BoundSize
NULL_SIZE
static BoundSize
ZERO_PIXEL
Constructor Summary
Constructor and Description
BoundSize(UnitValue minMaxPref, String createString)
Constructor.
BoundSize(UnitValue min, UnitValue preferred, UnitValue max, String createString)
Constructor.
Method Summary
Modifier and
Type
int
boolean
UnitValue
UnitValue
UnitValue
If the size should be hinted as "pushing" and thus want to occupy free
space if noone else is claiming it.
getMax()
boolean
Class BoundSize
Returns if this bound size has no min, preferred and maximum size set
(they are all null)
1120
Field Detail
NULL_SIZE
public static final BoundSize NULL_SIZE
ZERO_PIXEL
public static final BoundSize ZERO_PIXEL
Constructor Detail
BoundSize
public BoundSize(UnitValue minMaxPref,
String createString)
Constructor. This method is here for serilization only and should normally not
be used. Use ConstraintParser.parseBoundSize(String, boolean, boolean)
instead.
Parameters:
min - The minimum size. May be null.
preferred - The preferred size. May be null.
max - The maximum size. May be null.
createString - The string used to create the BoundsSize.
BoundSize
public BoundSize(UnitValue min,
UnitValue preferred,
UnitValue max,
boolean gapPush,
String createString)
Constructor. This method is here for serilization only and should normally not
be used. Use ConstraintParser.parseBoundSize(String, boolean, boolean)
instead.
Parameters:
min - The minimum size. May be null.
preferred - The preferred size. May be null.
max - The maximum size. May be null.
gapPush - If the size should be hinted as "pushing" and thus want to occupy
free space if no one else is claiming it.
createString - The string used to create the BoundsSize.
Method Detail
1121
If the size should be hinted as "pushing" and thus want to occupy free space if noone
else is claiming it.
Returns:
The value.
isUnset
public boolean isUnset()
Returns if this bound size has no min, preferred and maximum size set (they are all
null)
Returns:
If unset.
constrain
public int constrain(int size,
float refValue,
ContainerWrapper parent)
Makes sure that size is within min and max of this size.
Parameters:
size - The size to constrain.
refValue - The reference to use for relative sizes.
parent - The parent container.
Returns:
The size, constrained within min and max.
Method Detail
1122
Class AC
java.lang.Object
com.codename1.ui.layouts.mig.AC
A constraint that holds the column or row constraints for the grid. It also holds the gaps between the
rows and columns.
This class is a holder and builder for a number of net.miginfocom.layout.DimConstraints.
For a more thorough explanation of what these constraints do, and how to build the constraints, see
the White Paper or Cheat Sheet at www.migcomponents.com.
Note that there are two way to build this constraint. Through String (e.g. "[100]3[200,fill]" or
through API (E.g. new AC().size("100").gap("3").size("200").fill().
Constructor Summary
Constructor and Description
AC()
Constructor.
Method Summary
Modifier and
Type
AC
AC
AC
AC
AC
AC
AC
AC
DimConstraint[]
int
Class AC
Specifies the gap size to be the default one AND moves to the next
column/row.
gap(String size)
Specifies the gap size to size AND moves to the next column/row.
gap(String size, int... indexes)
Property.
getCount()
1123
AC
AC
AC
AC
AC
AC
AC
void
that this
AC
AC
AC
AC
AC
Deprecated.
in 3.7.2. Use shrink(float) instead.
shrinkWeight(float w, int... indexes)
AC
AC
Deprecated.
in 3.7.2. Use shrink(float, int...) instead.
size(String s)
Specifies the current row/column's min and/or preferred and/or max size.
size(String size, int... indexes)
AC
AC
Specifies that the current row/column should be put in the size group s
and will thus share the same size constraints as the other components in
the group.
sizeGroup(String s)
AC
Specifies that the current row/column should be put in the size group s
and will thus share the same size constraints as the other components in
the group.
sizeGroup(String s, int... indexes)
AC
Method Summary
Specifies that the indicated rows/columns should be put in the size group
s and will thus share the same size constraints as the other components
in the group.
1124
Constructor Detail
AC
public AC()
Method Detail
getConstaints
public final DimConstraint[] getConstaints()
1125
noGrid
public final AC noGrid(int... indexes)
Specifies that the indicated rows/columns should not be grid-like. The while
row/colum will have its components layed out in one single cell. It is the same as to
say that the cells in this column/row will all be merged (a.k.a spanned).
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The index(es) (0-based) of the columns/rows that should be
affected by this constraint.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
index
indexes
Sets the current row/column to i. If the current number of rows/columns is less than i
a call to count(int) will set the size accordingly.
The next call to any of the constraint methods (e.g.
net.miginfocom.layout.AC#noGrid) will be carried out on this new row/column.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
i - The new current row/column.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
fill
public final AC fill()
Specifies that the current row/column's component should grow by default. It does not
affect the size of the row/column.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
fill
public final AC fill(int... indexes)
Specifies that the indicated rows'/columns' component should grow by default. It does
not affect the size of the row/column.
Method Detail
1126
Specifies that the current row/column should be put in the size group s and will thus
share the same size constraints as the other components in the group.
Same as sizeGroup("")
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
Since:
3.7.2
sizeGroup
public final AC sizeGroup(String s)
Specifies that the current row/column should be put in the size group s and will thus
share the same size constraints as the other components in the group.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
s - A name to associate on the group that should be the same for other
rows/columns in the same group.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
sizeGroup
public final AC sizeGroup(String s,
int... indexes)
Specifies that the indicated rows/columns should be put in the size group s and will
thus share the same size constraints as the other components in the group.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
s - A name to associate on the group that should be the same for other
rows/columns in the same group.
indexes - The index(es) (0-based) of the columns/rows that should be
affected by this constraint.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
size
public final AC size(String s)
Method Detail
1127
Specifies the indicated rows'/columns' min and/or preferred and/or max size. E.g.
"10px" or "50:100:200".
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The minimum and/or preferred and/or maximum size of this row. The
string will be interpreted as a BoundSize. For more info on how BoundSize
is formatted see the documentation.
indexes - The index(es) (0-based) of the columns/rows that should be
affected by this constraint.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
gap
size
Specifies the gap size to be the default one AND moves to the next column/row. The
method is called .gap() rather the more natural .next() to indicate that it is very
much related to the other .gap(..) methods.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
gap
public final AC gap(String size)
Specifies the gap size to size AND moves to the next column/row.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- minimum and/or preferred and/or maximum size of the gap between
this and the next row/column. The string will be interpreted as a BoundSize.
For more info on how BoundSize is formatted see the documentation.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
size
Method Detail
1128
Specifies the current row/column's columns default alignment for its components. It
does not affect the positioning or size of the columns/row itself. For columns it is the
horizonal alignment (e.g. "left") and for rows it is the vertical alignment (e.g. "top").
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
- The default side to align the components. E.g. "top" or "left", or
"leading" or "trailing" or "bottom" or "right".
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
align
side
Method Detail
1129
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
growPrio
public final AC growPrio(int p,
int... indexes)
Specifies the current row/column's grow weight within columns/rows with the grow
priority 100f.
Same as grow(100f)
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
Since:
3.7.2
grow
public final AC grow(float w)
Specifies the current row/column's grow weight within columns/rows with the same
grow priority.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
w - The new grow weight.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
grow
public final AC grow(float w,
int... indexes)
Specifies the indicated rows'/columns' grow weight within columns/rows with the
same grow priority.
For a more thorough explanation of what this constraint does see the white paper or
cheat Sheet at www.migcomponents.com.
Parameters:
w - The new grow weight.
Method Detail
1130
Specifies that the current row/column's shrink weight withing the columns/rows with
the shrink priority 100f.
Same as shrink(100f).
For a more thorough explanation of what this constraint does see the White Paper or
Cheat Sheet at www.migcomponents.com.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
Since:
3.7.2
shrink
public final AC shrink(float w)
Specifies that the current row/column's shrink weight withing the columns/rows with
the same shrink priority.
For a more thorough explanation of what this constraint does see the White Paper or
Cheat Sheet at www.migcomponents.com.
Parameters:
w - The shrink weight.
Returns:
Method Detail
1131
Since:
3.7.2
shrink
public final AC shrink(float w,
int... indexes)
Specifies the indicated rows'/columns' shrink weight withing the columns/rows with
the same shrink priority.
For a more thorough explanation of what this constraint does see the White Paper or
Cheat Sheet at www.migcomponents.com.
Parameters:
w - The shrink weight.
indexes - The index(es) (0-based) of the columns/rows that should be
affected by this constraint.
Returns:
this so it is possible to chain calls. E.g. new
AxisConstraint().noGrid().gap().fill().
Since:
3.7.2
shrinkWeight
public final AC shrinkWeight(float w)
Method Detail
1132
Class LayoutStyle
java.lang.Object
com.codename1.ui.layouts.LayoutStyle
public class
extends Object
LayoutStyle is used to determine how much space to place between components during layout.
LayoutStyle can be obtained for two components, or for a component relative to an edge of a parent
container. The amount of space can vary depending upon whether or not the components are
logically grouped together (RELATED).
This class is primarily useful for JREs prior to 1.6. In 1.6 API for this was added to Swing. When run
on a JRE of 1.6 or greater this will call into the appropriate methods in Swing.
Version:
$Revision: 1.10 $
Field Summary
Modifier and Type
static int
static int
static int
Constructor Summary
Constructor and Description
LayoutStyle()
Method Summary
Modifier and
Type
int
Class LayoutStyle
getSharedInstance()
Sets the LayoutStyle instance to use for this look and feel.
1133
Field Detail
RELATED
public static final int RELATED
Possible argument to getPreferredGap. Used to indicate the two components are not
grouped together.
See Also:
Constant Field Values
INDENT
public static final int INDENT
Constructor Detail
LayoutStyle
public LayoutStyle()
Method Detail
setSharedInstance
public static void setSharedInstance(LayoutStyle layout)
Sets the LayoutStyle instance to use for this look and feel. You generally don't need
to invoke this, instead use the getter which will return the LayoutStyle appropriate for
the current look and feel.
Parameters:
layout - the LayoutStyle to use; a value of null indicates the default should be
used
getSharedInstance
public static LayoutStyle getSharedInstance()
Factory methods for obtaining the current LayoutStyle object appropriate for the
current look and feel.
Returns:
the current LayoutStyle instance
1134
Returns the amount of space to use between two components. The return value
indicates the distance to place component2 relative to component1. For example, the
following returns the amount of space to place between component2 and component1
when component2 is placed vertically above component1:
int gap = getPreferredGap(component1, component2,
LayoutStyle.RELATED,
SwingConstants.NORTH, parent);
The type parameter indicates the type of gap being requested. It can be one of the
following values:
If the two components will be contained in the same parent and are
showing similar logically related items, use RELATED.
If the two components will be contained in the same parent but show
UNRELATED
logically unrelated items use UNRELATED.
Used to obtain the preferred distance to indent a component relative to
INDENT
another. For example, if you want to horizontally indent a JCheckBox
relative to a JLabel use INDENT. This is only useful for the horizontal axis.
It's important to note that some look and feels may not distinguish between RELATED
and UNRELATED.
RELATED
The return value is not intended to take into account the current size and position of
component2 or component1. The return value may take into consideration various
properties of the components. For example, the space may vary based on font size,
or the preferred size of the component.
Parameters:
component1 - the JComponent component2 is being placed relative to
component2 - the JComponent being placed
type - how the two components are being placed
position - the position component2 is being placed relative to component1;
one of SwingConstants.NORTH, SwingConstants.SOUTH, SwingConstants.EAST
or SwingConstants.WEST
parent - the parent of component2; this may differ from the actual parent and
may be null
Returns:
the amount of space to place between the two components
Throws:
IllegalArgumentException - if position is not one of SwingConstants.NORTH,
SwingConstants.SOUTH, SwingConstants.EAST or SwingConstants.WEST; type
not one of INDENT, RELATED or UNRELATED; or component1 or component2 is null
getContainerGap
public int getContainerGap(Component component,
int position,
Container parent)
Method Detail
1135
Method Detail
1136
Class Layout
java.lang.Object
com.codename1.ui.layouts.Layout
Direct Known Subclasses:
BorderLayout, BoxLayout, CoordinateLayout, FlowLayout, GridBagLayout, GridLayout,
GroupLayout, LayeredLayout, MigLayout, TableLayout
Abstract class that can be used to arrange components in a container using a predefined algorithm.
This class may be implemented externally and is similar in spirit to the AWT/Swing layout managers.
Constructor Summary
Constructor and Description
Layout()
Method Summary
Modifier and
Type
Some layouts can optionally track the addition of elements with meta-data
that allows the user to "hint" on object positioning.
void
boolean
equals(Object o)
Object
abstract
Dimension
getPreferredSize(Container parent)
int
boolean
boolean
abstract void
boolean
Some layout managers can obscure their child components in some cases
this returns true if the basic underpinnings are in place for that.
removeLayoutComponent(Component comp)
Removes the component from the layout this operation is only useful if the
layout maintains references to components within it
void
Class Layout
1137
Detail
Layout
public Layout()
Method Detail
layoutContainer
public abstract void layoutContainer(Container parent)
Some layouts can optionally track the addition of elements with meta-data that allows
the user to "hint" on object positioning.
Parameters:
value - optional meta data information, like alignment orientation
comp - the added component to the layout
c - the parent container
removeLayoutComponent
public void removeLayoutComponent(Component comp)
Removes the component from the layout this operation is only useful if the layout
maintains references to components within it
Parameters:
comp - the removed component from layout
getComponentConstraint
public Object getComponentConstraint(Component comp)
Constructor Detail
1138
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Object
hashCode
public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of
hashtables such as those provided by java.util.Hashtable. The general contract of
hashCode is: Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application. If two objects are equal
according to the equals(Object) method, then calling the hashCode method on each
of the two objects must produce the same integer result. It is not required that if two
objects are unequal according to the equals(java.lang.Object) method, then calling
the hashCode method on each of the two objects must produce distinct integer
results. However, the programmer should be aware that producing distinct integer
results for unequal objects may improve the performance of hashtables. As much as
is reasonably practical, the hashCode method defined by class Object does return
distinct integers for distinct objects. (This is typically implemented by converting the
internal address of the object into an integer, but this implementation technique is not
required by the JavaTM programming language.)
Overrides:
hashCode in class Object
isConstraintTracking
public boolean isConstraintTracking()
If this method returns true, the addLayoutComponent method will be called when
replacing a layout for every component within the container
Returns:
false by default
obscuresPotential
public boolean obscuresPotential(Container parent)
Some layout managers can obscure their child components in some cases this
returns true if the basic underpinnings are in place for that. This method doesn't take
padding/margin etc. into account since that is checked by the caller
Parameters:
parent - parent container
Returns:
true if there is a chance that this layout manager can fully obscure the
background, when in doubt return false...
Method Detail
1139
Class LayeredLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.layouts.LayeredLayout
public class
extends Layout
The LayeredLayout places the components in order one on top of the other and sizes them all to the
size of the largest component. This is useful when trying to create an overlay on top of an existing
component. E.g. an "x" button to allow removing the component as shown here
The code to generate this UI is slightly complex and contains very little relevant pieces. The only truly
relevant piece the last line of code:
*
Form hi = new Form("Layered Layout");
int w = Math.min(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayHeight());
Button settingsLabel = new Button("");
Style settingsStyle = settingsLabel.getAllStyles();
settingsStyle.setFgColor(0xff);
settingsStyle.setBorder(null);
settingsStyle.setBgColor(0xff00);
settingsStyle.setBgTransparency(255);
settingsStyle.setFont(settingsLabel.getUnselectedStyle().getFont().derive(w / 3, Font.STYLE_PLAIN));
FontImage.setMaterialIcon(settingsLabel, FontImage.MATERIAL_SETTINGS);
Button close = new Button("");
close.setUIID("Container");
close.getAllStyles().setFgColor(0xff0000);
FontImage.setMaterialIcon(close, FontImage.MATERIAL_CLOSE);
hi.add(LayeredLayout.encloseIn(settingsLabel,
FlowLayout.encloseRight(close)));
Class LayeredLayout
1140
Style s = UIManager.getInstance().getComponentStyle("Button");
FontImage radioEmptyImage = FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_UNCHECKED, s);
FontImage radioFullImage = FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_CHECKED, s);
((DefaultLookAndFeel)UIManager.getInstance().getLookAndFeel()).setRadioButtonImages(radioFullImage, radioEmptyImage, r
Container container1 = BoxLayout.encloseY(new Label("Swipe the tab to see more"),
new Label("You can put anything here"));
t.addTab("Tab1", container1);
t.addTab("Tab2", new SpanLabel("Some text directly in the tab"));
RadioButton firstTab = new RadioButton("");
RadioButton secondTab = new RadioButton("");
firstTab.setUIID("Container");
secondTab.setUIID("Container");
new ButtonGroup(firstTab, secondTab);
firstTab.setSelected(true);
Container tabsFlow = FlowLayout.encloseCenter(firstTab, secondTab);
hi.add(t);
hi.add(BorderLayout.south(tabsFlow));
t.addSelectionListener((i1, i2) -> {
switch(i2) {
case 0:
if(!firstTab.isSelected()) {
firstTab.setSelected(true);
}
break;
case 1:
if(!secondTab.isSelected()) {
secondTab.setSelected(true);
}
break;
}
});
Class LayeredLayout
1141
Constructor Summary
Constructor and Description
LayeredLayout()
Method Summary
Modifier and
Type
static
Container
Dimension
boolean
void
boolean
String
Some layout managers can obscure their child components in some cases
this returns true if the basic underpinnings are in place for that.
toString()
Constructor Detail
LayeredLayout
public LayeredLayout()
Method Detail
Constructor Summary
1142
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
isOverlapSupported
public boolean isOverlapSupported()
Some layout managers can obscure their child components in some cases this
returns true if the basic underpinnings are in place for that. This method doesn't take
padding/margin etc. into account since that is checked by the caller
Overrides:
obscuresPotential in class Layout
Parameters:
parent - parent container
Returns:
true if there is a chance that this layout manager can fully obscure the
background, when in doubt return false...
encloseIn
public static Container encloseIn(Component... cmps)
Method Detail
1143
Class Insets
java.lang.Object
com.codename1.ui.layouts.Insets
public class
extends Object
Port of Insets from Harmony for the use of the GridBag code
Field Summary
Modifier and Type Field and Description
int
bottom
int
left
int
right
int
top
Constructor Summary
Constructor and Description
Insets(int top, int left, int bottom, int right)
Method Summary
Modifier and Type
Object
boolean
equals(Object o)
int
void
String
Field Detail
top
public int top
left
public int left
Class Insets
1144
right
public int right
Constructor Detail
Insets
public Insets(int
int
int
int
top,
left,
bottom,
right)
Method Detail
hashCode
public int hashCode()
equals
public boolean equals(Object o)
Field Detail
1145
Method Detail
top,
left,
bottom,
right)
1146
Class GroupLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.layouts.GroupLayout
public class
extends Layout
GroupLayout is a LayoutManager that hierarchically groups components to achieve common, and not
so common, layouts. Grouping is done by instances of the Group class. GroupLayout supports two
types of groups:
Sequential: A sequential group positions its child elements sequentially, one after another.
Parallel:
A parallel group positions its child elements in the same space on top of each other.
Parallel groups can also align the child elements along their baseline.
Each Group can contain any number of child groups, Components or gaps. GroupLayout treats each
axis independently. That is, there is a group representing the horizontal axis, and a separate group
representing the vertical axis. The horizontal group is responsible for setting the x and width of its
contents, where as the vertical group is responsible for setting the y and height of its contents.
The following code builds a simple layout consisting of two labels in one column, followed by two
textfields in the next column:
Container panel = ...;
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
layout.setAutocreateGaps(true);
layout.setAutocreateContainerGaps(true);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.add(layout.createParallelGroup().add(label1).add(label2)).
add(layout.createParallelGroup().add(tf1).add(tf2));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.add(layout.createParallelGroup(GroupLayout.BASELINE).add(label1).add(tf1)).
add(layout.createParallelGroup(GroupLayout.BASELINE).add(label2).add(tf2));
layout.setVerticalGroup(vGroup);
Class GroupLayout
1147
Class Summary
Modifier
and Type
Group provides for commonality between the two types of operations supported
by GroupLayout: laying out components one after another (SequentialGroup) or
layout on top of each other (ParallelGroup).
class
class
GroupLayout.ParallelGroup
A Group that lays out its elements
class
GroupLayout.SequentialGroup
A Group that lays out its elements
Field Summary
Modifier and Type
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
Constructor Summary
Constructor and Description
GroupLayout(Container host)
Method Summary
Modifier and Type
GroupLayout.ParallelGroup
it's
1148
createParallelGroup()
Creates and returns a ParallelGroup
with a LEADING
alignment.
GroupLayout.ParallelGroup
createParallelGroup(int alignment)
Creates and returns an ParallelGroup.
GroupLayout.ParallelGroup
GroupLayout.SequentialGroup
createSequentialGroup()
Creates and returns a SequentialGroup.
getAutocreateContainerGaps()
boolean
boolean
boolean
GroupLayout.Group
horizontal axis.
LayoutStyle
Dimension
GroupLayout.Group
getLayoutStyle()
void
layoutContainer(Container parent)
from the
parent container.
void
replace(Component existingComponent,
Component newComponent)
void
void
void
void
void
the
horizontal axis.
void
void
Method Summary
setLayoutStyle(LayoutStyle layoutStyle)
1149
String
Field Detail
NORTH
public static final int NORTH
Possible argument when linking sizes of components. Specifies the the two
component should share the same size along the horizontal axis.
See Also:
linkSize(Component[], int), Constant Field Values
VERTICAL
public static final int VERTICAL
Possible argument when linking sizes of components. Specifies the the two
component should share the same size along the vertical axis.
See Also:
linkSize(Component[],int), Constant Field Values
1150
Possible alignment type. Indicates the elements should be aligned to the origin. For
the horizontal axis with a left to right orientation this means aligned to the left.
See Also:
createParallelGroup(int), Constant Field Values
TRAILING
public static final int TRAILING
Possible alignment type. Indicates the elements should be aligned to the end. For the
horizontal axis with a left to right orientation this means aligned to the right.
See Also:
createParallelGroup(int), Constant Field Values
CENTER
public static final int CENTER
Possible alignment type. Indicates the elements should centered in the spaced
provided.
See Also:
createParallelGroup(int), Constant Field Values
BASELINE
public static final int BASELINE
Possible alignment type. Indicates the elements should aligned along their baseline.
See Also:
createParallelGroup(int), Constant Field Values
DEFAULT_SIZE
public static final int DEFAULT_SIZE
Possible value for the add methods that takes a Component. Indicates the size from
the component should be used.
See Also:
Constant Field Values
PREFERRED_SIZE
public static final int PREFERRED_SIZE
Possible value for the add methods that takes a Component. Indicates the preferred
size should be used.
See Also:
Constant Field Values
Constructor Detail
GroupLayout
public GroupLayout(Container host)
Method Detail
Field Detail
1151
setHonorsVisibility(Component,Boolean)
getHonorsVisibility
public boolean getHonorsVisibility()
Sets whether the component's visibility is considered for sizing and positioning. A
value of Boolean.TRUE indicates that if component is not visible it should not be treated
as part of the layout. A value of false indicates that component is positioned and
sized regardless of it's visibility. A value of null indicates the value specified by the
single argument method setHonorsVisibility should be used.
If component is not a child of the Container this GroupLayout is managing, it will be
added to the Container.
Parameters:
component - the component
honorsVisibility - whether component's
- if component is null
See Also:
setHonorsVisibility(boolean)
toString
public String toString()
Returns a textual description of this GroupLayout. The return value is intended for
debugging purposes only.
Overrides:
toString in class Object
Returns:
textual description of this GroupLayout
Method Detail
1152
Sets whether or not a gap between components should automatically be created. For
example, if this is true and you add two components to a SequentialGroup a gap
between the two will automatically be created. The default is false.
Parameters:
autocreatePadding - whether or not to automatically created a gap between
components and the container
getAutocreateGaps
public boolean getAutocreateGaps()
Sets whether or not gaps between the container and the first/last components should
automatically be created. The default is false.
Parameters:
autocreatePadding - whether or not to automatically create gaps between the
container and first/last components.
getAutocreateContainerGaps
public boolean getAutocreateContainerGaps()
Returns whether or not gaps between the container and the first/last components
should automatically be created. The default is false.
Returns:
whether or not the gaps between the container and the first/last components
should automatically be created
setHorizontalGroup
public void setHorizontalGroup(GroupLayout.Group group)
Sets the Group that is responsible for layout along the horizontal axis.
Parameters:
group - Group responsible for layout along the horizontal axis
Throws:
IllegalArgumentException - if group is null
getHorizontalGroup
public GroupLayout.Group getHorizontalGroup()
Returns the Group that is responsible for layout along the horizontal axis.
Returns:
ParallelGroup responsible for layout along the horizontal axis.
setVerticalGroup
public void setVerticalGroup(GroupLayout.Group group)
Sets the Group that is responsible for layout along the vertical axis.
Parameters:
group - Group responsible for layout along the vertical axis.
Throws:
IllegalArgumentException - if group is null.
getVerticalGroup
public GroupLayout.Group getVerticalGroup()
Returns the ParallelGroup that is responsible for layout along the vertical axis.
Returns:
ParallelGroup responsible for layout along the vertical axis.
Method Detail
1153
createParallelGroup
public GroupLayout.ParallelGroup createParallelGroup(int alignment)
Creates and returns a ParallelGroup that aligns it's elements along the baseline.
Parameters:
resizable - whether the group is resizable
anchorBaselineToTop - whether the baseline is anchored to the top or bottom
of the group
Returns:
parallel group
See Also:
Method Detail
1154
linkSize
public void linkSize(Component[] components)
Forces the set of components to have the same size. This can be used multiple times
to force any number of components to share the same size.
Linked Components are not be resizable.
Parameters:
components
Throws:
IllegalArgumentException
linkSize
public void linkSize(Component[] components,
int axis)
Forces the set of components to have the same size. This can be used multiple times
to force any number of components to share the same size.
Linked Components are not be resizable.
Parameters:
components - Components to force to have same size.
axis - Axis to bind size, one of HORIZONTAL, VERTICAL
or HORIZONTAL |
VERTICAL
Throws:
IllegalArgumentException
IllegalArgumentException
replace
public void replace(Component existingComponent,
Component newComponent)
Sets the LayoutStyle this GroupLayout is to use. A value of null can be used to
indicate the shared instance of LayoutStyle should be used.
Parameters:
layoutStyle - the LayoutStyle to use
getLayoutStyle
public LayoutStyle getLayoutStyle()
Notification that a Component has been removed from the parent container. You
should not invoke this method directly, instead invoke removeComponent on the parent
Container.
Overrides:
Method Detail
1155
in class Layout
Parameters:
component
See Also:
Container.removeComponent(com.codename1.ui.Component)
getPreferredSize
public Dimension getPreferredSize(Container parent)
layoutContainer
public void layoutContainer(Container parent)
Method Detail
1156
Class GroupLayout.SequentialGroup
java.lang.Object
com.codename1.ui.layouts.GroupLayout.Group
com.codename1.ui.layouts.GroupLayout.SequentialGroup
Enclosing class:
GroupLayout
public class
extends GroupLayout.Group
A Group that lays out its elements sequentially, one after another. This class has no public
constructor, use the createSequentialGroup method to create one.
See Also:
GroupLayout.createSequentialGroup()
Method Summary
Modifier and Type
GroupLayout.SequentialGroup
GroupLayout.SequentialGroup
add(GroupLayout.Group group)
Adds the specified Group to this SequentialGroup
GroupLayout.SequentialGroup
GroupLayout.SequentialGroup
add(int pref)
GroupLayout.SequentialGroup
GroupLayout.SequentialGroup
GroupLayout.SequentialGroup
GroupLayout.SequentialGroup
GroupLayout.SequentialGroup
GroupLayout.SequentialGroup
Class GroupLayout.SequentialGroup
1157
Method Detail
add
public GroupLayout.SequentialGroup add(GroupLayout.Group group)
Adds the specified Component. If the Component's min/max are different from its pref
than the component will be resizable.
Parameters:
component - the Component to add
Returns:
this SequentialGroup
add
public GroupLayout.SequentialGroup add(boolean useAsBaseline,
Component component)
Adds the specified Component. Min, pref and max can be absolute values, or they can
be one of DEFAULT_SIZE or PREFERRED_SIZE. For example, the following:
add(component, PREFERRED_SIZE, PREFERRED_SIZE, 1000);
Forces a max of 1000, with the min and preferred equalling that of the preferred size
of component.
Parameters:
1158
to add
Returns:
this SequentialGroup
Throws:
- if min, pref or max are not positive and not one
of PREFERRED_SIZE or DEFAULT_SIZE
IllegalArgumentException
add
public GroupLayout.SequentialGroup add(boolean useAsBaseline,
Component component,
int min,
int pref,
int max)
add
public GroupLayout.SequentialGroup add(int min,
int pref,
int max)
Adds an element representing the preferred gap between the two components.
Parameters:
comp1 - the first component
comp2 - the second component
type - the type of gap; one of the constants defined by LayoutStyle
Returns:
this SequentialGroup
Method Detail
1159
See Also:
LayoutStyle
addPreferredGap
public GroupLayout.SequentialGroup addPreferredGap(Component comp1,
Component comp2,
int type,
boolean canGrow)
Adds an element representing the preferred gap between the two components.
Parameters:
comp1 - the first component
comp2 - the second component
type - the type of gap; one of the constants defined by LayoutStyle
canGrow - true if the gap can grow if more space is available
Returns:
this SequentialGroup
Throws:
IllegalArgumentException - if type is not a valid LayoutStyle constant
See Also:
LayoutStyle
addPreferredGap
public GroupLayout.SequentialGroup addPreferredGap(int type)
Adds an element representing the preferred gap between the nearest components.
That is, during layout the neighboring components are found, and the min, pref and
max of this element is set based on the preferred gap between the components. If no
neighboring components are found the min, pref and max are set to 0.
Parameters:
type - the type of gap; one of the LayoutStyle constants
Returns:
this SequentialGroup
Throws:
IllegalArgumentException - if type is not one of LayoutStyle.RELATED or
LayoutStyle.UNRELATED
See Also:
LayoutStyle
addPreferredGap
public GroupLayout.SequentialGroup addPreferredGap(int type,
int pref,
int max)
Adds an element for the preferred gap between the nearest components. That is,
during layout the neighboring components are found, and the min of this element is
set based on the preferred gap between the components. If no neighboring
components are found the min is set to 0. This method allows you to specify the
preferred and maximum size by way of the pref and max arguments. These can either
be a value >= 0, in which case the preferred or max is the max of the argument and
the preferred gap, of DEFAULT_VALUE in which case the value is the same as the
preferred gap.
Parameters:
type - the type of gap; one of LayoutStyle.RELATED or
LayoutStyle.UNRELATED
pref - the preferred size; one of DEFAULT_SIZE or a value > 0
max - the maximum size; one of DEFAULT_SIZE, PREFERRED_SIZE or a
value > 0
Returns:
this SequentialGroup
Throws:
IllegalArgumentException - if type is not one of LayoutStyle.RELATED or
LayoutStyle.UNRELATED or pref/max is != DEFAULT_SIZE and < 0, or pref >
max
See Also:
LayoutStyle
Method Detail
1160
Adds an element representing the preferred gap between one edge of the container
and the next/previous Component. This will have no effect if the next/previous
element is not a Component and does not touch one edge of the parent container.
Returns:
this SequentialGroup.
addContainerGap
public GroupLayout.SequentialGroup addContainerGap(int pref,
int max)
Adds an element representing the preferred gap between one edge of the container
and the next/previous Component. This will have no effect if the next/previous
element is not a Component and does not touch one edge of the parent container.
Parameters:
pref - the preferred size; one of DEFAULT_SIZE or a value > 0
max - the maximum size; one of DEFAULT_SIZE, PREFERRED_SIZE or a
value > 0.
Returns:
this SequentialGroup
Throws:
IllegalArgumentException - if pref/max is != DEFAULT_SIZE and < 0, or
pref > max
Method Detail
1161
Class GroupLayout.ParallelGroup
java.lang.Object
com.codename1.ui.layouts.GroupLayout.Group
com.codename1.ui.layouts.GroupLayout.ParallelGroup
Enclosing class:
GroupLayout
public class
extends GroupLayout.Group
A Group that lays out its elements on top of each other. If a child element is smaller than the provided
space it is aligned based on the alignment of the child (if specified) or on the alignment of the
ParallelGroup.
See Also:
GroupLayout.createParallelGroup()
Method Summary
Modifier and Type
GroupLayout.ParallelGroup
GroupLayout.ParallelGroup
GroupLayout.ParallelGroup
add(GroupLayout.Group group)
Adds the specified Group.
GroupLayout.ParallelGroup
GroupLayout.ParallelGroup
add(int pref)
Method Detail
add
public GroupLayout.ParallelGroup add(GroupLayout.Group group)
Class GroupLayout.ParallelGroup
1162
Adds the specified Component. If the Component's min/max are different from its pref
than the component will be resizable.
Parameters:
component - the Component to add
Returns:
this ParallelGroup
add
public GroupLayout.ParallelGroup add(Component component,
int min,
int pref,
int max)
Adds the specified Component. Min, pref and max can be absolute values, or they can
be one of DEFAULT_SIZE or PREFERRED_SIZE. For example, the following:
add(component, PREFERRED_SIZE, PREFERRED_SIZE, 1000);
Forces a max of 1000, with the min and preferred equalling that of the preferred size
of component.
Parameters:
component - the Component to add
min - the minimum size
pref - the preferred size
max - the maximum size
Returns:
this SequentialGroup
Throws:
IllegalArgumentException - if min, pref or max are not positive and not one
of PREFERRED_SIZE or DEFAULT_SIZE.
add
public GroupLayout.ParallelGroup add(int pref)
add
public GroupLayout.ParallelGroup add(int min,
int pref,
int max)
Method Detail
1163
add
public GroupLayout.ParallelGroup add(int alignment,
Component component)
Adds the specified Component. If the Component's min/max are different from its pref
than the component will be resizable.
Parameters:
alignment - the alignment for the component
component - the Component to add
Returns:
this Group
Throws:
IllegalArgumentException - if alignment is not one of LEADING, TRAILING or
CENTER
add
public GroupLayout.ParallelGroup add(int alignment,
Component component,
int min,
int pref,
int max)
Adds the specified Component. Min, pref and max can be absolute values, or they can
be one of DEFAULT_SIZE or PREFERRED_SIZE. For example, the following:
add(component, PREFERRED_SIZE, PREFERRED_SIZE, 1000);
Forces a max of 1000, with the min and preferred equalling that of the preferred size
of component.
Parameters:
alignment - the alignment for the component.
component - the Component to add
min - the minimum size
pref - the preferred size
max - the maximum size
Returns:
this Group
Throws:
IllegalArgumentException - if min, pref or max are not positive and not one
of PREFERRED_SIZE or DEFAULT_SIZE.
Method Detail
1164
Class GroupLayout.Group
java.lang.Object
com.codename1.ui.layouts.GroupLayout.Group
Direct Known Subclasses:
GroupLayout.ParallelGroup, GroupLayout.SequentialGroup
Enclosing class:
GroupLayout
Group provides for commonality between the two types of operations supported by GroupLayout:
laying out components one after another (SequentialGroup) or layout on top of each other
(ParallelGroup). Use one of createSequentialGroup or createParallelGroup to create one.
Method Summary
Class GroupLayout.Group
1165
Class GridLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.layouts.GridLayout
public class
extends Layout
The components are arranged in a grid based on available space, all cells in the grid are given
exactly the same size which matches the largest preferred size or available space. The main use
case for this layout is a grid of icons e.g. like one would see in the iPhone home screen.
If the number of rows * columns is smaller than the number of components added a new row is
implicitly added to the grid. However, if the number of components is smaller than available cells
(won't fill the last row) blank spaces will be left in place.
In this example we can see that a 2x2 grid is used to add 5 elements, this results in an additional row
that's implicitly added turning the grid to a 3x2 grid implicitly and leaving one blank cell.
Form hi = new Form("Grid Layout 2x2", new GridLayout(2, 2));
hi.add(new Label("First")).
add(new Label("Second")).
add(new Label("Third")).
add(new Label("Fourth")).
add(new Label("Fifth"));
When we use a 2x4 size ratio we would see elements getting cropped as we do here. The grid layout
uses the grid size first and doesn't pay too much attention to the preferred size of the components it
holds.
1166
Grid also has an autoFit attribute that can be used to automatically calculate the column count based
on available space and preferred width. This is really useful for working with UI's where the device
orientation might change.
There is also a terse syntax for working with a grid that has two versions, one that uses the "auto fit"
option and another that accepts the column names. Heres a sample of the terse syntax coupled with
the auto fit screenshots of the same code in two orientations:
GridLayout.encloseIn(new Label("First"),
new Label("Second"),
new Label("Third"),
new Label("Fourth"),
new Label("Fifth")));
Class GridLayout
1167
Constructor Summary
Constructor and Description
GridLayout(int columns)
Creates a new instance of GridLayout with the given columns, rows is set to 1 but will
implicitly grow if more components are added
GridLayout(int rows, int columns)
Creates a new instance of GridLayout with the given rows and columns
Method Summary
Modifier and
Type
static
GridLayout
static
Container
static
Container
boolean
int
Dimension
int
boolean
Creates a new container with an auto fit grid layout and the components
added to it
encloseIn(int columns, Component... cmp)
Creates a new container with the grid layout and the components added to it
equals(Object o)
boolean
void
When set to true makes the grid layout fill the last row of the layout entirely if
the number of elements in that row is bigger.
layoutContainer(Container parent)
boolean
void
Constructor Summary
Some layout managers can obscure their child components in some cases
this returns true if the basic underpinnings are in place for that.
setAutoFit(boolean autoFit)
1168
When set to true makes the grid layout fill the last row of the layout entirely if
the number of elements in that row is bigger.
void
toString()
String
Constructor Detail
GridLayout
public GridLayout(int rows,
int columns)
Creates a new instance of GridLayout with the given rows and columns
Parameters:
rows - - number of rows.
columns - - number of columns.
Throws:
IllegalArgumentException - if rows < 1 or columns < 1
GridLayout
public GridLayout(int columns)
Creates a new instance of GridLayout with the given columns, rows is set to 1 but will
implicitly grow if more components are added
Parameters:
columns - - number of columns.
Throws:
IllegalArgumentException - if rows < 1 or columns < 1
Method Detail
autoFit
public static GridLayout autoFit()
Returns a grid layout that implicitly auto-fits to width in term of number of columns
Returns:
a grid layout that automatically adapts its size
encloseIn
public static Container encloseIn(Component... cmp)
Creates a new container with an auto fit grid layout and the components added to it
Parameters:
cmp - the components
Returns:
a new container
encloseIn
public static Container encloseIn(int columns,
Component... cmp)
Creates a new container with the grid layout and the components added to it
Method Summary
1169
Returns:
a new container
layoutContainer
public void layoutContainer(Container parent)
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
getRows
public int getRows()
Returns:
the rows
getColumns
public int getColumns()
Returns:
the columns
equals
public boolean equals(Object o)
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Method Detail
1170
in class Layout
isFillLastRow
public boolean isFillLastRow()
When set to true makes the grid layout fill the last row of the layout entirely if the
number of elements in that row is bigger.
Returns:
the fillLastRow
setFillLastRow
public void setFillLastRow(boolean fillLastRow)
When set to true makes the grid layout fill the last row of the layout entirely if the
number of elements in that row is bigger.
Parameters:
fillLastRow - the fillLastRow to set
isAutoFit
public boolean isAutoFit()
Some layout managers can obscure their child components in some cases this
returns true if the basic underpinnings are in place for that. This method doesn't take
padding/margin etc. into account since that is checked by the caller
Overrides:
obscuresPotential in class Layout
Parameters:
parent - parent container
Returns:
true if there is a chance that this layout manager can fully obscure the
background, when in doubt return false...
Method Detail
1171
Class GridBagLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.layouts.GridBagLayout
public class
extends Layout
Codename One port of the infamous GridBagLayout based on the Apache Harmony code. For new
applications we generally recommend a "native" Codename One layout such as TableLayout and
recommend avoiding this layout. Its here for developers who are accustomed to it and need to port
existing code.
Button button;
hi.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
Class GridBagLayout
1172
Field Summary
Field and
Description
columnWeights
int[]
columnWidths
protected Hashtable<Component,GridBagConstraints>
comptable
protected GridBagConstraints
defaultConstraints
protected com.codename1.ui.layouts.GridBagLayoutInfo
layoutInfo
MAXGRIDSIZE
MINSIZE
PREFERREDSIZE
int[]
rowHeights
double[]
rowWeights
Constructor Summary
Constructor and Description
GridBagLayout()
Method Summary
Modifier and Type
void
protected void
adjustForGravity(GridBagConstraints constraints,
Rectangle r)
protected void
AdjustForGravity(GridBagConstraints constraints,
Rectangle r)
protected void
arrangeGrid(Container parent)
protected void
ArrangeGrid(Container parent)
Object
Field Summary
getComponentConstraint(Component comp)
1173
getLayoutDimensions()
double[][]
getLayoutWeights()
Dimension
void
getPreferredSize(Container parent)
void
protected
GridBagConstraints
lookupConstraints(Component comp)
removeLayoutComponent(Component comp)
void
setConstraints(Component comp,
GridBagConstraints constraints)
void
Field Detail
MAXGRIDSIZE
protected static final int MAXGRIDSIZE
See Also:
Constant Field Values
MINSIZE
protected static final int MINSIZE
See Also:
Constant Field Values
PREFERREDSIZE
protected static final int PREFERREDSIZE
See Also:
Constant Field Values
comptable
protected volatile Hashtable<Component,GridBagConstraints> comptable
defaultConstraints
protected volatile GridBagConstraints defaultConstraints
layoutInfo
protected volatile com.codename1.ui.layouts.GridBagLayoutInfo layoutInfo
columnWeights
public volatile double[] columnWeights
rowWeights
public volatile double[] rowWeights
Method Summary
1174
rowHeights
public volatile int[] rowHeights
Constructor Detail
GridBagLayout
public GridBagLayout()
Method Detail
addLayoutComponent
public void addLayoutComponent(Object constraints,
Component comp,
Container c)
invalidateLayout
public void invalidateLayout(Container target)
getPreferredSize
public Dimension getPreferredSize(Container parent)
Field Detail
1175
getLayoutWeights
public double[][] getLayoutWeights()
ArrangeGrid
protected void ArrangeGrid(Container parent)
lookupConstraints
protected GridBagConstraints lookupConstraints(Component comp)
adjustForGravity
protected void adjustForGravity(GridBagConstraints constraints,
Rectangle r)
arrangeGrid
protected void arrangeGrid(Container parent)
AdjustForGravity
protected void AdjustForGravity(GridBagConstraints constraints,
Rectangle r)
Method Detail
1176
Class GridBagConstraints
java.lang.Object
com.codename1.ui.layouts.GridBagConstraints
public class
extends Object
Field Summary
Modifier and Type Field and Description
int
anchor
static int
BOTH
static int
CENTER
static int
EAST
int
fill
static int
FIRST_LINE_END
static int
FIRST_LINE_START
int
gridheight
int
gridwidth
int
gridx
int
gridy
static int
HORIZONTAL
Insets
insets
int
ipadx
int
ipady
static int
LAST_LINE_END
static int
LAST_LINE_START
static int
LINE_END
static int
LINE_START
static int
NONE
static int
NORTH
static int
NORTHEAST
static int
NORTHWEST
static int
PAGE_END
static int
PAGE_START
static int
RELATIVE
static int
REMAINDER
static int
SOUTH
static int
SOUTHEAST
static int
SOUTHWEST
static int
VERTICAL
double
weightx
Class GridBagConstraints
1177
weighty
static int
WEST
Constructor Summary
Constructor and Description
GridBagConstraints()
GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight,
double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx,
int ipady)
Method Summary
Modifier and Type Method and Description
Object
clone()
Field Detail
RELATIVE
public static final int RELATIVE
See Also:
Constant Field Values
REMAINDER
public static final int REMAINDER
See Also:
Constant Field Values
NONE
public static final int NONE
See Also:
Constant Field Values
BOTH
public static final int BOTH
See Also:
Constant Field Values
HORIZONTAL
public static final int HORIZONTAL
See Also:
Constant Field Values
VERTICAL
public static final int VERTICAL
See Also:
Constant Field Values
Field Summary
1178
See Also:
Constant Field Values
NORTH
public static final int NORTH
See Also:
Constant Field Values
NORTHEAST
public static final int NORTHEAST
See Also:
Constant Field Values
EAST
public static final int EAST
See Also:
Constant Field Values
SOUTHEAST
public static final int SOUTHEAST
See Also:
Constant Field Values
SOUTH
public static final int SOUTH
See Also:
Constant Field Values
SOUTHWEST
public static final int SOUTHWEST
See Also:
Constant Field Values
WEST
public static final int WEST
See Also:
Constant Field Values
NORTHWEST
public static final int NORTHWEST
See Also:
Constant Field Values
PAGE_START
public static final int PAGE_START
See Also:
Constant Field Values
PAGE_END
public static final int PAGE_END
See Also:
Constant Field Values
Field Detail
1179
See Also:
Constant Field Values
LINE_END
public static final int LINE_END
See Also:
Constant Field Values
FIRST_LINE_START
public static final int FIRST_LINE_START
See Also:
Constant Field Values
FIRST_LINE_END
public static final int FIRST_LINE_END
See Also:
Constant Field Values
LAST_LINE_START
public static final int LAST_LINE_START
See Also:
Constant Field Values
LAST_LINE_END
public static final int LAST_LINE_END
See Also:
Constant Field Values
gridx
public int gridx
gridy
public int gridy
gridwidth
public int gridwidth
gridheight
public int gridheight
weightx
public double weightx
weighty
public double weighty
anchor
public int anchor
fill
public int fill
insets
public Insets insets
ipadx
public int ipadx
Field Detail
1180
Constructor Detail
GridBagConstraints
public GridBagConstraints(int gridx,
int gridy,
int gridwidth,
int gridheight,
double weightx,
double weighty,
int anchor,
int fill,
Insets insets,
int ipadx,
int ipady)
GridBagConstraints
public GridBagConstraints()
Method Detail
clone
public Object clone()
Field Detail
1181
Class FlowLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.layouts.FlowLayout
public class
extends Layout
FlowLayout is the default layout manager for Codename One Containers and Forms. It places
components in a row one after another based on their preferred size. When it reaches the edge of the
container it will break a line and start a new row.
Form hi = new Form("Flow Layout", new FlowLayout());
hi.add(new Label("First")).
add(new Label("Second")).
add(new Label("Third")).
add(new Label("Fourth")).
add(new Label("Fifth"));
hi.show();
Since flow layout isn't a constraint based layout it has a bunch of very useful enclose methods that
can significantly reduce the code required to create the same UI e.g.:
Container flowLayout = FlowLayout.encloseIn(new Label("First"),
new Label("Second"),
new Label("Third"),
new Label("Fourth"),
new Label("Fifth"));
This class works nicely for simple elements, however since Codename One doesn't reflow recursively
(for performance) it can't accurately handle complex layouts. As a result when an element of varying
size is placed in a flow layout this confuses the line breaking logic and fails in odd ways. That is why
this layout should only be used for relatively simple use cases.
Flow layout supports aligning the component horizontally and vertically, it defaults to the top left
alignment for LTR languages. E.g. the following alignments are supported thru the usage of setAlign
& setValign.
Method Detail
1182
Class FlowLayout
1183
There are quite a few additional combinations that are possible with these API's.
See Also:
see the box layout X which is often a better choice than flow layout.
Constructor Summary
Constructor and Description
FlowLayout()
Creates a new instance of FlowLayout with the given orientation one of LEFT, RIGHT or
CENTER
FlowLayout(int orientation, int valign)
Creates a new instance of FlowLayout with the given orientation one of LEFT, RIGHT or
CENTER and the vertical orientation
Method Summary
Modifier
and Type
static
Container
static
Container
static
Container
static
Container
Constructor Summary
1184
encloseIn(Component... cmps)
int
Dimension
getPreferredSize(Container parent)
int
boolean
boolean
Indicates whether the layout manager should try to fill up the available space
in the row
isValignByRow()
void
void
Indicates whether the layout manager should try to fill up the available space
in the row
void
setValign(int valign)
void
void
String
toString()
Constructor Detail
Method Summary
1185
Creates a new instance of FlowLayout with the given orientation one of LEFT, RIGHT
or CENTER
Parameters:
orientation - the orientation value
FlowLayout
public FlowLayout(int orientation,
int valign)
Creates a new instance of FlowLayout with the given orientation one of LEFT, RIGHT
or CENTER and the vertical orientation
Parameters:
orientation - the orientation value
valign - the vertical orientation one of Component.TOP/BOTTOM/CENTER
Method Detail
layoutContainer
public void layoutContainer(Container parent)
This method tries to fill up the available space in a row. This method is called if
isFillRows() returns true.
Parameters:
target - the parent container
width - the width of the row to fill
start - the index of the first component in this row
end - the index of the last component in this row
getPreferredSize
public Dimension getPreferredSize(Container parent)
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
Constructor Detail
1186
Indicates whether the layout manager should try to fill up the available space in the
row
Returns:
the fillRows
setFillRows
public void setFillRows(boolean fillRows)
Indicates whether the layout manager should try to fill up the available space in the
row
Parameters:
fillRows - the fillRows to set
getValign
public int getValign()
When set to true vertical alignment will be performed by row (components within the
container will be aligned vertically to each other in the same row) When set to false
(which is default) vertical alignment relates to the alignment of this container in
regards to external components
Parameters:
internal - true for internal, false otherwise
isValignByRow
public boolean isValignByRow()
Method Detail
1187
equals
public boolean equals(Object o)
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Layout
encloseIn
public static Container encloseIn(Component... cmps)
Parameters:
cmps - the components to enclose in a new container
Returns:
the new container
encloseCenter
public static Container encloseCenter(Component... cmps)
Method Detail
1188
Method Detail
1189
Class CoordinateLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.layouts.CoordinateLayout
Deprecated.
the usage of this layout is strongly discouraged as elements will not adapt to the right position/size
public class
extends Layout
Allows laying out components based on absolute positions/sizes that are adapted based on available
space for the layout. The layout
Constructor Summary
Constructor and Description
CoordinateLayout()
Deprecated.
Allows creating a coordinate layouts that disables the scaling feature
CoordinateLayout(Dimension d)
Deprecated.
This constructor accepts the relative width and height used to define the aspect ratio of the
Container
CoordinateLayout(int width, int height)
Deprecated.
This constructor accepts the relative width and height used to define the aspect ratio of the
Container
Method Summary
Modifier and Type
Dimension
Deprecated.
Returns the container preferred size
isOverlapSupported()
boolean
Deprecated.
This method returns true if the Layout allows Components to Overlap.
layoutContainer(Container parent)
Deprecated.
Layout the given parent container children
void
Class CoordinateLayout
1190
Constructor
Detail
CoordinateLayout
public CoordinateLayout()
Deprecated.
Allows creating a coordinate layouts that disables the scaling feature
CoordinateLayout
public CoordinateLayout(int width,
int height)
Deprecated.
This constructor accepts the relative width and height used to define the aspect ratio
of the Container
Parameters:
width height CoordinateLayout
public CoordinateLayout(Dimension d)
Deprecated.
This constructor accepts the relative width and height used to define the aspect ratio
of the Container
Parameters:
d - the width/height
Method Detail
layoutContainer
public void layoutContainer(Container parent)
Deprecated.
Layout the given parent container children
Specified by:
layoutContainer in class Layout
Parameters:
parent - the given parent container
getPreferredSize
public Dimension getPreferredSize(Container parent)
Deprecated.
Returns the container preferred size
Specified by:
getPreferredSize in class Layout
Parameters:
parent - the parent container
Returns:
the container preferred size
isOverlapSupported
public boolean isOverlapSupported()
Deprecated.
This method returns true if the Layout allows Components to Overlap.
Overrides:
isOverlapSupported in class Layout
Returns:
true if Components may intersect in this layout
Constructor Detail
1191
Class BoxLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.layouts.BoxLayout
public class
extends Layout
Layout manager that places elements in a row (X_AXIS) or column (Y_AXIS) according to box
orientation. Box is a very simple and predictable layout that serves as the "workhorse" of component
lists in Codename One
You can create a box layout Y UI using syntax such as this
Form hi = new Form("Box Y Layout", new BoxLayout(BoxLayout.Y_AXIS));
hi.add(new Label("First")).
add(new Label("Second")).
add(new Label("Third")).
add(new Label("Fourth")).
add(new Label("Fifth"));
This can also be expressed with more terse syntax e.g. an X axis layout like this:
Container box = BoxLayout.encloseX(new Label("First"),
new Label("Second"),
new Label("Third"),
new Label("Fourth"),
new Label("Fifth")));
Method Detail
1192
The BoxLayout keeps the preferred size of its destination orientation and scales elements on the other
axis. Specifically X_AXIS will keep the preferred width of the component while growing all the
components vertically to match in size. Its Y_AXIS counterpart keeps the preferred height while
growing the components horizontally.
This behavior is very useful since it allows elements to align as they would all have the same size.
In some cases the growing behavior in the X axis is undesired, for these cases we can use the
X_AXIS_NO_GROW variant.
Class BoxLayout
1193
Field Summary
Modifier and
Type
static int
static int
static int
Horizontal layout where components are arranged from left to right but don't
grow vertically beyond their preferred size
Y_AXIS
Constructor Summary
Constructor and Description
BoxLayout(int axis)
Method Summary
Modifier and Type
static Container
Class BoxLayout
1194
static Container
encloseY(Component... cmps)
static Container
boolean
int
Dimension
void
Method Summary
equals(Object o)
1195
String
Field Detail
X_AXIS
public static final int X_AXIS
Horizontal layout where components are arranged from left to right but don't grow
vertically beyond their preferred size
See Also:
Constant Field Values
Constructor Detail
BoxLayout
public BoxLayout(int axis)
Method Detail
layoutContainer
public void layoutContainer(Container parent)
1196
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
equals
public boolean equals(Object o)
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Layout
encloseY
public static Container encloseY(Component... cmps)
Method Detail
1197
Parameters:
cmps - the set of components
Returns:
the newly created container
encloseX
public static Container encloseX(Component... cmps)
Parameters:
cmps - the set of components
Returns:
the newly created container
Method Detail
1198
Parameters:
cmps - the set of components
Returns:
the newly created container
Method Detail
1199
Class BorderLayout
java.lang.Object
com.codename1.ui.layouts.Layout
com.codename1.ui.layouts.BorderLayout
public class
extends Layout
A border layout lays out a container, arranging and resizing its components to fit in five regions: north,
south, east, west, and center. Each region may contain no more than one component, and is
identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and CENTER. When adding
a component to a container with a border layout, use one of these five constants.
The border layout scales all of the components within it to match the available constraints. The
NORTH & SOUTH components use their preferred height but are stretched to take up the full width
available. The EAST & WEST do the same for the reverse axis however they leave room for the
NORTH/SOUTH entries if they are defined.
The CENTER constraint will take up the rest of the available space regardless of its preferred size.
This is normally very useful, however in some cases we would prefer that the center component will
actually position itself in the middle of the available space. For this we have the setCenterBehavior
method.
Because of its scaling behavior scrolling a border layout makes no sense. However it is a common
mistake to apply a border layout to a scrollable container or trying to make a border layout scrollable.
That is why the Container class explicitly blocks scrolling on a BorderLayout.
Typical usage of this class:
Form hi = new Form("Border Layout", new BorderLayout());
hi.add(BorderLayout.CENTER, new Label("Center")).
add(BorderLayout.SOUTH, new Label("South")).
add(BorderLayout.NORTH, new Label("North")).
add(BorderLayout.EAST, new Label("East")).
add(BorderLayout.WEST, new Label("West"));
hi.show();
When defining the center behavior we can get very different results:
Form hi = new Form("Border Layout", new BorderLayout());
((BorderLayout)hi.getLayout()).setCenterBehavior(BorderLayout.CENTER_BEHAVIOR_CENTER);
hi.add(BorderLayout.CENTER, new Label("Center")).
add(BorderLayout.SOUTH, new Label("South")).
add(BorderLayout.NORTH, new Label("North")).
add(BorderLayout.EAST, new Label("East")).
add(BorderLayout.WEST, new Label("West"));
hi.show();
Class BorderLayout
1200
Notice that in the case of RTL (right to left language also known as bidi) the EAST and WEST values
are implicitly reversed as shown in this image:
You can read further in the BorderLayout section in the developer guide.
Field Summary
Modifier
and Type
static
String
static int
Defines the behavior of the component placed in the center position of the
layout, places the component in the center of the space available to the center
component.
CENTER_BEHAVIOR_CENTER_ABSOLUTE
static int
Defines the behavior of the component placed in the center position of the
layout, places the component in the center of the surrounding container
CENTER_BEHAVIOR_SCALE
static int
Defines the behavior of the component placed in the center position of the
layout, by default it is scaled to the available space
CENTER_BEHAVIOR_TOTAL_BELLOW
static int
Field Summary
Deprecated.
Deprecated due to spelling mistake, use
CENTER_BEHAVIOR_TOTAL_BELOW
1201
The center component takes up the entire screens and the sides are
automatically placed on top of it thus creating a layered effect
static
String
EAST
static
String
NORTH
static
String
SOUTH
static
String
WEST
Constructor Summary
Constructor and Description
BorderLayout()
Method Summary
Modifier and
Type
void
static
Container
Some layouts can optionally track the addition of elements with meta-data
that allows the user to "hint" on object positioning.
center(Component center)
Convenience method that creates a border layout container and places the
given component in the center
defineLandscapeSwap(String portraitPosition,
String landscapePosition)
void
static
Container
boolean
Component
This method allows swapping positions within the border layout when the
layout orientation changes to landscape or if the layout starts off as
landscape.
east(Component east)
Convenience method that creates a border layout container and places the
given component in the east
equals(Object o)
int
Object
Component
Defines the behavior of the center component to one of the constants defined
in this class
getComponentConstraint(Component comp)
String
Component
Dimension
Component
Constructor Summary
Returns the landscape swap destination for the given border layout element if
such a destination is defined.
getNorth()
1202
getWest()
boolean
Deprecated.
use center behavior instead
isConstraintTracking()
boolean
boolean
boolean
void
static
Container
north(Component north)
Convenience method that creates a border layout container and places the
given component in the north
obscuresPotential(Container parent)
boolean
Some layout managers can obscure their child components in some cases
this returns true if the basic underpinnings are in place for that.
removeLayoutComponent(Component comp)
Removes the component from the layout this operation is only useful if the
layout maintains references to components within it
void
setAbsoluteCenter(boolean absoluteCenter)
Deprecated.
use center behavior instead
void
setCenterBehavior(int centerBehavior)
Defines the behavior of the center component to one of the constants defined
in this class
void
setScaleEdges(boolean scaleEdges)
void
static
Container
south(Component south)
Convenience method that creates a border layout container and places the
given component in the south
toString()
String
static
Container
west(Component west)
Convenience method that creates a border layout container and places the
given component in the west
Field Detail
CENTER_BEHAVIOR_SCALE
public static final int CENTER_BEHAVIOR_SCALE
Defines the behavior of the component placed in the center position of the layout, by
default it is scaled to the available space
See Also:
Constant Field Values
Method Summary
1203
Defines the behavior of the component placed in the center position of the layout,
places the component in the center of the space available to the center component.
See Also:
Constant Field Values
CENTER_BEHAVIOR_CENTER_ABSOLUTE
public static final int CENTER_BEHAVIOR_CENTER_ABSOLUTE
Defines the behavior of the component placed in the center position of the layout,
places the component in the center of the surrounding container
See Also:
Constant Field Values
CENTER_BEHAVIOR_TOTAL_BELLOW
public static final int CENTER_BEHAVIOR_TOTAL_BELLOW
The center component takes up the entire screens and the sides are automatically
placed on top of it thus creating a layered effect
See Also:
Constant Field Values
NORTH
public static final String NORTH
Field Detail
1204
Constructor Detail
BorderLayout
public BorderLayout()
Method Detail
addLayoutComponent
public void addLayoutComponent(Object name,
Component comp,
Container c)
Some layouts can optionally track the addition of elements with meta-data that allows
the user to "hint" on object positioning.
Overrides:
addLayoutComponent in class Layout
Parameters:
name - optional meta data information, like alignment orientation
comp - the added component to the layout
c - the parent container
removeLayoutComponent
public void removeLayoutComponent(Component comp)
Removes the component from the layout this operation is only useful if the layout
maintains references to components within it
Overrides:
removeLayoutComponent in class Layout
Parameters:
comp - the removed component from layout
getComponentConstraint
public Object getComponentConstraint(Component comp)
Field Detail
1205
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Method Detail
1206
This method allows swapping positions within the border layout when the layout
orientation changes to landscape or if the layout starts off as landscape.
Parameters:
portraitPosition - the position for the component when in portrait (this
position should always be used when adding a component to the layout).
One of NORTH/SOUTH/EAST/WEST/CENTER.
landscapePosition - the destination position to use in landscape
getLandscapeSwap
public String getLandscapeSwap(String portraitPosition)
Returns the landscape swap destination for the given border layout element if such a
destination is defined.
Parameters:
portraitPosition - the constraint used when placing the component
Returns:
the constraint to use when in landscape or null if undefined
equals
public boolean equals(Object o)
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Layout
isAbsoluteCenter
public boolean isAbsoluteCenter()
Defines the behavior of the center component to one of the constants defined in this
class
Returns:
Method Detail
1207
Defines the behavior of the center component to one of the constants defined in this
class
Parameters:
centerBehavior - the centerBehavior to set
isOverlapSupported
public boolean isOverlapSupported()
If this method returns true, the addLayoutComponent method will be called when
replacing a layout for every component within the container
Overrides:
isConstraintTracking in class Layout
Returns:
false by default
obscuresPotential
public boolean obscuresPotential(Container parent)
Some layout managers can obscure their child components in some cases this
returns true if the basic underpinnings are in place for that. This method doesn't take
padding/margin etc. into account since that is checked by the caller
Overrides:
obscuresPotential in class Layout
Parameters:
parent - parent container
Returns:
true if there is a chance that this layout manager can fully obscure the
background, when in doubt return false...
center
public static Container center(Component center)
Convenience method that creates a border layout container and places the given
component in the center
Parameters:
center - the center component
Returns:
the created component
Method Detail
1208
Convenience method that creates a border layout container and places the given
component in the north
Parameters:
north - the north component
Returns:
the created component
south
public static Container south(Component south)
Convenience method that creates a border layout container and places the given
component in the south
Parameters:
south - the south component
Returns:
the created component
east
public static Container east(Component east)
Convenience method that creates a border layout container and places the given
component in the east
Parameters:
east - the east component
Returns:
the created component
west
public static Container west(Component west)
Convenience method that creates a border layout container and places the given
component in the west
Parameters:
west - the west component
Returns:
the created component
Method Detail
1209
Interface IOCallback
All Known Implementing Classes:
HTMLComponent
public interface
This interface is implemented by HTMLComponent and ResourceThread (The two classes using the
AsyncDocumentRequestHandler)
Method Summary
Modifier and Type
void
Method Detail
streamReady
void streamReady(InputStream is,
DocumentInfo docInfo)
Interface IOCallback
1210
Class HTMLUtils
java.lang.Object
com.codename1.ui.html.HTMLUtils
public class
extends Object
Method Summary
Modifier and
Type
static
String
static
String
convertHTMLCharEntity(String charEntity)
static
String
convertXMLCharEntity(String charEntity)
static
String
encodeString(String str)
Method Detail
convertXMLCharEntity
public static String convertXMLCharEntity(String charEntity)
Method Detail
1211
Converts a char entity to the matching character or string. This handles both
numbered and symbol char entities (The latter is done via getCharEntityCode)
Parameters:
charEntity - The char entity to convert (Not including the & and ;)
lookupHTMLentities - true to include the basic HTML named char entities
(unicode 160-255), false otherwise
userDefinedCharEntities - A hashtable containing (String,int) dentoing the
char entity name and its unicode
Returns:
A string containing a single char, or the original char entity string (with & and
;) if the char entity couldn't be resolved
encodeString
public static String encodeString(String str)
Method Detail
1212
Class HTMLParser
java.lang.Object
com.codename1.xml.XMLParser
com.codename1.ui.html.HTMLParser
public class
extends XMLParser
The HTMLParser class is used to parse an XHTML-MP 1.0 document into a DOM object (Element).
Unsupported tags and attributes as well as comments are dropped in the parsing process. The parser
is also makes use of CSSParser for external CSS files, embedded CSS segments and CSS within the
'style' attribute.
Constructor Summary
Constructor and Description
HTMLParser()
Method Summary
Modifier and
Type
protected
String
protected
Element
protected
Element
protected
String
protected
boolean
protected
boolean
Overrides the Element.isSupported to let the parser know which tags are
supported in XHTML-MP 1.0
parseHTML(InputStreamReader isr)
HTMLElement
A convenience method that casts the returned type of the parse method to
HTMLElement.
parseTagContent(Element element, Reader is)
protected void
protected
boolean
Class HTMLParser
1213
Constructor Detail
HTMLParser
public HTMLParser()
Method Detail
parseTagContent
protected void parseTagContent(Element element,
Reader is)
throws IOException
1214
A convenience method that casts the returned type of the parse method to
HTMLElement. Basically calling this method is simlar to calling parse and casting to
HTMLElement.
Parameters:
isr - The input stream containing the HTML
Returns:
The HTML document
getSupportedStandardName
protected String getSupportedStandardName()
{Returns a string identifying the document type this parser supports. This should be
overriden by subclassing parsers.}
Overrides:
getSupportedStandardName in class XMLParser
Returns:
a string identifying the document type this parser supports.
isSupported
protected boolean isSupported(Element element)
Overrides the Element.isSupported to let the parser know which tags are supported
in XHTML-MP 1.0
Overrides:
isSupported in class XMLParser
Parameters:
element - The element to check
Returns:
true if the tag is a supported XHTML Mobile Profile 1.0 tag, false otherwise
shouldEvaluate
protected boolean shouldEvaluate(Element element)
Overrides the Element.shouldEvaluate method to return false on the script tag. The
script tag should be skipped entirely, since it may contain characters like greater-than
and lesser-than which may break the HTML All other tags are evaluated (i.e. added
including all their children to the tree), even if not supported (But of course their
functionality is ignored by HTMLComponent)
Overrides:
shouldEvaluate in class XMLParser
Parameters:
element - The element to check
Returns:
false if this is the SCRIPT tag, true otherwise
Method Detail
1215
Class HTMLElement
java.lang.Object
com.codename1.xml.Element
com.codename1.ui.html.HTMLElement
All Implemented Interfaces:
Iterable<Element>
public class
extends Element
The HTMLElement class defines a single HTML element with its attributes and children. Due to its
hierarchial nature, this class can be used for a single "leaf" Element, for more complex elements (with
child elements), and up to describing the entire document.
Field Summary
Modifier and Type
static int
ATTR_ABBR
static int
ATTR_ACCESSKEY
static int
ATTR_ACTION
static int
ATTR_ALIGN
static int
ATTR_ALT
static int
ATTR_AXIS
static int
ATTR_BGCOLOR
static int
ATTR_BORDER
static int
ATTR_CELLPADDING
static int
ATTR_CELLSPACING
static int
ATTR_CHARSET
static int
ATTR_CHECKED
static int
ATTR_CITE
static int
ATTR_CLASS
static int
ATTR_COLOR
static int
ATTR_COLS
static int
ATTR_COLSPAN
static int
ATTR_CONTENT
static int
ATTR_COORDS
static int
ATTR_DIR
static int
ATTR_DISABLED
static int
ATTR_EMPTYOK
static int
ATTR_ENCTYPE
static int
ATTR_FACE
static int
ATTR_FOR
static int
ATTR_FORMAT
static int
ATTR_FRAME
static int
ATTR_HEADERS
Class HTMLElement
1216
Field Summary
static int
ATTR_HEIGHT
static int
ATTR_HREF
static int
ATTR_HREFLANG
static int
ATTR_HSPACE
static int
ATTR_HTTPEQUIV
static int
ATTR_ID
static int
ATTR_ISMAP
static int
ATTR_ISTYLE
static int
ATTR_LABEL
static int
ATTR_LANG
static int
ATTR_LINK
static int
ATTR_LOCALSRC
static int
ATTR_LONGDESC
static int
ATTR_MAXLENGTH
static int
ATTR_MEDIA
static int
ATTR_METHOD
static int
ATTR_MULTIPLE
static int
ATTR_NAME
static int
ATTR_READONLY
static int
ATTR_REL
static int
ATTR_REV
static int
ATTR_ROWS
static int
ATTR_ROWSPAN
static int
ATTR_RULES
static int
ATTR_SCHEME
static int
ATTR_SCOPE
static int
ATTR_SELECTED
static int
ATTR_SHAPE
static int
ATTR_SIZE
static int
ATTR_SRC
static int
ATTR_START
static int
ATTR_STYLE
static int
ATTR_SUMMARY
static int
ATTR_TABINDEX
static int
ATTR_TEXT
static int
ATTR_TITLE
static int
ATTR_TYPE
static int
ATTR_USEMAP
static int
ATTR_VALIGN
static int
ATTR_VALUE
static int
ATTR_VERSION
static int
ATTR_VSPACE
static int
ATTR_WIDTH
static int
ATTR_XMLLANG
static int
ATTR_XMLNS
static int
ATTR_XMLSPACE
1217
Field Summary
static int
COLOR_AQUA
static int
COLOR_BLACK
static int
COLOR_BLUE
static int
COLOR_FUCHSIA
static int
COLOR_GRAY
static int
COLOR_GREEN
static int
COLOR_LIME
static int
COLOR_MAROON
static int
COLOR_NAVY
static int
COLOR_OLIVE
static int
COLOR_ORANGE
static int
COLOR_PURPLE
static int
COLOR_RED
static int
COLOR_SILVER
static int
COLOR_TEAL
static int
COLOR_WHITE
static int
COLOR_YELLOW
static int
TAG_A
static int
TAG_ABBR
static int
TAG_ACRONYM
static int
TAG_ADDRESS
static int
TAG_AREA
static int
TAG_B
static int
TAG_BASE
static int
TAG_BASEFONT
static int
TAG_BIG
static int
TAG_BLOCKQUOTE
static int
TAG_BODY
static int
TAG_BR
static int
TAG_BUTTON
static int
TAG_CAPTION
static int
TAG_CENTER
static int
TAG_CITE
static int
TAG_CODE
static int
TAG_CSS_ILLEGAL_SELECTOR
static int
TAG_CSS_SELECTOR
static int
TAG_DD
static int
TAG_DEL
static int
TAG_DFN
static int
TAG_DIR
static int
TAG_DIV
static int
TAG_DL
static int
TAG_DT
static int
TAG_EM
static int
TAG_FIELDSET
static int
TAG_FONT
1218
Field Summary
static int
TAG_FORM
static int
TAG_H1
static int
TAG_H2
static int
TAG_H3
static int
TAG_H4
static int
TAG_H5
static int
TAG_H6
static int
TAG_HEAD
static int
TAG_HR
static int
TAG_HTML
static int
TAG_I
static int
TAG_IMG
static int
TAG_INPUT
static int
TAG_INS
static int
TAG_KBD
static int
TAG_LABEL
static int
TAG_LEGEND
static int
TAG_LI
static int
TAG_LINK
static int
TAG_MAP
static int
TAG_MENU
static int
TAG_META
static int
TAG_NOFRAMES
static int
TAG_NOSCRIPT
static int
TAG_OBJECT
static int
TAG_OL
static int
TAG_OPTGROUP
static int
TAG_OPTION
static int
TAG_P
static int
TAG_PARAM
static int
TAG_PRE
static int
TAG_Q
static int
TAG_S
static int
TAG_SAMP
static int
TAG_SELECT
static int
TAG_SMALL
static int
TAG_SPAN
static int
TAG_STRIKE
static int
TAG_STRONG
static int
TAG_STYLE
static int
TAG_SUB
static int
TAG_SUP
static int
TAG_TABLE
static int
TAG_TBODY
static int
TAG_TD
static int
TAG_TEXT
1219
TAG_TEXTAREA
static int
TAG_TFOOT
static int
TAG_TH
static int
TAG_THEAD
static int
TAG_TITLE
static int
TAG_TR
static int
TAG_TT
static int
TAG_U
static int
TAG_UL
static int
TAG_UNSUPPORTED
static int
TAG_VAR
Constructor Summary
Modifier
protected
Method Summary
Modifier and
Type
void
String
Returns the attribute value by its name (or null if it wasn't defined for this
element)
getAttributeById(int id)
String
String
Vector
Vector
HTMLElement
String
int
String
void
1220
void
Adds the specified attribute and value to this Element if it is supported for
the Element and has a valid value.
int
void
protected void
setTagId(int tagId)
String
Field Detail
TAG_CSS_ILLEGAL_SELECTOR
public static final int TAG_CSS_ILLEGAL_SELECTOR
See Also:
Constant Field Values
TAG_CSS_SELECTOR
public static final int TAG_CSS_SELECTOR
See Also:
Constant Field Values
TAG_UNSUPPORTED
public static final int TAG_UNSUPPORTED
See Also:
Constant Field Values
TAG_BODY
public static final int TAG_BODY
See Also:
Constant Field Values
TAG_HEAD
public static final int TAG_HEAD
See Also:
Constant Field Values
TAG_HTML
public static final int TAG_HTML
See Also:
Method Summary
1221
See Also:
Constant Field Values
TAG_ABBR
public static final int TAG_ABBR
See Also:
Constant Field Values
TAG_ACRONYM
public static final int TAG_ACRONYM
See Also:
Constant Field Values
TAG_ADDRESS
public static final int TAG_ADDRESS
See Also:
Constant Field Values
TAG_BLOCKQUOTE
public static final int TAG_BLOCKQUOTE
See Also:
Constant Field Values
TAG_BR
public static final int TAG_BR
See Also:
Constant Field Values
TAG_CITE
public static final int TAG_CITE
See Also:
Constant Field Values
TAG_CODE
public static final int TAG_CODE
See Also:
Constant Field Values
TAG_DFN
public static final int TAG_DFN
See Also:
Constant Field Values
TAG_DIV
public static final int TAG_DIV
See Also:
Constant Field Values
TAG_EM
public static final int TAG_EM
See Also:
Constant Field Values
Field Detail
1222
See Also:
Constant Field Values
TAG_H2
public static final int TAG_H2
See Also:
Constant Field Values
TAG_H3
public static final int TAG_H3
See Also:
Constant Field Values
TAG_H4
public static final int TAG_H4
See Also:
Constant Field Values
TAG_H5
public static final int TAG_H5
See Also:
Constant Field Values
TAG_H6
public static final int TAG_H6
See Also:
Constant Field Values
TAG_KBD
public static final int TAG_KBD
See Also:
Constant Field Values
TAG_P
public static final int TAG_P
See Also:
Constant Field Values
TAG_PRE
public static final int TAG_PRE
See Also:
Constant Field Values
TAG_Q
public static final int TAG_Q
See Also:
Constant Field Values
TAG_SAMP
public static final int TAG_SAMP
See Also:
Constant Field Values
Field Detail
1223
See Also:
Constant Field Values
TAG_STRONG
public static final int TAG_STRONG
See Also:
Constant Field Values
TAG_VAR
public static final int TAG_VAR
See Also:
Constant Field Values
TAG_A
public static final int TAG_A
See Also:
Constant Field Values
TAG_DL
public static final int TAG_DL
See Also:
Constant Field Values
TAG_DT
public static final int TAG_DT
See Also:
Constant Field Values
TAG_DD
public static final int TAG_DD
See Also:
Constant Field Values
TAG_OL
public static final int TAG_OL
See Also:
Constant Field Values
TAG_UL
public static final int TAG_UL
See Also:
Constant Field Values
TAG_LI
public static final int TAG_LI
See Also:
Constant Field Values
TAG_FORM
public static final int TAG_FORM
See Also:
Constant Field Values
Field Detail
1224
See Also:
Constant Field Values
TAG_LABEL
public static final int TAG_LABEL
See Also:
Constant Field Values
TAG_SELECT
public static final int TAG_SELECT
See Also:
Constant Field Values
TAG_OPTION
public static final int TAG_OPTION
See Also:
Constant Field Values
TAG_TEXTAREA
public static final int TAG_TEXTAREA
See Also:
Constant Field Values
TAG_CAPTION
public static final int TAG_CAPTION
See Also:
Constant Field Values
TAG_TABLE
public static final int TAG_TABLE
See Also:
Constant Field Values
TAG_TD
public static final int TAG_TD
See Also:
Constant Field Values
TAG_TH
public static final int TAG_TH
See Also:
Constant Field Values
TAG_TR
public static final int TAG_TR
See Also:
Constant Field Values
TAG_IMG
public static final int TAG_IMG
See Also:
Constant Field Values
Field Detail
1225
See Also:
Constant Field Values
TAG_PARAM
public static final int TAG_PARAM
See Also:
Constant Field Values
TAG_META
public static final int TAG_META
See Also:
Constant Field Values
TAG_LINK
public static final int TAG_LINK
See Also:
Constant Field Values
TAG_BASE
public static final int TAG_BASE
See Also:
Constant Field Values
TAG_HR
public static final int TAG_HR
See Also:
Constant Field Values
TAG_OPTGROUP
public static final int TAG_OPTGROUP
See Also:
Constant Field Values
TAG_STYLE
public static final int TAG_STYLE
See Also:
Constant Field Values
TAG_B
public static final int TAG_B
See Also:
Constant Field Values
TAG_I
public static final int TAG_I
See Also:
Constant Field Values
TAG_BIG
public static final int TAG_BIG
See Also:
Constant Field Values
Field Detail
1226
See Also:
Constant Field Values
TAG_FIELDSET
public static final int TAG_FIELDSET
See Also:
Constant Field Values
TAG_U
public static final int TAG_U
See Also:
Constant Field Values
TAG_FONT
public static final int TAG_FONT
See Also:
Constant Field Values
TAG_DEL
public static final int TAG_DEL
See Also:
Constant Field Values
TAG_INS
public static final int TAG_INS
See Also:
Constant Field Values
TAG_TT
public static final int TAG_TT
See Also:
Constant Field Values
TAG_BASEFONT
public static final int TAG_BASEFONT
See Also:
Constant Field Values
TAG_MENU
public static final int TAG_MENU
See Also:
Constant Field Values
TAG_S
public static final int TAG_S
See Also:
Constant Field Values
TAG_STRIKE
public static final int TAG_STRIKE
See Also:
Constant Field Values
Field Detail
1227
See Also:
Constant Field Values
TAG_DIR
public static final int TAG_DIR
See Also:
Constant Field Values
TAG_MAP
public static final int TAG_MAP
See Also:
Constant Field Values
TAG_AREA
public static final int TAG_AREA
See Also:
Constant Field Values
TAG_LEGEND
public static final int TAG_LEGEND
See Also:
Constant Field Values
TAG_SUB
public static final int TAG_SUB
See Also:
Constant Field Values
TAG_SUP
public static final int TAG_SUP
See Also:
Constant Field Values
TAG_NOSCRIPT
public static final int TAG_NOSCRIPT
See Also:
Constant Field Values
TAG_NOFRAMES
public static final int TAG_NOFRAMES
See Also:
Constant Field Values
TAG_THEAD
public static final int TAG_THEAD
See Also:
Constant Field Values
TAG_TBODY
public static final int TAG_TBODY
See Also:
Constant Field Values
Field Detail
1228
See Also:
Constant Field Values
TAG_BUTTON
public static final int TAG_BUTTON
See Also:
Constant Field Values
TAG_TEXT
public static final int TAG_TEXT
See Also:
Constant Field Values
ATTR_CLASS
public static final int ATTR_CLASS
See Also:
Constant Field Values
ATTR_ID
public static final int ATTR_ID
See Also:
Constant Field Values
ATTR_STYLE
public static final int ATTR_STYLE
See Also:
Constant Field Values
ATTR_TITLE
public static final int ATTR_TITLE
See Also:
Constant Field Values
ATTR_XMLNS
public static final int ATTR_XMLNS
See Also:
Constant Field Values
ATTR_XMLLANG
public static final int ATTR_XMLLANG
See Also:
Constant Field Values
ATTR_ALIGN
public static final int ATTR_ALIGN
See Also:
Constant Field Values
ATTR_BGCOLOR
public static final int ATTR_BGCOLOR
See Also:
Constant Field Values
Field Detail
1229
See Also:
Constant Field Values
ATTR_TEXT
public static final int ATTR_TEXT
See Also:
Constant Field Values
ATTR_VERSION
public static final int ATTR_VERSION
See Also:
Constant Field Values
ATTR_CITE
public static final int ATTR_CITE
See Also:
Constant Field Values
ATTR_ACCESSKEY
public static final int ATTR_ACCESSKEY
See Also:
Constant Field Values
ATTR_CHARSET
public static final int ATTR_CHARSET
See Also:
Constant Field Values
ATTR_HREF
public static final int ATTR_HREF
See Also:
Constant Field Values
ATTR_HREFLANG
public static final int ATTR_HREFLANG
See Also:
Constant Field Values
ATTR_REL
public static final int ATTR_REL
See Also:
Constant Field Values
ATTR_REV
public static final int ATTR_REV
See Also:
Constant Field Values
ATTR_TABINDEX
public static final int ATTR_TABINDEX
See Also:
Constant Field Values
Field Detail
1230
See Also:
Constant Field Values
ATTR_ACTION
public static final int ATTR_ACTION
See Also:
Constant Field Values
ATTR_ENCTYPE
public static final int ATTR_ENCTYPE
See Also:
Constant Field Values
ATTR_METHOD
public static final int ATTR_METHOD
See Also:
Constant Field Values
ATTR_WIDTH
public static final int ATTR_WIDTH
See Also:
Constant Field Values
ATTR_HEIGHT
public static final int ATTR_HEIGHT
See Also:
Constant Field Values
ATTR_ALT
public static final int ATTR_ALT
See Also:
Constant Field Values
ATTR_HSPACE
public static final int ATTR_HSPACE
See Also:
Constant Field Values
ATTR_VSPACE
public static final int ATTR_VSPACE
See Also:
Constant Field Values
ATTR_LONGDESC
public static final int ATTR_LONGDESC
See Also:
Constant Field Values
ATTR_LOCALSRC
public static final int ATTR_LOCALSRC
See Also:
Constant Field Values
Field Detail
1231
See Also:
Constant Field Values
ATTR_SIZE
public static final int ATTR_SIZE
See Also:
Constant Field Values
ATTR_CHECKED
public static final int ATTR_CHECKED
See Also:
Constant Field Values
ATTR_EMPTYOK
public static final int ATTR_EMPTYOK
See Also:
Constant Field Values
ATTR_FORMAT
public static final int ATTR_FORMAT
See Also:
Constant Field Values
ATTR_ISTYLE
public static final int ATTR_ISTYLE
See Also:
Constant Field Values
ATTR_MAXLENGTH
public static final int ATTR_MAXLENGTH
See Also:
Constant Field Values
ATTR_NAME
public static final int ATTR_NAME
See Also:
Constant Field Values
ATTR_VALUE
public static final int ATTR_VALUE
See Also:
Constant Field Values
ATTR_FOR
public static final int ATTR_FOR
See Also:
Constant Field Values
ATTR_XMLSPACE
public static final int ATTR_XMLSPACE
See Also:
Constant Field Values
Field Detail
1232
See Also:
Constant Field Values
ATTR_SELECTED
public static final int ATTR_SELECTED
See Also:
Constant Field Values
ATTR_ABBR
public static final int ATTR_ABBR
See Also:
Constant Field Values
ATTR_AXIS
public static final int ATTR_AXIS
See Also:
Constant Field Values
ATTR_COLSPAN
public static final int ATTR_COLSPAN
See Also:
Constant Field Values
ATTR_HEADERS
public static final int ATTR_HEADERS
See Also:
Constant Field Values
ATTR_ROWSPAN
public static final int ATTR_ROWSPAN
See Also:
Constant Field Values
ATTR_SCOPE
public static final int ATTR_SCOPE
See Also:
Constant Field Values
ATTR_VALIGN
public static final int ATTR_VALIGN
See Also:
Constant Field Values
ATTR_START
public static final int ATTR_START
See Also:
Constant Field Values
ATTR_MEDIA
public static final int ATTR_MEDIA
See Also:
Constant Field Values
Field Detail
1233
See Also:
Constant Field Values
ATTR_SUMMARY
public static final int ATTR_SUMMARY
See Also:
Constant Field Values
ATTR_CONTENT
public static final int ATTR_CONTENT
See Also:
Constant Field Values
ATTR_HTTPEQUIV
public static final int ATTR_HTTPEQUIV
See Also:
Constant Field Values
ATTR_SCHEME
public static final int ATTR_SCHEME
See Also:
Constant Field Values
ATTR_COLS
public static final int ATTR_COLS
See Also:
Constant Field Values
ATTR_ROWS
public static final int ATTR_ROWS
See Also:
Constant Field Values
ATTR_DIR
public static final int ATTR_DIR
See Also:
Constant Field Values
ATTR_BORDER
public static final int ATTR_BORDER
See Also:
Constant Field Values
ATTR_COLOR
public static final int ATTR_COLOR
See Also:
Constant Field Values
ATTR_FACE
public static final int ATTR_FACE
See Also:
Constant Field Values
Field Detail
1234
See Also:
Constant Field Values
ATTR_COORDS
public static final int ATTR_COORDS
See Also:
Constant Field Values
ATTR_USEMAP
public static final int ATTR_USEMAP
See Also:
Constant Field Values
ATTR_LANG
public static final int ATTR_LANG
See Also:
Constant Field Values
ATTR_CELLSPACING
public static final int ATTR_CELLSPACING
See Also:
Constant Field Values
ATTR_CELLPADDING
public static final int ATTR_CELLPADDING
See Also:
Constant Field Values
ATTR_FRAME
public static final int ATTR_FRAME
See Also:
Constant Field Values
ATTR_RULES
public static final int ATTR_RULES
See Also:
Constant Field Values
ATTR_DISABLED
public static final int ATTR_DISABLED
See Also:
Constant Field Values
ATTR_READONLY
public static final int ATTR_READONLY
See Also:
Constant Field Values
ATTR_ISMAP
public static final int ATTR_ISMAP
See Also:
Constant Field Values
Field Detail
1235
See Also:
Constant Field Values
COLOR_BLACK
public static final int COLOR_BLACK
See Also:
Constant Field Values
COLOR_BLUE
public static final int COLOR_BLUE
See Also:
Constant Field Values
COLOR_FUCHSIA
public static final int COLOR_FUCHSIA
See Also:
Constant Field Values
COLOR_GRAY
public static final int COLOR_GRAY
See Also:
Constant Field Values
COLOR_GREEN
public static final int COLOR_GREEN
See Also:
Constant Field Values
COLOR_LIME
public static final int COLOR_LIME
See Also:
Constant Field Values
COLOR_MAROON
public static final int COLOR_MAROON
See Also:
Constant Field Values
COLOR_NAVY
public static final int COLOR_NAVY
See Also:
Constant Field Values
COLOR_OLIVE
public static final int COLOR_OLIVE
See Also:
Constant Field Values
COLOR_PURPLE
public static final int COLOR_PURPLE
See Also:
Constant Field Values
Field Detail
1236
See Also:
Constant Field Values
COLOR_SILVER
public static final int COLOR_SILVER
See Also:
Constant Field Values
COLOR_TEAL
public static final int COLOR_TEAL
See Also:
Constant Field Values
COLOR_WHITE
public static final int COLOR_WHITE
See Also:
Constant Field Values
COLOR_YELLOW
public static final int COLOR_YELLOW
See Also:
Constant Field Values
COLOR_ORANGE
public static final int COLOR_ORANGE
See Also:
Constant Field Values
Constructor Detail
HTMLElement
protected HTMLElement()
Method Detail
Field Detail
1237
Adds the specified attribute and value to this Element if it is supported for the
Element and has a valid value.
Overrides:
setAttribute in class Element
Parameters:
attribute - The attribute's name
value - The attribute's value
Returns:
a positive error code or -1 if attribute is supported and valid
setAttributeById
public void setAttributeById(int attrId,
String value)
Returns a list of supported attributes for this tag. Note that the list does not include
the core attributes that are supported on almost all tags
Returns:
a list of supported attributes for this tag
getTagName
public String getTagName()
Method Detail
1238
Method Detail
1239
Method Detail
1240
Class HTMLComponent
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.html.HTMLComponent
All Implemented Interfaces:
Animation, ActionListener, StyleListener, IOCallback, Iterable<Component>
Deprecated.
this component includes some customizability advantages but its probably better for 99% of the use
cases to use the WebBrowser Component from the Components package. That component works
with the native browser when applicable which is a far superior approach.
public class
extends Container
implements ActionListener, IOCallback
HTMLComponent is a Codename One Component that renders HTML documents that conform to the
XHTML Mobile Profile 1.0
Field Summary
Constructor Summary
Constructor and Description
HTMLComponent()
Deprecated.
Constructs HTMLComponent
HTMLComponent(DocumentRequestHandler handler)
Deprecated.
Constructs HTMLComponent
Method Summary
Modifier and Type
void
Deprecated.
{Invoked when an action occurred on a component}
addCharEntitiesRange(String[] symbols, int startcode)
void
Deprecated.
Adds the given symbols array to the user defined char entities
table with the startcode provided as the code of the first string,
startcode+1 for the second etc.
addCharEntity(String symbol, int code)
void
Class HTMLComponent
Deprecated.
Adds the given symbol and code to the user defined char entities
table.
1241
Deprecated.
Sets the given Codename One font for use with
HTMLComponents.
addSpecialKey(String specialKeyName, int specialKeyCode)
static void
Deprecated.
Adds support for a special key to be used as an accesskey.
animate()
boolean
Deprecated.
Allows the animation to reduce "repaint" calls when it returns false.
cancel()
void
Deprecated.
Cancels the loading of the current page
deinitialize()
protected void
Deprecated.
If the component is taken off for any reason, makes sure access
keys are not active
getDocumentInfo()
DocumentInfo
Deprecated.
Returns the DocumentInfo that currently represents the document
loaded/shown
getDOM()
HTMLElement
Deprecated.
Returns the DOM representing this document
getHTMLCallback()
HTMLCallback
Deprecated.
Returns the HTMLCallback that is set on this HTMLComponent
getPageStatus()
int
Deprecated.
Returns the page status
getPageURL()
String
Deprecated.
Returns the page's URL
getPropertyNames()
String[]
Deprecated.
A component may expose mutable property names for a UI
designer to manipulate, this API is designed for usage internally
by the GUI builder code
getPropertyTypes()
Class[]
Deprecated.
Matches the property names method (see that method for further
details).
getPropertyValue(String name)
Object
Deprecated.
Returns the current value of the property name, this method is
used by the GUI builder
getRequestHandler()
DocumentRequestHandler
Deprecated.
Returns the document request handler
getTitle()
String
Deprecated.
Returns the HTML page's title as described in its TITLE tag
initComponent()
protected void
Deprecated.
Overrides initComponent to add the key listeners to the access
keys when the component is first added to the form/displayed This
is useful when the component is added only after the page was
read
isEventsEnabled()
boolean
Method Summary
Deprecated.
Returns the current status of the events enabled flag
1242
Deprecated.
layoutContainer()
void
Deprecated.
{Performs the layout of the container if a layout is necessary}
refreshDOM()
void
Deprecated.
Refreshes the current DOM so it any changes done after loading
will be rendered.
scrollPages(int pages, boolean animate)
void
Deprecated.
Scrolls the HTMLComponent several pages forward/backward.
scrollPixels(int pixels, boolean animate)
void
Deprecated.
Scrolls the HTMLComponent several pixels forward/backward.
scrollToElement(HTMLElement element, boolean animate)
void
Deprecated.
Scrolls the HTMLComponent to the specified element
setAutoFocusOnFirstLink(boolean autoFocus)
void
Deprecated.
Determines whether to auto-focus on the first link after page load
Note that focusing will happen only if the link is within a visible
range (no scrolling is performed since this is rarely a wanted
behaviour in this case)
setBodyText(String htmlText)
void
Deprecated.
Sets the given string containing HTML code as this
HTMLComponent's body
setBodyText(String htmlText, String encoding)
boolean
Deprecated.
Sets the given string containing HTML code as this
HTMLComponent's body.
setCSSSupportedMediaTypes(String[] supportedMediaTypes)
static void
Deprecated.
Sets the supported CSS media types to the given strings.
setDefaultFont(String fontKey, Font font)
void
Deprecated.
Sets the default font for this HTMLComponent
setDOM(HTMLElement dom)
void
Deprecated.
Sets this HTMLComponent to render the document in the
specified DOM.
setDOM(HTMLElement dom, String baseURL)
void
Deprecated.
Sets this HTMLComponent to render the document in the
specified DOM
setEventsEnabled(boolean enabled)
void
Deprecated.
Sets whether the active controls in the HTML will trigger events,
and whether the DOM will change dynamically due to user input.
setHTML(String htmlText, String encoding, String title,
boolean isFullHTML)
boolean
Deprecated.
Sets the given string containing HTML code either as this
HTMLComponent's body or as the full HTML.
setHTMLCallback(HTMLCallback callback)
void
Deprecated.
Sets an HTMLCallback to listen to this HTMLCOmponent
void
setIgnoreCSS(boolean ignore)
Deprecated.
Method Summary
1243
Deprecated.
Sets the maximum number of threads to use for image download
setPage(String pageURL)
Deprecated.
Sets this HTMLComponent to render the document in the
specified URL
void
setPageStyle(Style pageStyle)
Deprecated.
Sets the style of the page, allowing for example to set
transparency to the main page.
void
setPageUIID(String pageUIID)
Deprecated.
Sets the UIID of the page (the internal container) This applies not
only to the current page, but rather to all pages created with this
HTMLComponent instance.
void
setParser(HTMLParser parser)
Deprecated.
Sets a custom HTMLParser for this HTMLComponent By default,
a new HTMLParser instance is created for each
HTMLComponent, use this method if you have a custom parser.
void
Deprecated.
Sets a new value to the given property, returns an error message
if failed and null if successful.
setRequestHandler(DocumentRequestHandler handler)
Deprecated.
Changes the document request handler
void
setShowImages(boolean show)
Deprecated.
Sets whether this HTMLComponent will download and show
linked images or not
void
setSupressExceptions(boolean supressExceptions)
Deprecated.
void
Deprecated.
This method should be called only by
AsyncDocumentRequestHandler implementations after an async
fetch of a document
void
1244
Constructor Detail
HTMLComponent
public HTMLComponent()
Deprecated.
Constructs HTMLComponent
HTMLComponent
public HTMLComponent(DocumentRequestHandler handler)
Deprecated.
Constructs HTMLComponent
Parameters:
1245
Method Detail
addFont
public static void addFont(String fontKey,
Font font)
Deprecated.
Sets the given Codename One font for use with HTMLComponents. The font key can
contain information about the following attributes: * The font family - i.e. Arial, Times
New Roman etc. * The font size - in pixels (i.e. 12, 14 etc.) * The font style - bold,
italic or both (no need to specify plain) * The font tag assignments - if this font should
be used for any HTML specific tags they should be specified - i.e. h1, kbd etc. The
key is just a concatenation of all attributes seperated with a dot. Examples for valid
keys: arial.12 - Describes a plain font from the arial family in size 12 arial.16.bold - A
bold arial font in size 16 courier.italic.bold.20 - A bold and italic courier font in size 20
arial.20.h1 - A plain arial font, size 20, that should be used for contents of the H1 tag
code.kbd.samp - A font that should be used for the CODE, KBD and SAMP tags Note
that the order of the attributes is not important and also that the case is ignored. This
means that arial.12.bold.italic.h3 is equivalent to itALIc.H3.arial.BOLD.12 Also note
that while you do not have to provide all the info for the font, but the info helps the
rendering engine to reuse fonts when suitable. For example, if you have a 16px arial
bold font which you want to use for H2, you can simply add it as "h2", but if you add it
as "arial.16.bold.h2" then if the current font is arial.16 and the renderer encounters a
B tag, it will know it can use the font you added as the bold counterpart of the current
font. When adding system fonts there is no need to describe the font, the usage of
setFont with system fonts is usually just to assign them for tags. The rendering
engine knows to derive bold/italic/bigger/smaller fonts from other system fonts
(default or tag fonts) even if not added.
Parameters:
fontKey - The font key in the format described above
font - The actual Codename One font object
setParser
public void setParser(HTMLParser parser)
Deprecated.
Sets a custom HTMLParser for this HTMLComponent By default, a new HTMLParser
instance is created for each HTMLComponent, use this method if you have a custom
parser.
Parameters:
parser - The HTMLParser to use
addCharEntity
public void addCharEntity(String symbol,
int code)
Deprecated.
Adds the given symbol and code to the user defined char entities table. Symbols do
not need to include leading & and trailing ; - these will be trimmed if given as the
symbol
Parameters:
symbol - The symbol to add
code - The symbol's code
addSpecialKey
public static void addSpecialKey(String specialKeyName,
int specialKeyCode)
Deprecated.
Adds support for a special key to be used as an accesskey. The CSS property
-wap-accesskey supports special keys, for example "phone-send" that may have
different key codes per device. This method allows pairing between such keys to their
Constructor Detail
1246
Deprecated.
Adds the given symbols array to the user defined char entities table with the
startcode provided as the code of the first string, startcode+1 for the second etc.
Some strings in the symbols array may be null thus skipping code numbers.
Parameters:
symbols - The symbols to add
startcode - The symbol's code
setMaxThreads
public static void setMaxThreads(int threadsNum)
Deprecated.
Sets the maximum number of threads to use for image download
Parameters:
threadsNum - the maximum number of threads to use for image download
setCSSSupportedMediaTypes
public static void setCSSSupportedMediaTypes(String[] supportedMediaTypes)
Deprecated.
Sets the supported CSS media types to the given strings. Usually the default media
types ("all","handheld") should be suitable, but in case this runs on a device that
matches another profile, the developer can specify it here.
Parameters:
supportedMediaTypes - A string array containing the media types that should
be supported
getRequestHandler
public DocumentRequestHandler getRequestHandler()
Deprecated.
Returns the document request handler
Returns:
the document request handler
setRequestHandler
public void setRequestHandler(DocumentRequestHandler handler)
Deprecated.
Changes the document request handler
Parameters:
handler - the new document request handler
getDocumentInfo
public DocumentInfo getDocumentInfo()
Deprecated.
Returns the DocumentInfo that currently represents the document loaded/shown
Returns:
the DocumentInfo that currently represents the document loaded/shown
setHTMLCallback
public void setHTMLCallback(HTMLCallback callback)
Deprecated.
Sets an HTMLCallback to listen to this HTMLCOmponent
Parameters:
Method Detail
1247
Deprecated.
Returns the HTMLCallback that is set on this HTMLComponent
Returns:
the HTMLCallback that is set on this HTMLComponent or null if none
setDefaultFont
public void setDefaultFont(String fontKey,
Font font)
Deprecated.
Sets the default font for this HTMLComponent
Parameters:
fontKey - The font key in the format described in setFont (Can be null for
default font, but it is recommended to add a descriptive key if this is a bitmap
font to enable the font engine to use it in other cases as well)
font - The actual Codename One font object
setShowImages
public void setShowImages(boolean show)
Deprecated.
Sets whether this HTMLComponent will download and show linked images or not
Parameters:
show - true to show images, false otherwise
setIgnoreCSS
public void setIgnoreCSS(boolean ignore)
Deprecated.
Sets whether this HTMLComponent will ignore all CSS.directives. This includes
external CSS files (which won't be downloaded), embedded CSS segmentsand style
tags and attributes. By default this is false.
Parameters:
ignore - true to ignore CSS directives, false otherwise
scrollPixels
public void scrollPixels(int pixels,
boolean animate)
Deprecated.
Scrolls the HTMLComponent several pixels forward/backward.
Parameters:
pixels - The number of pixels to scroll (positive for forward and negative for
backward)
animate - true to animate the scrolling, false otherwise
scrollPages
public void scrollPages(int pages,
boolean animate)
Deprecated.
Scrolls the HTMLComponent several pages forward/backward. TO scroll to the start
or end of the document, one can provide a very big number.
Parameters:
pages - The number of pages to scroll (positive for forward and negative for
backward)
animate - true to animate the scrolling, false otherwise
scrollToElement
public void scrollToElement(HTMLElement element,
boolean animate)
Method Detail
1248
Deprecated.
Sets the given string containing HTML code as this HTMLComponent's body
Parameters:
htmlText - The HTML body to set
setBodyText
public boolean setBodyText(String htmlText,
String encoding)
Deprecated.
Sets the given string containing HTML code as this HTMLComponent's body. The
string is read using the specified encoding. If the encoding is not supported it will be
read without encoding
Parameters:
htmlText - The HTML body to set
encoding - The encoding to use when reading the HTML i.e. UTF8,
ISO-8859-1 etc.
Returns:
true if the encoding succeeded, false otherwise
setHTML
public boolean setHTML(String htmlText,
String encoding,
String title,
boolean isFullHTML)
Deprecated.
Sets the given string containing HTML code either as this HTMLComponent's body or
as the full HTML. The string is read using the specified encoding. If the encoding is
not supported it will be read without encoding
Parameters:
htmlText - The HTML to set
encoding - The encoding to use when reading the HTML i.e. UTF8,
ISO-8859-1 etc.
title - The HTML title, or null if none (Used only when isFullHTML is false)
isFullHTML - true if this is a full HTML document (with html/body tags), false if
this HTML should be used as the HTMLComponent's body
Returns:
true if the encoding succeeded, false otherwise
cancel
public void cancel()
Deprecated.
Cancels the loading of the current page
setPage
public void setPage(String pageURL)
Deprecated.
Sets this HTMLComponent to render the document in the specified URL
Parameters:
pageURL - The URL containing the HTML document
Method Detail
1249
Deprecated.
Sets the style of the page, allowing for example to set transparency to the main page.
This applies not only to the current page, but rather to all pages created with this
HTMLComponent instance. If both a UIID and a pageStyle were set, the style
overrides the UIID.
Parameters:
pageStyle - The style to set to the page
setPageUIID
public void setPageUIID(String pageUIID)
Deprecated.
Sets the UIID of the page (the internal container) This applies not only to the current
page, but rather to all pages created with this HTMLComponent instance. If both a
UIID and a pageStyle were set, the style overrides the UIID.
Parameters:
pageUIID - The UIID that should be applied to the page
streamReady
public void streamReady(InputStream is,
DocumentInfo docInfo)
Deprecated.
This method should be called only by AsyncDocumentRequestHandler
implementations after an async fetch of a document
Specified by:
streamReady in interface IOCallback
Parameters:
is - The InputStream of the document
docInfo - The document info
setDOM
public void setDOM(HTMLElement dom)
Deprecated.
Sets this HTMLComponent to render the document in the specified DOM. Note that
relative links if any will be disabled. To allow relative links with DOM use
setDOM(HTMLElement dom,String baseURL)
Parameters:
dom - An HTMLElement representing the root of the HTML document
Throws:
IllegalArgumentException - if the HTMLElement supplied is not an 'html' tag
setDOM
public void setDOM(HTMLElement dom,
String baseURL)
Deprecated.
Sets this HTMLComponent to render the document in the specified DOM
Parameters:
dom - An HTMLElement representing the root of the HTML document
baseURL - The base URL for this DOM (Necessary if document references
relative links)
Throws:
IllegalArgumentException - if the HTMLElement supplied is not an 'html' tag
getDOM
public HTMLElement getDOM()
Deprecated.
Returns the DOM representing this document
Returns:
An HTMLElement representing the entire current HTML document
Method Detail
1250
refreshDOM
public void refreshDOM()
Deprecated.
Refreshes the current DOM so it any changes done after loading will be rendered.
setEventsEnabled
public void setEventsEnabled(boolean enabled)
Deprecated.
Sets whether the active controls in the HTML will trigger events, and whether the
DOM will change dynamically due to user input. If so the events are dispatched via
HTMLCallback methods actionPerformed, focusGained/Lost, selectionChanged and
dataChanged The default is false in order not to add more overhead if these are not
needed.
Parameters:
enabled - true to enable event dispatching, false otherwise
isEventsEnabled
public boolean isEventsEnabled()
Deprecated.
Returns the current status of the events enabled flag
Returns:
true if events are enabled, false if not
setAutoFocusOnFirstLink
public void setAutoFocusOnFirstLink(boolean autoFocus)
Deprecated.
Determines whether to auto-focus on the first link after page load Note that focusing
will happen only if the link is within a visible range (no scrolling is performed since this
is rarely a wanted behaviour in this case)
Parameters:
autoFocus - true to auto-focus, false otherwise
animate
public boolean animate()
Deprecated.
Description copied from class: Component
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Component
Returns:
true if a repaint is desired or false if no repaint is necessary
getTitle
public String getTitle()
Deprecated.
Returns the HTML page's title as described in its TITLE tag
Returns:
the HTML page's title as described in its TITLE tag
getPageURL
public String getPageURL()
Deprecated.
Returns the page's URL
Returns:
Method Detail
1251
Deprecated.
Returns the page status
Returns:
the page status (One of the STATUS_* constants in HTMLCallback)
initComponent
protected void initComponent()
Deprecated.
Overrides initComponent to add the key listeners to the access keys when the
component is first added to the form/displayed This is useful when the component is
added only after the page was read
Overrides:
initComponent in class Component
deinitialize
protected void deinitialize()
Deprecated.
If the component is taken off for any reason, makes sure access keys are not active
Overrides:
deinitialize in class Component
layoutContainer
public void layoutContainer()
Deprecated.
{Performs the layout of the container if a layout is necessary}
Overrides:
layoutContainer in class Container
actionPerformed
public void actionPerformed(ActionEvent evt)
Deprecated.
{Invoked when an action occurred on a component}
Specified by:
actionPerformed in interface ActionListener
Parameters:
evt - event object describing the source of the action as well as its trigger
getPropertyNames
public String[] getPropertyNames()
Deprecated.
A component may expose mutable property names for a UI designer to manipulate,
this API is designed for usage internally by the GUI builder code
Overrides:
getPropertyNames in class Component
Returns:
the property names allowing mutation
getPropertyTypes
public Class[] getPropertyTypes()
Deprecated.
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
Method Detail
1252
Deprecated.
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Deprecated.
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
isSupressExceptions
public boolean isSupressExceptions()
Deprecated.
Returns:
the supressExceptions
setSupressExceptions
public void setSupressExceptions(boolean supressExceptions)
Deprecated.
Parameters:
supressExceptions
Method Detail
1253
Interface HTMLCallback
All Superinterfaces:
ParserCallback
All Known Implementing Classes:
Ads, DefaultHTMLCallback
public interface
extends ParserCallback
HTMLCallback is used to dispatch document lifecycle events. Most methods are called on the EDT
thread, except parsingError, getAutoComplete and getLinkProperties
Field Summary
Modifier
and Type
static
int
static
int
static
int
Error code denoting that a connection to the resource provider/server could not
be made
ERROR_CSS_ATTIBUTE_VALUE_INVALID
Error code denoting that an invalid attribute value was found in the CSS
ERROR_CSS_ATTRIBUTE_NOT_SUPPORTED
Error code denoting that an unsupported CSS attribute (by XHTML-MP 1.0
standards) was found in the HTML or external CSS files
ERROR_CSS_NO_BASE_URL
static
int
static
int
static
int
static
int
static
int
Error code denoting that a relative URL was referenced from a document with no
base URL (A document that was loaded via setBody/setHTML/setDOM and not
via setPage) In this case the return value of parsingError is not considered parsing continues and the resource at the URL (CSS file/image) is ignored
ERROR_CSS_NOT_FOUND
Error code denoting that a CSS file referenced from the HTML or from another
external CSS file was not found
ERROR_IMAGE_BAD_FORMAT
Error code denoting that an image referenced from the HTML could not be
loaded
ERROR_IMAGE_NOT_FOUND
Error code denoting that an image referenced from the HTML was not found
ERROR_INVALID_TAG_HIERARCHY
Error code denoting that a tag contains tags it shouldn't, or that a tag doesn't
have the parent tag it should have
ERROR_NO_BASE_URL
static
int
Error code denoting that a relative URL was referenced from a document with no
base URL (A document that was loaded via setBody/setHTML/setDOM and not
via setPage) In this case the return value of parsingError is not considered parsing continues and the resource at the URL (CSS file/image) is ignored
static
int
FIELD_PASSWORD
static
int
FIELD_TEXT
static
int
LINK_FORBIDDEN
static
int
LINK_REGULAR
static
int
LINK_VISTED
Interface HTMLCallback
A password field
A text field
A forbidden link (not to be rendered as a link but as a regular label)
A regular link
A link that was visited before
1254
STATUS_CANCELLED
static
int
STATUS_COMPLETED
static
int
STATUS_CONNECTED
static
int
The page was displayed on screen - but at this stage some images and CSS
files may still be loading in the background
STATUS_ERROR
static
int
static
int
This is returned in the page status if no page has been set to the
HTMLComponent
static
int
STATUS_PARSED
static
int
STATUS_REDIRECTED
static
int
STATUS_REQUESTED
Method Summary
Modifier
and Type
void
void
String
Called when the user types in a TextField inside the HTMLComponent This
method will be called only if HTMLComponent.isEventsEnabled() is true
fieldSubmitted(HTMLComponent htmlC, TextArea ta, String actionURL,
String id, String value, int type, String errorMsg)
Called when one of the controls in the HTMLComponent obtained focus This
method will be called only if HTMLComponent.isEventsEnabled() is true
focusLost(Component cmp, HTMLComponent htmlC, HTMLElement element)
void
Called when one of the controls in the HTMLComponent lost focus This method
will be called only if HTMLComponent.isEventsEnabled() is true
getAutoComplete(HTMLComponent htmlC, String actionURL, String id)
String
int
boolean
void
Field Summary
1255
Called when the user selects an item in a List inside the HTMLComponent Note:
Selection is traversing through the items - once the user has actually decided, an
ActionEvent will be sent as well This method will be called only if
HTMLComponent.isEventsEnabled() is true
void
void
Field Detail
ERROR_CONNECTING
static final int ERROR_CONNECTING
Error code denoting that a connection to the resource provider/server could not be
made
See Also:
Constant Field Values
ERROR_IMAGE_NOT_FOUND
static final int ERROR_IMAGE_NOT_FOUND
Error code denoting that an image referenced from the HTML was not found
See Also:
Constant Field Values
ERROR_IMAGE_BAD_FORMAT
static final int ERROR_IMAGE_BAD_FORMAT
Error code denoting that an image referenced from the HTML could not be loaded
See Also:
Constant Field Values
ERROR_NO_BASE_URL
static final int ERROR_NO_BASE_URL
Error code denoting that a relative URL was referenced from a document with no
base URL (A document that was loaded via setBody/setHTML/setDOM and not via
setPage) In this case the return value of parsingError is not considered - parsing
continues and the resource at the URL (CSS file/image) is ignored
See Also:
Constant Field Values
ERROR_INVALID_TAG_HIERARCHY
static final int ERROR_INVALID_TAG_HIERARCHY
Error code denoting that a tag contains tags it shouldn't, or that a tag doesn't have
the parent tag it should have
See Also:
Constant Field Values
Method Summary
1256
This is returned in the page status if no page has been set to the HTMLComponent
See Also:
Constant Field Values
STATUS_ERROR
static final int STATUS_ERROR
The page was displayed on screen - but at this stage some images and CSS files
may still be loading in the background
See Also:
Constant Field Values
STATUS_COMPLETED
static final int STATUS_COMPLETED
The page and all of its referenced images and CSS files were loaded completely
See Also:
Constant Field Values
STATUS_REDIRECTED
static final int STATUS_REDIRECTED
Field Detail
1257
A text field
See Also:
Constant Field Values
FIELD_PASSWORD
static final int FIELD_PASSWORD
A password field
See Also:
Constant Field Values
LINK_REGULAR
static final int LINK_REGULAR
A regular link
See Also:
Constant Field Values
LINK_VISTED
static final int LINK_VISTED
Error code denoting that an unsupported CSS attribute (by XHTML-MP 1.0
standards) was found in the HTML or external CSS files
See Also:
Constant Field Values
ERROR_CSS_ATTIBUTE_VALUE_INVALID
static final int ERROR_CSS_ATTIBUTE_VALUE_INVALID
Error code denoting that an invalid attribute value was found in the CSS
See Also:
Constant Field Values
ERROR_CSS_NOT_FOUND
static final int ERROR_CSS_NOT_FOUND
Error code denoting that a CSS file referenced from the HTML or from another
external CSS file was not found
See Also:
Constant Field Values
ERROR_CSS_NO_BASE_URL
static final int ERROR_CSS_NO_BASE_URL
Error code denoting that a relative URL was referenced from a document with no
base URL (A document that was loaded via setBody/setHTML/setDOM and not via
setPage) In this case the return value of parsingError is not considered - parsing
continues and the resource at the URL (CSS file/image) is ignored
See Also:
Field Detail
1258
Method Detail
titleUpdated
void titleUpdated(HTMLComponent htmlC,
String title)
Called whenever a field is submitted to a form. This can be used to perform sanity
checks and/or to store values for auto complete.
Parameters:
htmlC - The HTMLComponent in which this event occured
ta - The TextArea/TextField of this field
actionURL - The action URL of the form
id - The ID of the field
value - The value entered
type - The type of the field, one of the FIELD_* constants
errorMsg - The error message if any error occured (i.e. input validation error)
or null if no error occured
Returns:
The string to submit to the form (Should return value if nothing changed)
getAutoComplete
String getAutoComplete(HTMLComponent htmlC,
String actionURL,
String id)
Called on form creation and enabled implementations of this method to return a value
to preset in a form field. This can be used to auto complete previously entered value
Note that this method is always called NOT on the EDT thread.
Parameters:
htmlC - The HTMLComponent in which this event occured
actionURL - The action URL of the form
id - The ID of the field
Returns:
The string to place in the indicated field
getLinkProperties
int getLinkProperties(HTMLComponent htmlC,
String url)
Method Detail
1259
Called when a link is clicked. This can be used to process links that needs
additional/alternate handling than fetching an HTML.
Parameters:
htmlC - The HTMLComponent
url - The Link URL
Returns:
true if regular link processing should continue, false otherwise
actionPerformed
void actionPerformed(ActionEvent evt,
HTMLComponent htmlC,
HTMLElement element)
Called when one of the controls in the HTMLComponent obtained focus This method
will be called only if HTMLComponent.isEventsEnabled() is true
Parameters:
cmp - The component that triggered the event
htmlC - The HTMLComponent
element - The element associated with the component that triggered the
event
focusLost
void focusLost(Component cmp,
HTMLComponent htmlC,
HTMLElement element)
Called when one of the controls in the HTMLComponent lost focus This method will
be called only if HTMLComponent.isEventsEnabled() is true
Parameters:
cmp - The component that triggered the event
htmlC - The HTMLComponent
element - The element associated with the component that triggered the
event
selectionChanged
void selectionChanged(int oldSelected,
int newSelected,
HTMLComponent htmlC,
List list,
HTMLElement element)
Method Detail
1260
Called when the user types in a TextField inside the HTMLComponent This method
will be called only if HTMLComponent.isEventsEnabled() is true
Parameters:
type - the type data change; REMOVED, ADDED or CHANGED
index - item index in a list model
htmlC - The HTMLComponent
textField - The TextField that triggerd the event
element - The element associated with the component that triggered the
event (Should be TAG_INPUT with type text/password)
parsingError
boolean parsingError(int errorId,
String tag,
String attribute,
String value,
String description)
Called when encountering an error while parsing the HTML document. When
implementing this, the developer should return true if the error should be ignored and
the document needs to be further parsed, or false to stop parsing and issue an error
to the user Note that this method is always called NOT on the EDT thread.
Parameters:
errorId - The error ID, one of the ERROR_* constants
tag - The tag in which the error occured (Can be null for non-tag related
errors)
attribute - The attribute in which the error occured (Can be null for
non-attribute related errors)
value - The value in which the error occured (Can be null for non-value
related errors)
description - A verbal description of the error
Returns:
true to continue parsing, false to stop
Method Detail
1261
Interface DocumentRequestHandler
All Known Subinterfaces:
AsyncDocumentRequestHandler
All Known Implementing Classes:
AsyncDocumentRequestHandlerImpl, DefaultDocumentRequestHandler
public interface
Method Summary
Modifier and
Type
InputStream
Method Detail
resourceRequested
InputStream resourceRequested(DocumentInfo docInfo)
Interface DocumentRequestHandler
1262
Class DocumentInfo
java.lang.Object
com.codename1.ui.html.DocumentInfo
public class
extends Object
DocumentInfo holds important information about a document that is loading. This class is constructed
internally by HTMLComponent and HTMLForm and is sent to the RequestHandler. It is intended for
the RequestHandler to use and update (For example update encoding according to the HTTP
response, update URL in case of a redirect etc.)
Field Summary
Modifier and Type
static String
static String
static int
static int
static int
Method Summary
Modifier
and Type
String
String
int
String
String
String
boolean
void
static
void
void
Method Detail
Sets the document encoding (This can be determined via the charset attribute in
the response)
1263
void
setParams(String params)
void
void
void
Field Detail
ENCODING_ISO
public static final String ENCODING_ISO
Method Detail
setDefaultEncoding
public static void setDefaultEncoding(String encoding)
Method Summary
1264
Method Detail
1265
Sets the document encoding (This can be determined via the charset attribute in the
response)
Parameters:
encoding - the encoding to set. It is recommended to use the ENCODING_*
constants when possible to avoid typos
getBaseURL
public String getBaseURL()
Sets the base URL for this document. Usually this is deduced automatically from the
page URL, but in some cases this is different, for example when an HREF attribute is
provided in the BASE tag
Parameters:
baseURL - the baseURL to set
Method Detail
1266
Class DefaultHTMLCallback
java.lang.Object
com.codename1.ui.html.DefaultHTMLCallback
All Implemented Interfaces:
HTMLCallback, ParserCallback
public class
extends Object
implements HTMLCallback
This is a default implementation of HTMLCallback that basically doesn't do much but does keep the
HTMLComponent work intact. This class was created so developers will avoid pitfalls of
HTMLCallback, as using the wrong return values. Note that in any case an HTMLComponent doesn't
have to use an HTMLCallback.
Field Summary
Modifier
and Type
static
int
static
int
Error code denoting that an invalid attribute value was found in the CSS
ERROR_CSS_ATTRIBUTE_NOT_SUPPORTED
Error code denoting that an unsupported CSS attribute (by XHTML-MP 1.0
standards) was found in the HTML or external CSS files
ERROR_CSS_NO_BASE_URL
static
int
static
int
Error code denoting that a relative URL was referenced from a document with no
base URL (A document that was loaded via setBody/setHTML/setDOM and not
via setPage) In this case the return value of parsingError is not considered parsing continues and the resource at the URL (CSS file/image) is ignored
ERROR_CSS_NOT_FOUND
Error code denoting that a CSS file referenced from the HTML or from another
external CSS file was not found
Constructor Summary
Constructor and Description
DefaultHTMLCallback()
Class DefaultHTMLCallback
1267
Summary
Modifier
and Type
void
void
{Called when the user types in a TextField inside the HTMLComponent This
method will be called only if HTMLComponent.isEventsEnabled() is true}
fieldSubmitted(HTMLComponent htmlC, TextArea ta, String actionURL,
String id, String value, int type, String errorMsg)
String
{Called when one of the controls in the HTMLComponent obtained focus This
method will be called only if HTMLComponent.isEventsEnabled() is true}
void
{Called when one of the controls in the HTMLComponent lost focus This method
will be called only if HTMLComponent.isEventsEnabled() is true}
void
String
int
boolean
void
boolean
{Called when the user selects an item in a List inside the HTMLComponent
Note: Selection is traversing through the items - once the user has actually
decided, an ActionEvent will be sent as well This method will be called only if
HTMLComponent.isEventsEnabled() is true}
void
void
Field Detail
ERROR_CSS_ATTRIBUTE_NOT_SUPPORTED
public static final int ERROR_CSS_ATTRIBUTE_NOT_SUPPORTED
Error code denoting that an unsupported CSS attribute (by XHTML-MP 1.0
standards) was found in the HTML or external CSS files
See Also:
Constant Field Values
Method Summary
1268
Error code denoting that an invalid attribute value was found in the CSS
See Also:
Constant Field Values
ERROR_CSS_NOT_FOUND
public static final int ERROR_CSS_NOT_FOUND
Error code denoting that a CSS file referenced from the HTML or from another
external CSS file was not found
See Also:
Constant Field Values
ERROR_CSS_NO_BASE_URL
public static final int ERROR_CSS_NO_BASE_URL
Error code denoting that a relative URL was referenced from a document with no
base URL (A document that was loaded via setBody/setHTML/setDOM and not via
setPage) In this case the return value of parsingError is not considered - parsing
continues and the resource at the URL (CSS file/image) is ignored
See Also:
Constant Field Values
Constructor Detail
DefaultHTMLCallback
public DefaultHTMLCallback()
Method Detail
titleUpdated
public void titleUpdated(HTMLComponent htmlC,
String title)
{Called when encountering an error while parsing the XML document. When
implementing this, the developer should return true if the error should be ignored and
the document needs to be further parsed, or false to stop parsing and issue an error
to the user Note that this method is always called NOT on the EDT thread.}
Specified by:
parsingError in interface ParserCallback
Parameters:
errorId - The error ID, one of the ERROR_* constants
tag - The tag in which the error occured (Can be null for non-tag related
errors)
attribute - The attribute in which the error occured (Can be null for
non-attribute related errors)
Field Detail
1269
{Called whenever a field is submitted to a form. This can be used to perform sanity
checks and/or to store values for auto complete.}
Specified by:
fieldSubmitted in interface HTMLCallback
Parameters:
htmlC - The HTMLComponent in which this event occured
ta - The TextArea/TextField of this field
actionURL - The action URL of the form
id - The ID of the field
value - The value entered
type - The type of the field, one of the FIELD_* constants
errorMsg - The error message if any error occured (i.e. input validation error)
or null if no error occured
Returns:
The string to submit to the form (Should return value if nothing changed)
getAutoComplete
public String getAutoComplete(HTMLComponent htmlC,
String actionURL,
String id)
Method Detail
1270
in interface HTMLCallback
Parameters:
htmlC - The HTMLComponent
url - The Link URL
Returns:
LINK_REGULAR or LINK_VISITED or LINK_FORBIDDEN or a mask of
those
linkClicked
public boolean linkClicked(HTMLComponent htmlC,
String url)
{Called when a link is clicked. This can be used to process links that needs
additional/alternate handling than fetching an HTML.}
Specified by:
linkClicked in interface HTMLCallback
Parameters:
htmlC - The HTMLComponent
url - The Link URL
Returns:
true if regular link processing should continue, false otherwise
actionPerformed
public void actionPerformed(ActionEvent evt,
HTMLComponent htmlC,
HTMLElement element)
{Called when one of the controls in the HTMLComponent obtained focus This method
will be called only if HTMLComponent.isEventsEnabled() is true}
Specified by:
focusGained in interface HTMLCallback
Parameters:
cmp - The component that triggered the event
htmlC - The HTMLComponent
element - The element associated with the component that triggered the
event
focusLost
public void focusLost(Component cmp,
HTMLComponent htmlC,
HTMLElement element)
{Called when one of the controls in the HTMLComponent lost focus This method will
be called only if HTMLComponent.isEventsEnabled() is true}
Specified by:
focusLost in interface HTMLCallback
Parameters:
cmp - The component that triggered the event
htmlC - The HTMLComponent
element - The element associated with the component that triggered the
event
Method Detail
1271
{Called when the user selects an item in a List inside the HTMLComponent Note:
Selection is traversing through the items - once the user has actually decided, an
ActionEvent will be sent as well This method will be called only if
HTMLComponent.isEventsEnabled() is true}
Specified by:
selectionChanged in interface HTMLCallback
Parameters:
oldSelected - old selected index in list model
newSelected - new selected index in list model
htmlC - The HTMLComponent
list - The list that triggered the event (Usually a ComboBox but not always)
element - The element associated with the component that triggered the
event (Should be TAG_SELECT)
dataChanged
public void dataChanged(int type,
int index,
HTMLComponent htmlC,
TextField textField,
HTMLElement element)
{Called when the user types in a TextField inside the HTMLComponent This method
will be called only if HTMLComponent.isEventsEnabled() is true}
Specified by:
dataChanged in interface HTMLCallback
Parameters:
type - the type data change; REMOVED, ADDED or CHANGED
index - item index in a list model
htmlC - The HTMLComponent
textField - The TextField that triggerd the event
element - The element associated with the component that triggered the
event (Should be TAG_INPUT with type text/password)
Method Detail
1272
Class DefaultDocumentRequestHandler
java.lang.Object
com.codename1.ui.html.DefaultDocumentRequestHandler
All Implemented Interfaces:
AsyncDocumentRequestHandler, DocumentRequestHandler
Direct Known Subclasses:
AsyncDocumentRequestHandlerImpl
public class
extends Object
implements AsyncDocumentRequestHandler
Default implementation of the HTML components document request handler to allow simple HTML
support in Codename One. This version includes only the basics supported by MIDP e.g. resources
and jar file URL's such as jar:// and res://
Constructor Summary
Constructor and Description
DefaultDocumentRequestHandler()
Method Summary
Modifier and
Type
static
Resources
boolean
InputStream
void
static void
setResFile(Resources res)
void
protected
void
boolean
visitingURL(String url)
This method can be invoked to indicate a URL was visited fro tracking
wasURLVisited(String url)
Constructor Detail
Class DefaultDocumentRequestHandler
1273
Method Detail
resourceRequestedAsync
public void resourceRequestedAsync(DocumentInfo docInfo,
IOCallback callback)
This method can be invoked to indicate a URL was visited fro tracking
Parameters:
url - the url
wasURLVisited
public boolean wasURLVisited(String url)
Constructor Detail
1274
Method Detail
1275
Class AsyncDocumentRequestHandlerImpl
java.lang.Object
com.codename1.ui.html.DefaultDocumentRequestHandler
com.codename1.ui.html.AsyncDocumentRequestHandlerImpl
All Implemented Interfaces:
AsyncDocumentRequestHandler, DocumentRequestHandler
public class
extends DefaultDocumentRequestHandler
Implementation of the HTML components document request handler to allow simple HTML support in
CodenameOne.
Field Summary
Modifier and Type
LOCK
Constructor Summary
Constructor and Description
AsyncDocumentRequestHandlerImpl()
Method Summary
Modifier and Type
protected
ConnectionRequest
InputStream
void
Field Detail
Class AsyncDocumentRequestHandlerImpl
1276
Constructor Detail
AsyncDocumentRequestHandlerImpl
public AsyncDocumentRequestHandlerImpl()
Method Detail
resourceRequestedAsync
public void resourceRequestedAsync(DocumentInfo docInfo,
IOCallback callback)
Field Detail
1277
Interface AsyncDocumentRequestHandler
All Superinterfaces:
DocumentRequestHandler
All Known Implementing Classes:
AsyncDocumentRequestHandlerImpl, DefaultDocumentRequestHandler
public interface
extends DocumentRequestHandler
Provides an interface for Asynchronous request handling. The resourceRequestedAsync will be called
without creating a new thread, but it has to return immediately. This can be useful when an external
threading mechanism is to be utilized instead of the internal threading which is done by
HTMLComponent. Note that the resourceRequested method should be implemented as well, since
HTMLComponent has situations in which a resource needs to be fetched immediately (And block all
the rest).
Method Summary
Modifier and
Type
void
Method Detail
resourceRequestedAsync
void resourceRequestedAsync(DocumentInfo docInfo,
IOCallback callback)
Method Detail
1278
Interface Shape
All Known Implementing Classes:
GeneralPath, Rectangle, Rectangle2D
public interface
An interface that can be implemented by any class that wants to be drawable as a shape.
See Also:
for a concrete implementation of Shape.,
Graphics.drawShape(com.codename1.ui.geom.Shape, com.codename1.ui.Stroke),
Graphics.fillShape(com.codename1.ui.geom.Shape)
Method Summary
Modifier and
Type
boolean
Rectangle
float[]
getPathIterator()
PathIterator
PathIterator
intersection(Rectangle rect)
Returns the shape formed by the intersection of this shape and the
provided rectangle.
Shape
isRectangle()
boolean
Method Detail
getPathIterator
PathIterator getPathIterator()
Gets an iterator where all points are transformed by the provided transform.
Note: If Transform.isSupported() is false, then using this iterator will throw a
Runtime Exception.
Parameters:
transform
Returns:
Method Detail
1279
Returns the bounding rectangle for the shape. This should be the smallest rectangle
such that the all path segments in the shape are contained within it.
Returns:
A Rectangle that comprises the bounds of the shape.
getBounds2D
float[] getBounds2D()
Returns the shape formed by the intersection of this shape and the provided
rectangle.
Parameters:
rect - A rectangle with which to form an intersection.
Returns:
The shape formed by intersecting the current shape with the provided
rectangle.
Method Detail
1280
Class Rectangle2D
java.lang.Object
com.codename1.ui.geom.Rectangle2D
All Implemented Interfaces:
Shape
public class
extends Object
implements Shape
Represents a Rectangle position (x, y) and Dimension (width, height), this is useful for measuring
coordinates within the application.
Constructor Summary
Constructor and Description
Rectangle2D()
Creates a new instance of Rectangle at position (x, y) and with predefine dimension
Rectangle2D(double x, double y, double w, double h)
Creates a new instance of Rectangle at position (x, y) and with predefine width and height
Rectangle2D(Rectangle2D rect)
A copy Constructor
Method Summary
Modifier and
Type
boolean
Checks whether or not this Rectangle contains the point at the specified
location (rX, rY).
contains(double rX, double rY, double rWidth, double rHeight)
boolean
contains(double x1, double y1, double w1, double h1, double x2,
static boolean double y2, double w2, double h2)
contains(int x, int y)
boolean
Rectangle
float[]
double
PathIterator
Class Rectangle2D
1281
Dimension2D
double
double
double
Rectangle2D
static void
Returns a rectangle that intersects the given rectangle with this rectangle
intersection(double rrX, double rrY, double rrW, double rrH,
double rtx1, double rty1, double rtw2, double rth2,
Rectangle2D dest)
Returns a rectangle that intersects the given rectangle with this rectangle
intersection(Rectangle rect)
Returns the shape formed by the intersection of this shape and the
provided rectangle.
Shape
Rectangle2D
intersection(Rectangle2D r)
Returns a rectangle that intersects the given rectangle with this rectangle
intersects(double x, double y, double width, double height)
boolean
boolean
void
void
void
void
void
String
void
toString()
Constructor Detail
Rectangle2D
public Rectangle2D()
Method Summary
1282
Creates a new instance of Rectangle at position (x, y) and with predefine dimension
Parameters:
x - the x coordinate of the rectangle
y - the y coordinate of the rectangle
size - the Dimension of the rectangle
Rectangle2D
public Rectangle2D(double
double
double
double
x,
y,
w,
h)
Creates a new instance of Rectangle at position (x, y) and with predefine width and
height
Parameters:
x - the x coordinate of the rectangle
y - the y coordinate of the rectangle
w - the width of the rectangle
h - the height of the rectangle
Rectangle2D
public Rectangle2D(Rectangle2D rect)
A copy Constructor
Parameters:
rect - the Rectangle to copy
Method Detail
setBounds
public void setBounds(double
double
double
double
x,
y,
w,
h)
Constructor Detail
1283
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
setX
public void setX(int x)
Checks whether or not this Rectangle entirely contains the specified Rectangle.
Parameters:
rect - the specified Rectangle
Returns:
true if the Rectangle is contained entirely inside this Rectangle; false
otherwise
Method Detail
1284
rX,
rY,
rWidth,
rHeight)
Checks whether this Rectangle entirely contains the Rectangle at the specified
location (rX, rY) with the specified dimensions (rWidth, rHeight).
Parameters:
rX - the specified x coordinate
rY - the specified y coordinate
rWidth - the width of the Rectangle
rHeight - the height of the Rectangle
Returns:
true if the Rectangle specified by (rX, rY, rWidth, rHeight) is entirely enclosed
inside this Rectangle; false otherwise.
contains
public static boolean contains(double
double
double
double
double
double
double
double
x1,
y1,
w1,
h1,
x2,
y2,
w2,
h2)
Checks whether or not this Rectangle contains the point at the specified location (rX,
rY).
Parameters:
rX - the specified x coordinate
rY - the specified y coordinate
Returns:
true if the point (rX, rY) is inside this Rectangle; false otherwise.
intersection
public Rectangle2D intersection(double
double
double
double
rX,
rY,
rW,
rH)
Returns a rectangle that intersects the given rectangle with this rectangle
Parameters:
rX - rectangle to intersect with this rectangle
rY - rectangle to intersect with this rectangle
rW - rectangle to intersect with this rectangle
rH - rectangle to intersect with this rectangle
Returns:
the intersection
Method Detail
1285
Returns a rectangle that intersects the given rectangle with this rectangle
Parameters:
rrX - rectangle to intersect with this rectangle
rrY - rectangle to intersect with this rectangle
rrW - rectangle to intersect with this rectangle
rrH - rectangle to intersect with this rectangle
rtx1 - rectangle to intersect with this rectangle
rty1 - rectangle to intersect with this rectangle
rtw2 - rectangle to intersect with this rectangle
rth2 - rectangle to intersect with this rectangle
dest - result of the intersection are stored here
intersection
public Rectangle2D intersection(Rectangle2D r)
Returns a rectangle that intersects the given rectangle with this rectangle
Parameters:
r - rectangle to intersect with this rectangle
Returns:
the intersection
intersects
public boolean intersects(double
double
double
double
x,
y,
width,
height)
Determines whether or not this Rectangle and the specified Rectangle location (x, y)
with the specified dimensions (width, height), intersect. Two rectangles intersect if
their intersection is nonempty.
Parameters:
x - the specified x coordinate
y - the specified y coordinate
width - the width of the Rectangle
height - the height of the Rectangle
Returns:
true if the specified Rectangle and this Rectangle intersect; false otherwise.
intersects
public boolean intersects(Rectangle2D rect)
Determines whether or not this Rectangle and the specified Rectangle location (x, y)
with the specified dimensions (width, height), intersect. Two rectangles intersect if
their intersection is nonempty.
Parameters:
rect - the Rectangle to check intersection with
Returns:
true if the specified Rectangle and this Rectangle intersect; false otherwise.
intersects
public static boolean intersects(double
double
double
double
double
double
double
Method Detail
tx,
ty,
tw,
th,
x,
y,
width,
1286
Helper method allowing us to determine if two coordinate sets intersect. This saves
us the need of creating a rectangle object for a quick calculation
Parameters:
tx - x of first rectangle
ty - y of first rectangle
tw - width of first rectangle
th - height of first rectangle
x - x of second rectangle
y - y of second rectangle
width - width of second rectangle
height - height of second rectangle
Returns:
true if the rectangles intersect
getPathIterator
public PathIterator getPathIterator(Transform m)
{Gets an iterator where all points are transformed by the provided transform.
Note: If Transform.isSupported() is false, then using this iterator will throw a
Runtime Exception.
}
Specified by:
getPathIterator in interface Shape
Returns:
A PathIterator where points are transformed by the provided transform.
getPathIterator
public PathIterator getPathIterator()
{Returns the bounding rectangle for the shape. This should be the smallest rectangle
such that the all path segments in the shape are contained within it.}
Specified by:
getBounds in interface Shape
Returns:
A Rectangle that comprises the bounds of the shape.
getBounds2D
public float[] getBounds2D()
Method Detail
1287
Method Detail
1288
Class Rectangle
java.lang.Object
com.codename1.ui.geom.Rectangle
All Implemented Interfaces:
Shape
public class
extends Object
implements Shape
Represents a Rectangle position (x, y) and Dimension (width, height), this is useful for measuring
coordinates within the application.
Constructor Summary
Constructor and Description
Rectangle()
Creates a new instance of Rectangle at position (x, y) and with predefine dimension
Rectangle(int x, int y, int w, int h)
Creates a new instance of Rectangle at position (x, y) and with predefine width and height
Rectangle(Rectangle rect)
A copy Constructor
Method Summary
Modifier and
Type
boolean
Checks whether or not this Rectangle contains the point at the specified
location (rX, rY).
contains(int rX, int rY, int rWidth, int rHeight)
boolean
contains(int x1, int y1, int w1, int h1, int x2, int y2, int w2,
static boolean int h2)
Rectangle
float[]
int
PathIterator
PathIterator
Class Rectangle
1289
getSize()
int
int
int
Rectangle
static void
Returns a rectangle that intersects the given rectangle with this rectangle
intersection(int rrX, int rrY, int rrW, int rrH, int rtx1,
int rty1, int rtw2, int rth2, Rectangle dest)
Returns a rectangle that intersects the given rectangle with this rectangle
Rectangle
void
intersection(Rectangle r)
Returns a rectangle that intersects the given rectangle with this rectangle
intersection(Rectangle input, Rectangle output)
intersects(int x, int y, int width, int height)
boolean
intersects(int tx, int ty, int tw, int th, int x, int y,
static boolean int width, int height)
boolean
void
void
void
void
void
String
toString()
Constructor Detail
Rectangle
public Rectangle()
Creates a new instance of Rectangle at position (x, y) and with predefine dimension
Parameters:
Method Summary
1290
Rectangle
public Rectangle(int
int
int
int
x,
y,
w,
h)
Creates a new instance of Rectangle at position (x, y) and with predefine width and
height
Parameters:
x - the x coordinate of the rectangle
y - the y coordinate of the rectangle
w - the width of the rectangle
h - the height of the rectangle
Rectangle
public Rectangle(Rectangle rect)
A copy Constructor
Parameters:
rect - the Rectangle to copy
Method Detail
setBounds
public void setBounds(int
int
int
int
x,
y,
w,
h)
Constructor Detail
1291
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
setX
public void setX(int x)
Checks whether or not this Rectangle entirely contains the specified Rectangle.
Parameters:
rect - the specified Rectangle
Returns:
true if the Rectangle is contained entirely inside this Rectangle; false
otherwise
contains
public boolean contains(int
int
int
int
Method Detail
rX,
rY,
rWidth,
rHeight)
1292
x1,
y1,
w1,
h1,
x2,
y2,
w2,
h2)
Checks whether or not this Rectangle contains the point at the specified location (rX,
rY).
Specified by:
contains in interface Shape
Parameters:
rX - the specified x coordinate
rY - the specified y coordinate
Returns:
true if the point (rX, rY) is inside this Rectangle; false otherwise.
intersection
public Rectangle intersection(int
int
int
int
rX,
rY,
rW,
rH)
Returns a rectangle that intersects the given rectangle with this rectangle
Parameters:
rX - rectangle to intersect with this rectangle
rY - rectangle to intersect with this rectangle
rW - rectangle to intersect with this rectangle
rH - rectangle to intersect with this rectangle
Returns:
the intersection
intersection
public void intersection(Rectangle input,
Rectangle output)
Method Detail
1293
Returns a rectangle that intersects the given rectangle with this rectangle
Parameters:
rrX - rectangle to intersect with this rectangle
rrY - rectangle to intersect with this rectangle
rrW - rectangle to intersect with this rectangle
rrH - rectangle to intersect with this rectangle
rtx1 - rectangle to intersect with this rectangle
rty1 - rectangle to intersect with this rectangle
rtw2 - rectangle to intersect with this rectangle
rth2 - rectangle to intersect with this rectangle
dest - result of the intersection are stored here
intersection
public Rectangle intersection(Rectangle r)
Returns a rectangle that intersects the given rectangle with this rectangle
Specified by:
intersection in interface Shape
Parameters:
r - rectangle to intersect with this rectangle
Returns:
the intersection
intersects
public boolean intersects(int
int
int
int
x,
y,
width,
height)
Determines whether or not this Rectangle and the specified Rectangle location (x, y)
with the specified dimensions (width, height), intersect. Two rectangles intersect if
their intersection is nonempty.
Parameters:
x - the specified x coordinate
y - the specified y coordinate
width - the width of the Rectangle
height - the height of the Rectangle
Returns:
true if the specified Rectangle and this Rectangle intersect; false otherwise.
intersects
public boolean intersects(Rectangle rect)
Determines whether or not this Rectangle and the specified Rectangle location (x, y)
with the specified dimensions (width, height), intersect. Two rectangles intersect if
their intersection is nonempty.
Parameters:
rect - the Rectangle to check intersection with
Returns:
true if the specified Rectangle and this Rectangle intersect; false otherwise.
intersects
public static boolean intersects(int
int
int
int
int
Method Detail
tx,
ty,
tw,
th,
x,
1294
Helper method allowing us to determine if two coordinate sets intersect. This saves
us the need of creating a rectangle object for a quick calculation
Parameters:
tx - x of first rectangle
ty - y of first rectangle
tw - width of first rectangle
th - height of first rectangle
x - x of second rectangle
y - y of second rectangle
width - width of second rectangle
height - height of second rectangle
Returns:
true if the rectangles intersect
getPathIterator
public PathIterator getPathIterator(Transform m)
{Gets an iterator where all points are transformed by the provided transform.
Note: If Transform.isSupported() is false, then using this iterator will throw a
Runtime Exception.
}
Specified by:
getPathIterator in interface Shape
Returns:
A PathIterator where points are transformed by the provided transform.
getPathIterator
public PathIterator getPathIterator()
{Returns the bounding rectangle for the shape. This should be the smallest rectangle
such that the all path segments in the shape are contained within it.}
Specified by:
getBounds in interface Shape
Returns:
A Rectangle that comprises the bounds of the shape.
getBounds2D
public float[] getBounds2D()
Method Detail
1295
Method Detail
1296
Class Point2D
java.lang.Object
com.codename1.ui.geom.Point2D
public class
extends Object
Constructor Summary
Constructor and Description
Point2D(double x, double y)
Method Summary
Modifier and Type
double
double
void
void
String
Constructor Detail
Point2D
public Point2D(double x,
double y)
Method Detail
Class Point2D
1297
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
Method Detail
1298
Class Point
java.lang.Object
com.codename1.ui.geom.Point
public class
extends Object
Constructor Summary
Constructor and Description
Point(int x, int y)
Method Summary
Modifier and Type
int
int
void
void
String
Constructor Detail
Point
public Point(int x,
int y)
Method Detail
Class Point
1299
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
Method Detail
1300
Interface PathIterator
public interface
This interface provides a directed path over the boundary of a shape. The path can contain 1st
through 3rd order Bezier curves (lines, and quadratic and cubic splines). A shape can have multiple
disjoint paths via the SEG_MOVETO directive, and can close a circular path back to the previous
SEG_MOVETO via the SEG_CLOSE directive.
See Also:
GeneralPath, Shape, Graphics.drawShape(com.codename1.ui.geom.Shape,
com.codename1.ui.Stroke), Graphics.fillShape(com.codename1.ui.geom.Shape)
Field Summary
Modifier
and Type
static int
static int
static int
static int
static int
static int
The even-odd winding mode: a point is internal to the shape if a ray from the
point to infinity (in any direction) crosses an odd number of segments.
WIND_NON_ZERO
static int
The non-zero winding mode: a point is internal to the shape if a ray from the
point to infinity (in any direction) crosses a different number of segments
headed clockwise than those headed counterclockwise.
Method Summary
Modifier and
Type
int
Returns the coordinates of the next point(s), as well as the type of line
segment.
currentSegment(float[] coords)
int
int
boolean
void
Interface PathIterator
Returns the coordinates of the next point(s), as well as the type of line
segment.
getWindingRule()
Returns the winding rule to determine which points are inside this path.
isDone()
1301
Field Detail
WIND_EVEN_ODD
static final int WIND_EVEN_ODD
The even-odd winding mode: a point is internal to the shape if a ray from the point to
infinity (in any direction) crosses an odd number of segments.
See Also:
Constant Field Values
WIND_NON_ZERO
static final int WIND_NON_ZERO
The non-zero winding mode: a point is internal to the shape if a ray from the point to
infinity (in any direction) crosses a different number of segments headed clockwise
than those headed counterclockwise.
See Also:
Constant Field Values
SEG_MOVETO
static final int SEG_MOVETO
See Also:
Constant Field Values
SEG_CUBICTO
static final int SEG_CUBICTO
The current segment is a cubic parametric curve (more commonly known as a Bezier
curve). It is interpolated as t varies from 0 to 1 over the current point (CP), first control
point (P1), the second control point (P2), and final interpolated control point (P3):
P(t) = B(3,0)*CP + B(3,1)*P1 + B(3,2)*P2 + B(3,3)*P3
0 <= t <= 1
B(n,m) = mth coefficient of nth degree Bernstein polynomial
= C(n,m) * t^(m) * (1 - t)^(n-m)
C(n,m) = Combinations of n things, taken m at a time
= n! / (m! * (n-m)!)
See Also:
Constant Field Values
Field Detail
1302
SEG_CLOSE
static final int SEG_CLOSE
The current segment closes a loop by an implicit line to the previous SEG_MOVETO
coordinate.
See Also:
Constant Field Values
Method Detail
getWindingRule
int getWindingRule()
Returns the winding rule to determine which points are inside this path.
Returns:
the winding rule. (WIND_EVEN_ODD or WIND_NON_ZERO).
isDone
boolean isDone()
Tests if the iterator is exhausted. If this returns true, currentSegment and next may
throw a RuntimeException (although this is not required).
Returns:
true if the iteration is complete
next
void next()
Advance to the next segment in the iteration. It is not specified what this does if called
when isDone() returns true.
currentSegment
int currentSegment(float[] coords)
Returns the coordinates of the next point(s), as well as the type of line segment. The
input array must be at least a float[6], to accommodate up to three (x,y) point pairs
(although if you know the iterator is flat, you can probably get by with a float[2]). If
the returned type is SEG_MOVETO or SEG_LINETO, the first point in the array is modified;
if the returned type is SEG_QUADTO, the first two points are modified; if the returned
type is SEG_CUBICTO, all three points are modified; and if the returned type is
SEG_CLOSE, the array is untouched.
Parameters:
coords - the array to place the point coordinates in
Returns:
the segment type. One of (SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO,
SEG_CLOSE).
currentSegment
int currentSegment(double[] coords)
Returns the coordinates of the next point(s), as well as the type of line segment. The
input array must be at least a double[6], to accommodate up to three (x,y) point
pairs (although if you know the iterator is flat, you can probably get by with a
double[2]). If the returned type is SEG_MOVETO or SEG_LINETO, the first point in the
array is modified; if the returned type is SEG_QUADTO, the first two points are modified;
if the returned type is SEG_CUBICTO, all three points are modified; and if the returned
type is SEG_CLOSE, the array is untouched.
Parameters:
coords - the array to place the point coordinates in
Returns:
the segment type. One of (SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO,
SEG_CLOSE).
Field Detail
1303
Class GeneralPath
java.lang.Object
com.codename1.ui.geom.GeneralPath
All Implemented Interfaces:
Shape
A general geometric path, consisting of any number of subpaths constructed out of straight lines and
cubic or quadratic Bezier curves. The inside of the curve is defined for drawing purposes by a winding
rule. Either the WIND_EVEN_ODD or WIND_NON_ZERO winding rule can be chosen.
A drawing of a GeneralPath
The WIND_EVEN_ODD winding rule defines a point as inside a path if: A ray from the point towards
infinity in an arbitrary direction intersects the path an odd number of times. Points A and C in the
image are considered to be outside the path. (both intersect twice) Point B intersects once, and is
inside.
The WIND_NON_ZERO winding rule defines a point as inside a path if: The path intersects the ray in an
equal number of opposite directions. Point A in the image is outside (one intersection in the 'up'
direction, one in the 'down' direction) Point B in the image is inside (one intersection 'down') Point C in
the image is inside (two intersections in the 'down' direction)
See Also:
Graphics.drawShape(com.codename1.ui.geom.Shape, com.codename1.ui.Stroke),
Graphics.fillShape(com.codename1.ui.geom.Shape)
Field Summary
Modifier and Type
static int
static int
Constructor Summary
Constructor and Description
GeneralPath()
Method Detail
1304
Constructs a GeneralPath with a specific winding rule and the default initial capacity (10).
GeneralPath(int rule, int initialCapacity)
Constructs a GeneralPath with a specific winding rule and the initial capacity.
GeneralPath(Shape shape)
Method Summary
Modifier and
Type
void
void
void
void
boolean
boolean
Closes the current subpath by drawing a line back to the point of the last
moveTo, unless the path is already closed.
contains(float x, float y)
Shape
void
void
getBounds()
Constructor Summary
1305
void
int
void
int
int
void
Resets this path to be the intersection of itself with the given shape.
intersection(Rectangle rect)
{Returns the shape formed by the intersection of this shape and the
provided rectangle.}
Shape
boolean
void
isRectangle()
void
void
moveTo(double x, double y)
moveTo(float x, float y)
void
void
void
void
Sets the path's winding rule, which controls which areas are considered
'inside' or 'outside' the path on drawing.
void
toString()
String
Field Detail
WIND_EVEN_ODD
public static final int WIND_EVEN_ODD
Method Summary
1306
Detail
GeneralPath
public GeneralPath()
Constructs a GeneralPath with the default (WIND_NON_ZERO) winding rule and initial
capacity (10).
GeneralPath
public GeneralPath(int rule)
Constructs a GeneralPath with a specific winding rule and the default initial capacity
(10).
Parameters:
rule - The winding rule. One of WIND_NON_ZERO and WIND_EVEN_ODD
See Also:
WIND_NON_ZERO, WIND_EVEN_ODD
GeneralPath
public GeneralPath(int rule,
int initialCapacity)
Constructs a GeneralPath with a specific winding rule and the initial capacity. The
initial capacity should be the approximate number of path segments to be used.
Parameters:
rule - The winding rule. (WIND_NON_ZERO or WIND_EVEN_ODD).
initialCapacity - the inital capacity, in path segments
GeneralPath
public GeneralPath(Shape shape)
Method Detail
getTypesSize
public int getTypesSize()
Constructor Detail
1307
Sets the path's winding rule, which controls which areas are considered 'inside' or
'outside' the path on drawing. Valid rules are WIND_EVEN_ODD for an even-odd winding
rule, or WIND_NON_ZERO for a non-zero winding rule.
Parameters:
rule - the rule. (WIND_NON_ZERO or WIND_EVEN_ODD).
getWindingRule
public int getWindingRule()
moveTo
public void moveTo(float x,
float y)
lineTo
public void lineTo(float x,
float y)
Method Detail
1308
x1,
y1,
x2,
y2)
quadTo
public void quadTo(float
float
float
float
x1,
y1,
x2,
y2)
x1,
y1,
x2,
y2,
x3,
y3)
curveTo
public void curveTo(float
float
float
float
float
float
x1,
y1,
x2,
y2,
x3,
y3)
x,
y,
w,
h,
startAngle,
sweepAngle)
Method Detail
1309
x,
y,
w,
h,
startAngle,
sweepAngle)
cX,
cY,
endX,
endY)
Adds an arc to the path. This method uses an approximation of an arc using a cubic
path. It is not a precise arc.
Parameters:
cX - The x-coordinate of the oval center.
cY - The y-coordinate of the oval center.
endX - The end X coordinate.
endY - The end Y coordinate.
arcTo
public void arcTo(double
double
double
double
Method Detail
cX,
cY,
endX,
endY)
1310
Closes the current subpath by drawing a line back to the point of the last moveTo,
unless the path is already closed.
append
public void append(Shape shape,
boolean connect)
Appends the segments of a Shape to the path. If connect is true, the new path
segments are connected to the existing one with a line. The winding rule of the
Shape is ignored.
Parameters:
shape - the shape (null not permitted).
connect - whether to connect the new shape to the existing path.
append
public void append(PathIterator path,
boolean connect)
Method Detail
1311
{Gets an iterator where all points are transformed by the provided transform.
Note: If Transform.isSupported() is false, then using this iterator will throw a
Runtime Exception.
}
Specified by:
getPathIterator in interface Shape
Returns:
A PathIterator where points are transformed by the provided transform.
createTransformedShape
public Shape createTransformedShape(Transform m)
Returns a shape formed by transforming the current shape with the provided
transform.
Note: If Transform.isSupported() is false, this may throw a RuntimeException.
Parameters:
m - The transform to be used to transform the shape.
Returns:
The transformed shape.
intersect
public void intersect(Shape shape)
Resets this path to be the intersection of itself with the given shape. Note that only
Rectangles are current supported. If you pass any other shape, it will throw a
RuntimeException.
Note: If com.codename1.ui.TransformisSupported is false, this will throw a Runtime
Exception
Parameters:
shape
Method Detail
1312
{Returns the shape formed by the intersection of this shape and the provided
rectangle.}
Specified by:
intersection in interface Shape
Parameters:
rect - A rectangle with which to form an intersection.
Returns:
The shape formed by intersecting the current shape with the provided
rectangle.
contains
public boolean contains(float x,
float y)
Method Detail
1313
Class Dimension2D
java.lang.Object
com.codename1.ui.geom.Dimension2D
public class
extends Object
Utility class that holds a width and height that represents a dimension of a component or element
Constructor Summary
Constructor and Description
Dimension2D()
Method Summary
Modifier and Type
double
double
void
void
String
toString()
Constructor Detail
Dimension2D
public Dimension2D()
Class Dimension2D
1314
Method Detail
setWidth
public void setWidth(double width)
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
Constructor Detail
1315
Class Dimension
java.lang.Object
com.codename1.ui.geom.Dimension
public class
extends Object
Utility class that holds a width and height that represents a dimension of a component or element
Constructor Summary
Constructor and Description
Dimension()
Method Summary
Modifier and Type
boolean
int
int
int
void
void
String
Constructor Detail
Dimension
public Dimension()
Method Detail
1316
Method Detail
setWidth
public void setWidth(int width)
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
hashCode
public int hashCode()
Constructor Detail
1317
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Object
Method Detail
1318
Interface StyleListener
All Known Implementing Classes:
Ads, AutoCompleteTextField, BaseSpinner, BrowserComponent, Button, Calendar,
ChartComponent, CheckBox, ComboBox, Component, ComponentGroup, Container,
ContainerList, DateSpinner, DateTimeSpinner, DefaultListCellRenderer, Dialog,
EmbeddedContainer, FileTree, FloatingHint, Form, GenericSpinner, HTMLComponent,
ImageViewer, InfiniteContainer, InfiniteProgress, InteractionDialog, Label, LikeButton, List,
MapComponent, MediaPlayer, MenuBar, MultiButton, MultiList, NumericSpinner,
OnOffSwitch, PeerComponent, Picker, Progress, RadioButton, RSSReader,
ScaleImageButton, ScaleImageLabel, ShareButton, SideMenuBar, Slider, SliderBridge,
SpanButton, SpanLabel, SwipeableContainer, Table, Tabs, TextArea, TextField,
TimeSpinner, Toolbar, Tree, VirtualKeyboard, WebBrowser
public interface
Method Summary
Modifier and Type
void
Method Detail
styleChanged
void styleChanged(String propertyName,
Style source)
Interface StyleListener
1319
Interface SelectionListener
public interface
Method Summary
Modifier and Type
void
Method Detail
selectionChanged
void selectionChanged(int oldSelected,
int newSelected)
Method Detail
1320
Interface ScrollListener
public interface
Method Summary
Modifier and
Type
void
Method Detail
scrollChanged
void scrollChanged(int
int
int
int
scrollX,
scrollY,
oldscrollX,
oldscrollY)
Method Detail
1321
Interface FocusListener
All Known Implementing Classes:
DefaultLookAndFeel
public interface
Observes focus change events for a given form and invokes the callbacks to enable us to assign
functionality based on current focused component.
Method Summary
Modifier and Type
void
void
Method Detail
focusGained
void focusGained(Component cmp)
Method Detail
1322
Interface DataChangedListener
All Known Implementing Classes:
FilterProxyListModel
public interface
Event callback interface invoked when a ListModel changes its state thus indicating to the view that it
should refresh.
Field Summary
Modifier and Type
static int
static int
static int
Method Summary
Modifier and Type
void
Field Detail
REMOVED
static final int REMOVED
Method Detail
Method Detail
1323
Method Detail
1324
Interface BrowserNavigationCallback
public interface
Important: Calls to this interface are always performed on a separate thread from the EDT!
They are performed on the native webkit rendering thread or native event dispatch thread, this
interface MUST NEVER block or synchronize against the EDT which WILL lead to deadlocks.
This interface can be used to bind functionality to URL navigation which is a very portable way to
invoke Java functionality from the JavaScript side of things.
This interface should be applied to the BrowserComponent or WebBrowser class.
Method Summary
Modifier
and Type
boolean
Method Detail
shouldNavigate
boolean shouldNavigate(String url)
Interface BrowserNavigationCallback
1325
Interface ActionListener
All Known Implementing Classes:
Command, EmailShare, FacebookShare, HTMLComponent, LikeButton, MenuBar,
NavigationCommand, Progress, ShareButton, ShareService, SideMenuBar, SMSShare
public interface
Method Summary
Modifier and Type
void
Method Detail
actionPerformed
void actionPerformed(ActionEvent evt)
Method Detail
1326
Class ActionEvent
java.lang.Object
com.codename1.ui.events.ActionEvent
Direct Known Subclasses:
NetworkEvent
public class
extends Object
Constructor Summary
Constructor and Description
ActionEvent(Command source, ActionEvent.Type type, Component sourceComponent,
int x, int y)
Method Summary
Modifier and
Type
Method Detail
1327
Consume the event indicating that it was handled thus preventing other
action listeners from handling/receiving the event
void
Component
getActualComponent()
Identical to getComponent()
Command
Component
Component
Set in the case of a drop listener, returns the component being dragged
getDropTarget()
Component
Set in the case of a drop listener, returns the component on which the
drop occurs
getEventType()
ActionEvent.Type
Returns the type of the given event allowing us to have more generic
event handling code and useful for debugging
getKeyEvent()
If this event was triggered by a key press this method will return the
appropriate keycode
int
getSource()
The element that triggered the action event, useful for decoupling event
handling code
Object
getX()
int
int
boolean
boolean
Returns true if the event was consumed thus indicating that it was
handled.
isLongEvent()
Constructor Detail
ActionEvent
public ActionEvent(Object source)
Method Summary
1328
Creates a new instance of ActionEvent. The key event is really just a numeric code,
not indicative of a key press
Parameters:
source - element for the action event
type - the ActionEvent.Type of the event
keyEvent - the key that triggered the event
ActionEvent
public ActionEvent(Object source,
int keyEvent)
Constructor Detail
1329
Method Detail
getEventType
public ActionEvent.Type getEventType()
Returns the type of the given event allowing us to have more generic event handling
code and useful for debugging
Returns:
the Type enum
Constructor Detail
1330
The element that triggered the action event, useful for decoupling event handling
code
Returns:
the element that triggered the action event
getKeyEvent
public int getKeyEvent()
If this event was triggered by a key press this method will return the appropriate
keycode
Returns:
the key that triggered the event
getCommand
public Command getCommand()
If this event was sent as a result of a command action this method returns that
command
Returns:
the command action that triggered the action event
getActualComponent
public Component getActualComponent()
Identical to getComponent() except for the fact that a lead component will be returned
if such a lead component is available. This is important for components such as
MultiButton which will return the underlying button instead.
Returns:
the component that sent the event
getComponent
public Component getComponent()
Returns the component that generated the event. important this might not be the
actual component. In case of a lead component such as MultiButton the underlying
Button will be returned and not the MultiButton itself. To get the component that you
would logically think of as the source component use the getActualComponent
method.
If you are in doubt use the getActualComponent method.
Returns:
a component
See Also:
- you should probably use {@code getActualComponent} instead of this
method
consume
public void consume()
Consume the event indicating that it was handled thus preventing other action
listeners from handling/receiving the event
isConsumed
public boolean isConsumed()
Returns true if the event was consumed thus indicating that it was handled. This
prevents other action listeners from handling/receiving the event
Returns:
true if the event was consumed
Method Detail
1331
Set in the case of a drop listener, returns the component being dragged
Returns:
the component being dragged
getDropTarget
public Component getDropTarget()
Set in the case of a drop listener, returns the component on which the drop occurs
Returns:
the component on which the drop occurs
Method Detail
1332
Enum ActionEvent.Type
java.lang.Object
java.lang.Enum<ActionEvent.Type>
com.codename1.ui.events.ActionEvent.Type
All Implemented Interfaces:
Comparable<ActionEvent.Type>
Enclosing class:
ActionEvent
Method Summary
Modifier and Type
static ActionEvent.Type
Enum ActionEvent.Type
Returns the enum constant of this type with the specified name.
1333
values()
Command
public static final ActionEvent.Type Command
Pointer
public static final ActionEvent.Type Pointer
PointerPressed
public static final ActionEvent.Type PointerPressed
PointerReleased
public static final ActionEvent.Type PointerReleased
PointerDrag
public static final ActionEvent.Type PointerDrag
Swipe
public static final ActionEvent.Type Swipe
KeyPress
public static final ActionEvent.Type KeyPress
KeyRelease
public static final ActionEvent.Type KeyRelease
Exception
public static final ActionEvent.Type Exception
Response
public static final ActionEvent.Type Response
Progress
public static final ActionEvent.Type Progress
Data
public static final ActionEvent.Type Data
Calendar
public static final ActionEvent.Type Calendar
Edit
public static final ActionEvent.Type Edit
Done
public static final ActionEvent.Type Done
Method Summary
1334
JavaScript
public static final ActionEvent.Type JavaScript
Log
public static final ActionEvent.Type Log
Theme
public static final ActionEvent.Type Theme
Show
public static final ActionEvent.Type Show
SizeChange
public static final ActionEvent.Type SizeChange
OrientationChange
public static final ActionEvent.Type OrientationChange
Method Detail
values
public static ActionEvent.Type[] values()
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
for (ActionEvent.Type c : ActionEvent.Type.values())
System.out.println(c);
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static ActionEvent.Type valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
1335
Class Transition
java.lang.Object
com.codename1.ui.animations.Transition
All Implemented Interfaces:
Animation
Direct Known Subclasses:
CommonTransitions, FlipTransition, MorphTransition
Represents a transition animation between two forms this class is used internally by Display to play
an animation when moving from one form to the next. A transition can be installed on a Form object
using the in/out transitions, for ease of use LookAndFeel has support for default transitions.
Constructor Summary
Constructor and Description
Transition()
Method Summary
Modifier and
Type
abstract
boolean
protected
void
Allows setting the source form to null to save memory if the transition
doesn't need it in memory.
cleanup()
void
Transition
copy(boolean reverse)
Component
Component
Returns the source form which is the form from which the animation is
starting.
init(Component source, Component destination)
Invoked by Display to set the source and destination
void
forms.
initTransition()
Callback thats invoked before a transition begins, the source form may be
null for the first form in the application.
void
paint(Graphics g)
abstract void
Draws the animation, within a component the standard paint method would
be invoked since it bares the exact same signature.
Method Detail
1336
Detail
Transition
public Transition()
Method Detail
init
public final void init(Component source,
Component destination)
Invoked by Display to set the source and destination forms. This method should not
be invoked by developers.
Parameters:
source - the source form from which the transition originates
destination - the destination form to which the transition will lead
initTransition
public void initTransition()
Callback thats invoked before a transition begins, the source form may be null for the
first form in the application.
getDestination
public final Component getDestination()
Returns the destination form that should be set once animation is completed
Returns:
the destination component
getSource
public final Component getSource()
Returns the source form which is the form from which the animation is starting. This
may be null for the first form in the application
Returns:
the source component
cleanup
public void cleanup()
Allows setting the source form to null to save memory if the transition doesn't need it
in memory.
animate
public abstract boolean animate()
Constructor Detail
1337
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Returns:
true if a repaint is desired or false if no repaint is necessary
paint
public abstract void paint(Graphics g)
Draws the animation, within a component the standard paint method would be
invoked since it bares the exact same signature.
Specified by:
paint in interface Animation
Parameters:
g - graphics context
Method Detail
1338
Class Timeline
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.animations.Timeline
All Implemented Interfaces:
Animation, Painter
Method Summary
Modifier and
Type
void
boolean
animate()
static Timeline
AnimationObject
AnimationObject
int
Returns the animation object at the given X/Y coordinate in the timeline
for the current frame.
getAnimationCount()
int
int
int
int[]
Inidicates the minimal delay between animation frames allowing the CPU
to rest.
getDuration()
int[]
Dimension
int
int
boolean
Class Timeline
1339
isLoop()
void
paint(Graphics g)
void
void
boolean
New label optimizations don't invoke drawImage and instead just pass
the native image directly to the underlying renderer.
scaled(int width, int height)
Returns a scaled version of this image image using the given width and
height, this is a fast algorithm that preserves translucent information.
Image
setAnimationDelay(int animationDelay)
Inidicates the minimal delay between animation frames allowing the CPU
to rest.
void
setLoop(boolean loop)
void
void
void
void
Method Detail
lock
public void lock()
This callback indicates that a component pointing at this image is initialized, this
allows an image to make performance sensitive considerations e.g. an encoded
image might choose to cache itself in RAM. This method may be invoked multiple
times.
Overrides:
lock in class Image
Method Summary
1340
This callback indicates that a component pointing at this image is now deinitilized
This method may be invoked multiple times.
Overrides:
unlock in class Image
getRGB
public int[] getRGB()
Returns the content of this image as a newly created ARGB array or a cached
instance if possible. Note that cached instances may be garbage collected.
Overrides:
getRGBCached in class Image
Returns:
array instance containing the ARGB data within this image
createTimeline
public static Timeline createTimeline(int duration,
AnimationObject[] animations,
Dimension size)
Method Detail
1341
Specified by:
animate
in interface Animation
Overrides:
animate in class Image
Returns:
true if a repaint is desired or false if no repaint is necessary
paint
public void paint(Graphics g)
Draws the animation, within a component the standard paint method would be
invoked since it bares the exact same signature.
Specified by:
paint in interface Animation
Parameters:
g - graphics context
paint
public void paint(Graphics g,
Rectangle rect)
Inidicates the minimal delay between animation frames allowing the CPU to rest.
Increase this number to increase general device performance, decrease it to speed
the animation.
Returns:
the animationDelay
setAnimationDelay
public void setAnimationDelay(int animationDelay)
Inidicates the minimal delay between animation frames allowing the CPU to rest.
Increase this number to increase general device performance, decrease it to speed
the animation.
Parameters:
animationDelay - the animationDelay to set
drawImage
protected void drawImage(Graphics g,
Object nativeGraphics,
int x,
int y)
Callback invoked internally by Codename One to draw the image/frame onto the
display. Image subclasses can override this method to perform drawing of custom
image types.
Overrides:
drawImage in class Image
Parameters:
g - the graphics object
Method Detail
1342
Returns a scaled version of this image image using the given width and height, this is
a fast algorithm that preserves translucent information. The method accepts -1 to
preserve aspect ratio in the given axis.
Overrides:
scaled in class Image
Parameters:
width - width for the scaling
height - height of the scaled image
Returns:
new image instance scaled to the given height and width
isPause
public boolean isPause()
Method Detail
1343
Returns the animation object at the given X/Y coordinate in the timeline for the
current frame. This allows functionality such as responding to pointer events on the
resource editor. Notice that this method is not efficient since it tests the pixel opacity
which is a pretty expensive operation...
Parameters:
x - the x location in the timeline
y - the y location in the timeline
Returns:
an animation object or null if no animation object is at that position.
isLoop
public boolean isLoop()
New label optimizations don't invoke drawImage and instead just pass the native
image directly to the underlying renderer. This is problematic for some image types
specifically timeline & FontImage and this method allows these classes to indicate
that they need that legacy behavior of calling drawImage.
Overrides:
requiresDrawImage in class Image
Returns:
true if a drawImage call is a required
Method Detail
1344
Class Motion
java.lang.Object
com.codename1.ui.animations.Motion
public class
extends Object
Abstracts the notion of physical motion over time from a numeric location to another. This class can
be subclassed to implement any motion equation for appropriate physics effects.
This class relies on the System.currentTimeMillis() method to provide transitions between
coordinates. The motion can be subclassed to provide every type of motion feel from parabolic motion
to spline and linear motion. The default implementation provides a simple algorithm giving the feel of
acceleration and deceleration.
Constructor Summary
Modifier
Method Summary
Modifier
and Type
static
Motion
static
Motion
static
Motion
static
Motion
static
Motion
static
Motion
static
Motion
static
Motion
static
Motion
Class Motion
Creates a deceleration motion starting from source value all the way to
destination value
createEaseInMotion(int sourceValue, int destinationValue,
int duration)
Creates a friction motion starting from source with initial speed and the friction
createLinearColorMotion(int sourceValue, int destinationValue,
int duration)
1345
static
Motion
Creates a linear motion starting from source value all the way to destination
value
createSplineMotion(int sourceValue, int destinationValue,
int duration)
static
Motion
Creates a spline motion starting from source value all the way to destination
value
finish()
Sends the motion to the end time instantly which is useful for flushing an
animation
void
getCurrentMotionTime()
long
Returns the current time within the motion relative to start time
getDestinationValue()
int
int
int
The number from which we are starting (usually indicating animation start
position)
protected
long
getStartTime()
int
Returns the value for the motion for the current clock time.
isFinished()
boolean
static
boolean
Returns true if the motion has run its course and has finished meaning the
current time is greater than startTime + duration.
isSlowMotion()
void
setSlowMotion(boolean aSlowMotion)
static void
The number from which we are starting (usually indicating animation start
position)
void
setStartTime(long startTime)
void
void
Constructor Detail
Motion
protected Motion(int sourceValue,
int destinationValue,
int duration)
Method Summary
1346
value
Motion
protected Motion(int sourceValue,
float initVelocity,
float friction)
Method Detail
isSlowMotion
public static boolean isSlowMotion()
Allows debugging motion behavior by slowing motions down 50 fold, doesn't apply to
friction motion
Returns:
the slowMotion
setSlowMotion
public static void setSlowMotion(boolean aSlowMotion)
Allows debugging motion behavior by slowing motions down 50 fold, doesn't apply to
friction motion
Parameters:
aSlowMotion - the slowMotion to set
finish
public void finish()
Sends the motion to the end time instantly which is useful for flushing an animation
createCubicBezierMotion
public static Motion createCubicBezierMotion(int sourceValue,
int destinationValue,
int duration,
float p0,
float p1,
float p2,
float p3)
Constructor Detail
1347
Creates a linear motion starting from source value all the way to destination value
Parameters:
sourceValue - the number from which we are starting (usually indicating
animation start position)
destinationValue - the number to which we are heading (usually indicating
animation destination)
duration - the length in milliseconds of the motion (time it takes to get from
sourceValue to destinationValue)
Returns:
new motion object
Method Detail
1348
Creates a linear motion starting from source value all the way to destination value for
a color value. Unlike a regular linear motion a color linear motion is shifted based on
channels where red, green & blue get shifted separately.
Parameters:
sourceValue - the color from which we are starting
destinationValue - the destination color
duration - the length in milliseconds of the motion (time it takes to get from
sourceValue to destinationValue)
Returns:
new motion object
createSplineMotion
public static Motion createSplineMotion(int sourceValue,
int destinationValue,
int duration)
Creates a spline motion starting from source value all the way to destination value
Parameters:
sourceValue - the number from which we are starting (usually indicating
animation start position)
destinationValue - the number to which we are heading (usually indicating
animation destination)
duration - the length in milliseconds of the motion (time it takes to get from
sourceValue to destinationValue)
Returns:
new motion object
createDecelerationMotion
public static Motion createDecelerationMotion(int sourceValue,
int destinationValue,
int duration)
Creates a deceleration motion starting from source value all the way to destination
value
Parameters:
sourceValue - the number from which we are starting (usually indicating
animation start position)
destinationValue - the number to which we are heading (usually indicating
animation destination)
duration - the length in milliseconds of the motion (time it takes to get from
sourceValue to destinationValue)
Returns:
new motion object
createFrictionMotion
public static Motion createFrictionMotion(int sourceValue,
int maxValue,
float initVelocity,
float friction)
Creates a friction motion starting from source with initial speed and the friction
Parameters:
sourceValue - the number from which we are starting (usually indicating
animation start position)
maxValue - the maximum value for the friction
initVelocity - the starting velocity
friction - the motion friction
Returns:
new motion object
Method Detail
1349
start
public void start()
Returns the current time within the motion relative to start time
Returns:
long value representing System.currentTimeMillis() - startTime
setCurrentMotionTime
public void setCurrentMotionTime(long currentMotionTime)
Returns true if the motion has run its course and has finished meaning the current
time is greater than startTime + duration.
Returns:
true if System.currentTimeMillis() > duration + startTime or the last returned
value is the destination value
getValue
public int getValue()
Returns the value for the motion for the current clock time. The value is dependent on
the Motion type.
Returns:
a value that is relative to the source value
getSourceValue
public int getSourceValue()
The number from which we are starting (usually indicating animation start position)
Returns:
the source value
getDestinationValue
public int getDestinationValue()
Method Detail
1350
The number from which we are starting (usually indicating animation start position)
Parameters:
sourceValue - the source value
getStartTime
protected long getStartTime()
Method Detail
1351
Class MorphTransition
java.lang.Object
com.codename1.ui.animations.Transition
com.codename1.ui.animations.MorphTransition
All Implemented Interfaces:
Animation
public class
extends Transition
A transition inspired by the Android L release morph activity effect allowing a set of components in
one form/container to morph into another in a different container/form.
Method Summary
Modifier and Type
boolean
Transition
static
MorphTransition
Callback thats invoked before a transition begins, the source form may
be null for the first form in the application.
void
Morphs the component with the given source name in the source
container hierarchy to the component with the given name in the
destination hierarchy
paint(Graphics g)
void
Method Detail
copy
public Transition copy(boolean reverse)
Class MorphTransition
1352
Creates a transition with the given duration, this transition should be modified with the
builder methods such as morph
Parameters:
duration - the duration of the transition
Returns:
a new Morph transition instance
morph
public MorphTransition morph(String source,
String to)
Morphs the component with the given source name in the source container hierarchy
to the component with the given name in the destination hierarchy
Parameters:
source to Returns:
this so morph operations can be chained as MorphTransition t =
MorphTransition.create(300).morph("a", "b").("c", "d");
initTransition
public final void initTransition()
Callback thats invoked before a transition begins, the source form may be null for the
first form in the application.
Overrides:
initTransition in class Transition
animate
public boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Specified by:
animate in class Transition
Returns:
true if a repaint is desired or false if no repaint is necessary
paint
public void paint(Graphics g)
Draws the animation, within a component the standard paint method would be
invoked since it bares the exact same signature.
Specified by:
paint in interface Animation
Specified by:
paint in class Transition
Parameters:
g - graphics context
Method Detail
1353
Class FlipTransition
java.lang.Object
com.codename1.ui.animations.Transition
com.codename1.ui.animations.FlipTransition
All Implemented Interfaces:
Animation
public class
extends Transition
Constructor Summary
Constructor and Description
FlipTransition()
Method Summary
Modifier and
Type
boolean
void
The background color that is painted behind the flipping effect or -1 to use
the paintBackgrounds method instead
int
getDuration()
int
Callback thats invoked before a transition begins, the source form may be
null for the first form in the application.
void
paint(Graphics g)
Draws the animation, within a component the standard paint method would
be invoked since it bares the exact same signature.
void
setBgColor(int bgColor)
The background color that is painted behind the flipping effect or -1 to use
the paintBackgrounds method instead
void
setDuration(int duration)
void
Class FlipTransition
1354
Constructor Detail
FlipTransition
public FlipTransition()
Method Detail
initTransition
public void initTransition()
1355
The background color that is painted behind the flipping effect or -1 to use the
paintBackgrounds method instead
Returns:
the bgColor
setBgColor
public void setBgColor(int bgColor)
The background color that is painted behind the flipping effect or -1 to use the
paintBackgrounds method instead
Parameters:
bgColor - the bgColor to set
Method Detail
1356
Class ComponentAnimation
java.lang.Object
com.codename1.ui.animations.ComponentAnimation
Constructor Summary
Constructor and Description
ComponentAnimation()
Method Summary
Modifier and Type
static
ComponentAnimation
void
getMaxSteps()
int
int
getStep()
abstract boolean
isInProgress()
boolean
void
setOnCompletion(Runnable r)
void
setStep(int step)
void
void
protected abstract
void
updateState()
Class ComponentAnimation
1357
Detail
ComponentAnimation
public ComponentAnimation()
Method Detail
isStepModeSupported
public boolean isStepModeSupported()
Step mode allows stepping thru an animation one frame at a time, e.g. when scrolling
down an animation might change title elements then change them back as we scroll
up.
Returns:
true if this animation can be stepped in which case the setStep etc. methods
should work.
setStep
public void setStep(int step)
getMaxSteps
public int getMaxSteps()
Flushes the animation immediately, this will be called if the form is de-initialized
setNotifyLock
public final void setNotifyLock(Object l)
Constructor Detail
1358
setOnCompletion
public final void setOnCompletion(Runnable r)
Method Detail
1359
Class CommonTransitions
java.lang.Object
com.codename1.ui.animations.Transition
com.codename1.ui.animations.CommonTransitions
All Implemented Interfaces:
Animation
Field Summary
Modifier and Type
static int
static int
Method Summary
Modifier and Type
boolean
void
Transition
static
CommonTransitions
static
CommonTransitions
createDialogPulsate()
static
CommonTransitions
createEmpty()
static
CommonTransitions
Creates a transition for fading a form in while fading out the original
form
createFastSlide(int type, boolean forward, int duration)
static
CommonTransitions
Creates a slide transition with the given duration and direction, this
differs from the standard slide animation by focusing on speed rather
than on minimizing heap usage.
static
CommonTransitions
Creates a slide transition with the given duration and direction, this
differs from the standard slide animation by focusing on speed rather
than on minimizing heap usage This method works by creating two
Class CommonTransitions
1360
static
CommonTransitions
static
CommonTransitions
static
CommonTransitions
Creates a slide transition for the body of the form that fades the title in
while sliding
static
CommonTransitions
createTimeline(Image animation)
static
CommonTransitions
Motion
int
void
Callback thats invoked before a transition begins, the source form may
be null for the first form in the application.
isDefaultLinearMotion()
static boolean
boolean
boolean
boolean
boolean
boolean
boolean
void
static void
void
void
void
Method Summary
1361
inherited from
class com.codename1.ui.animations.Transition
cleanSource, getDestination, getSource, init
Field Detail
SLIDE_HORIZONTAL
public static final int SLIDE_HORIZONTAL
SLIDE_VERTICAL
public static final int SLIDE_VERTICAL
Method Detail
isHorizontalSlide
public boolean isHorizontalSlide()
1362
Creates an empty transition that does nothing. This has the same effect as setting a
transition to null.
Returns:
empty transition
createSlideFadeTitle
public static CommonTransitions createSlideFadeTitle(boolean forward,
int duration)
Creates a slide transition for the body of the form that fades the title in while sliding
Parameters:
forward - forward is a boolean value, represent the directions of switching
forms, for example for a horizontally type, true means horizontally movement
to right.
duration - represent the time the transition should take in millisecond
createDialogPulsate
public static CommonTransitions createDialogPulsate()
Creates a slide transition with the given duration and direction, this differs from the
standard slide animation by focusing on speed rather than on minimizing heap usage.
This method works by creating two images and sliding them which works much faster
for all devices however takes up more ram. Notice that this method of painting
doesn't support various basic CodenameOne abilities such as translucent
menus/dialogs etc.
Parameters:
type - type can be either vertically or horizontally, which means the
movement direction of the transition
forward - forward is a boolean value, represent the directions of switching
forms, for example for a horizontally type, true means horizontally movement
to right.
duration - represent the time the transition should take in millisecond
Returns:
a transition object
createSlide
public static CommonTransitions createSlide(int type,
boolean forward,
int duration)
Method Detail
1363
Creates a slide transition with the given duration and direction, this differs from the
standard slide animation by focusing on speed rather than on minimizing heap usage
This method works by creating two images and sliding them which works much faster
for all devices however takes up more ram. Notice that this method of painting
doesn't support various basic CodenameOne abilities such as translucent
menus/dialogs etc.
Parameters:
Method Detail
1364
Creates a transition for fading a form in while fading out the original form
Parameters:
duration - represent the time the transition should take in millisecond
Returns:
a transition object
createTimeline
public static CommonTransitions createTimeline(Image animation)
Creates a transition using an animated image object (e.g. timeline object) as an alpha
mask between the source/target
Parameters:
animation - the image object to execute
Returns:
a transition object
initTransition
public void initTransition()
Callback thats invoked before a transition begins, the source form may be null for the
first form in the application.
Overrides:
initTransition in class Transition
createMotion
protected Motion createMotion(int startOffset,
int dest,
int speed)
This method can be overriden by subclasses to create their own motion object on the
fly
Parameters:
startOffset - the start offset for the menu
dest - the destination of the motion
speed - the speed of the motion
Returns:
a motion instance
animate
public boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Specified by:
animate in class Transition
Returns:
true if a repaint is desired or false if no repaint is necessary
Method Detail
1365
Draws the animation, within a component the standard paint method would be
invoked since it bares the exact same signature.
Specified by:
paint in interface Animation
Specified by:
paint in class Transition
Parameters:
g - graphics context
cleanup
public void cleanup()
Indicates whether the motion associated with this transition is linear or spline motion
Returns:
the linearMotion
setLinearMotion
public void setLinearMotion(boolean linearMotion)
Indicates whether the motion associated with this transition is linear or spline motion
Method Detail
1366
Indicates whether the motion associated with these transitions by default is linear or
spline motion
Returns:
the defaultLinearMotion
setDefaultLinearMotion
public static void setDefaultLinearMotion(boolean aDefaultLinearMotion)
Indicates whether the motion associated with these transitions by default is linear or
spline motion
Parameters:
aDefaultLinearMotion - the defaultLinearMotion to set
Method Detail
1367
Class AnimationObject
java.lang.Object
com.codename1.ui.animations.AnimationObject
An animation object is an element within the timeline that has a visibility state for rendering at a given
point in time. E.g. the object can be queried of its position and render itself for any time.
Field Summary
Modifier and
Type
static int
static int
Method Summary
Modifier and Type
AnimationObject
static
AnimationObject
static
AnimationObject
void
void
void
void
void
void
Class AnimationObject
Defines the height of the object starting at the given time/value and
ending at the given position
defineMotionX(int motionType, int startTime, int duration,
int start, int end)
1368
void
Defines the width of the object starting at the given time/value and
ending at the given position
getEndTime()
int
getStartTime()
int
setEndTime(int endTime)
void
setStartTime(int startTime)
void
Field Detail
MOTION_TYPE_SPLINE
public static final int MOTION_TYPE_SPLINE
Used to define the motion type used when manipulating an animation property
See Also:
Constant Field Values
MOTION_TYPE_LINEAR
public static final int MOTION_TYPE_LINEAR
Used to define the motion type used when manipulating an animation property
See Also:
Constant Field Values
Method Detail
copy
public AnimationObject copy()
Creates an animation object instance that can define the animation properties for an
image
Parameters:
img - the image to animate within the timeline
x - position of the animation
y - position of the animation
Method Summary
1369
Defines the frames of the animation if this is a frame changing animation (e.g. a sprite
of a walking person). Notice that this method must not be invoked more than once or
after the image was initilized
Parameters:
frameWidth - the width of the frame within the image object
frameHeight - the height of the frame within the image object
frameDelay - the delay of the frame
createAnimationImage
public static AnimationObject createAnimationImage(String imageName,
Resources res,
int x,
int y)
Creates an animation object instance that can define the animation properties for an
image. This version of the method is useful while a resource file is in the process of
being loaded and not all images are in place. Loading will finish implicitly when the
image is first used.
Parameters:
imageName - the image to animate within the timeline
res - the resources file from which the image should be fetched.
x - position of the animation
y - position of the animation
Returns:
new animation object
defineMotionX
public void defineMotionX(int
int
int
int
int
motionType,
startTime,
duration,
start,
end)
Defines a motion on the x axis starting at the given time/value and ending at the
given position
Parameters:
motionType - the type of the motion (spline/linear)
startTime - the start time for the motion within the timeline timeframe
duration - the duration of the motion
start - the starting position (the value before startTime)
end - the ending position for the property (the value after endTime)
defineMotionY
public void defineMotionY(int
int
int
int
int
motionType,
startTime,
duration,
start,
end)
Defines a motion on the y axis starting at the given time/value and ending at the
given position
Parameters:
motionType - the type of the motion (spline/linear)
startTime - the start time for the motion within the timeline timeframe
duration - the duration of the motion
start - the starting position (the value before startTime)
end - the ending position for the property (the value after endTime)
Method Detail
1370
motionType,
startTime,
duration,
start,
end)
Defines a rotation animation starting at the given time/value and ending at the given
position
Parameters:
motionType - the type of the motion (spline/linear)
startTime - the start time for the motion within the timeline timeframe
duration - the duration of the motion
start - the starting position (the value before startTime)
end - the ending position for the property (the value after endTime)
defineOpacity
public void defineOpacity(int
int
int
int
int
motionType,
startTime,
duration,
start,
end)
Defines opacity (translucency) starting at the given time/value and ending at the
given position. Values should rance from 0 (transparent) to 255 (opaque).
Parameters:
motionType - the type of the motion (spline/linear)
startTime - the start time for the motion within the timeline timeframe
duration - the duration of the motion
start - the starting position (the value before startTime)
end - the ending position for the property (the value after endTime)
defineWidth
public void defineWidth(int
int
int
int
int
motionType,
startTime,
duration,
start,
end)
Defines the width of the object starting at the given time/value and ending at the
given position
Parameters:
motionType - the type of the motion (spline/linear)
startTime - the start time for the motion within the timeline timeframe
duration - the duration of the motion
start - the starting position (the value before startTime)
end - the ending position for the property (the value after endTime)
defineHeight
public void defineHeight(int
int
int
int
int
motionType,
startTime,
duration,
start,
end)
Defines the height of the object starting at the given time/value and ending at the
given position
Parameters:
motionType - the type of the motion (spline/linear)
startTime - the start time for the motion within the timeline timeframe
duration - the duration of the motion
start - the starting position (the value before startTime)
end - the ending position for the property (the value after endTime)
getStartTime
public int getStartTime()
Method Detail
1371
The start time of the animation determines when we start actually drawing the
animation object. -1 means the duration of the entire animation.
Parameters:
startTime - the startTime to set
getEndTime
public int getEndTime()
The end time of the animation determines when we finish actually drawing the
animation object. -1 means the duration of the entire animation.
Returns:
the endTime in timeline time
setEndTime
public void setEndTime(int endTime)
The end time of the animation determines when we finish actually drawing the
animation object. -1 means the duration of the entire animation.
Parameters:
endTime - the endTime to set
Method Detail
1372
Interface Animation
All Known Implementing Classes:
Ads, AutoCompleteTextField, BaseSpinner, BrowserComponent, Button, Calendar,
ChartComponent, CheckBox, ComboBox, CommonTransitions, Component,
ComponentGroup, Container, ContainerList, DateSpinner, DateTimeSpinner,
DefaultListCellRenderer, Dialog, EmbeddedContainer, FileTree, FlipTransition, FloatingHint,
Form, GenericSpinner, HTMLComponent, ImageViewer, InfiniteContainer, InfiniteProgress,
InteractionDialog, Label, LikeButton, List, MapComponent, MediaPlayer, MenuBar,
MorphTransition, MultiButton, MultiList, NumericSpinner, OnOffSwitch, PeerComponent,
Picker, Progress, RadioButton, RSSReader, ScaleImageButton, ScaleImageLabel,
SeriesTransition, ShareButton, SideMenuBar, Slider, SliderBridge, SpanButton, SpanLabel,
SwipeableContainer, Table, Tabs, TextArea, TextField, Timeline, TimeSpinner, Toolbar,
Transition, Tree, VirtualKeyboard, WebBrowser, XYMultiSeriesTransition,
XYSeriesTransition, XYValueSeriesTransition
public interface
Allows any object to react to events and draw an animation at a fixed interval. All animation methods
are executed on the EDT. For simplicities sake all components are animatable, however no animation
will appear unless it is explicitly registered into the parent form. In order to stop animation callbacks
the animation must be explicitly removed from the form (notice that this differs from removing the
component from the form!).
Method Summary
Modifier and
Type
boolean
void
Draws the animation, within a component the standard paint method would
be invoked since it bares the exact same signature.
Method Detail
animate
boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Returns:
true if a repaint is desired or false if no repaint is necessary
paint
void paint(Graphics g)
Draws the animation, within a component the standard paint method would be
invoked since it bares the exact same signature.
Parameters:
g - graphics context
Interface Animation
1373
Class VirtualKeyboard
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.Form
com.codename1.ui.Dialog
com.codename1.ui.VirtualKeyboard
All Implemented Interfaces:
com.codename1.impl.VirtualKeyboardInterface, Animation, StyleListener,
Iterable<Component>
public class
extends Dialog
implements com.codename1.impl.VirtualKeyboardInterface
This class represent the Codename One Light Weight Virtual Keyboard
Field Summary
Modifier and Type
static int
static String[][]
static String[][]
static String[][]
static String[][]
static int
DELETE_CHAR
static int
INSERT_CHAR
static String
NAME
static String
static String
static int
static String
NUMBERS_MODE
static int
SHIFT
static int
SPACE
static String
static int
SYMBOLS_MODE
Method Detail
1374
focusScrolling
Constructor Summary
Constructor and Description
VirtualKeyboard()
Method Summary
Modifier and
Type
protected void
static void
void
void
void
protected void
static void
void
protected String
static String[]
protected
TextField
String[]
static Transition
static Transition
static
VirtualKeyboard
String
Closes the current form and returns to the previous form, releasing the
EDT in the process
getCurrentMode()
1375
The tint color for the virtual keyboard when shown on top of this text
field see the form tint methods for more information
initModes()
protected void
protected void
static boolean
static boolean
boolean
Indicates whether tooltips should be shown when the keys in the VKB
are pressed
isVirtualKeyboardShowing()
protected void
void
If this Component is focused, the pointer dragged event will call this
method
pointerPressed(int x, int y)
void
If this Component is focused, the pointer pressed event will call this
method
pointerReleased(int x, int y)
void
If this Component is focused, the pointer released event will call this
method
setCommitOnDispose(TextField tf, boolean b)
static void
protected void
Indicates whether the VKB should commit changes to the text field
when the VKB is closed not via the OK button.
setCurrentMode(String mode)
static void
Sets the order in which input modes are toggled by default and allows
disabling/hiding an input mode
setDefaultVirtualKeyboardClass(Class vkbClazz)
static void
void
Sets the order in which input modes are toggled and allows
disabling/hiding an input mode
setInputType(int inputType)
void
static void
Indicates whether tooltips should be shown when the keys in the VKB
are pressed
setTextField(TextArea field)
void
static void
static void
Invoked internally by the implementation to indicate the text field that will
be edited by the virtual keyboard
setTransitionIn(Transition aTransitionIn)
static void
Method Summary
Sets the tint color for the virtual keyboard when shown on top of this text
field see the form tint methods for more information
1376
The default version of show modal shows the dialog occupying the
center portion of the screen.
void
showKeyboard(boolean show)
void
1377
Field Detail
DEFAULT_QWERTY
public static final String[][] DEFAULT_QWERTY
1378
See Also:
Constant Field Values
DELETE_CHAR
public static final int DELETE_CHAR
See Also:
Constant Field Values
CHANGE_MODE
public static final int CHANGE_MODE
See Also:
Constant Field Values
SHIFT
public static final int SHIFT
See Also:
Constant Field Values
OK
public static final int OK
See Also:
Field Detail
1379
See Also:
Constant Field Values
T9
public static final int T9
See Also:
Constant Field Values
NAME
public static final String NAME
See Also:
Constant Field Values
Constructor Detail
VirtualKeyboard
public VirtualKeyboard()
Method Detail
setInputType
public void setInputType(int inputType)
Invoked internally by the implementation to indicate the text field that will be edited by
the virtual keyboard
Parameters:
field - the text field instance
show
public void show()
The default version of show modal shows the dialog occupying the center portion of
the screen.
Overrides:
show in class Dialog
autoAdjust
protected void autoAdjust(int w,
int h)
Auto adjust size of the dialog. This method is triggered from a sizeChanged event.
Overrides:
autoAdjust in class Dialog
Parameters:
w - width of the screen
h - height of the screen
Field Detail
1380
Method Detail
1381
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Dialog
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerDragged
public void pointerDragged(int x,
int y)
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Form
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Dialog
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
initSpecialButtons
protected void initSpecialButtons()
Sets the order in which input modes are toggled and allows disabling/hiding an input
mode
Parameters:
order - the order for the input modes in this field
getDefaultInputModeOrder
public static String[] getDefaultInputModeOrder()
Sets the order in which input modes are toggled by default and allows
disabling/hiding an input mode
Parameters:
Method Detail
1382
Invoked to allow subclasses of form to handle a command from one point rather than
implementing many command instances
Overrides:
actionCommand in class Dialog
Parameters:
cmd - the action command
dispose
public void dispose()
Closes the current form and returns to the previous form, releasing the EDT in the
process
Overrides:
dispose in class Dialog
onShow
protected void onShow()
Allows subclasses to bind functionality that occurs when a specific form or dialog
appears on the screen
Overrides:
onShow in class Dialog
getInputField
protected TextField getInputField()
Indicates whether the VKB should commit changes to the text field when the VKB is
closed not via the OK button. This might be useful for some situations such as
searches
Parameters:
tf - the text field to mark as commit on dispose
b - the value of commit on dispose, true to always commit changes
bindVirtualKeyboard
public static void bindVirtualKeyboard(TextArea t,
VirtualKeyboard vkb)
Method Detail
1383
Sets the tint color for the virtual keyboard when shown on top of this text field see the
form tint methods for more information
Parameters:
tf - the relevant text field
tint - the tint color with an alpha channel
getVKBTint
public static int getVKBTint(TextArea tf)
The tint color for the virtual keyboard when shown on top of this text field see the
form tint methods for more information
Parameters:
tf - the relevant text field
Returns:
the tint color with an alpha channel
isShowTooltips
public static boolean isShowTooltips()
Indicates whether tooltips should be shown when the keys in the VKB are pressed
Returns:
the showTooltips
setShowTooltips
public static void setShowTooltips(boolean aShowTooltips)
Indicates whether tooltips should be shown when the keys in the VKB are pressed
Parameters:
aShowTooltips - true to show tooltips
getTransitionIn
public static Transition getTransitionIn()
Method Detail
1384
Shows the virtual keyboard that is assoiciated with the displayed TextField or
displays the default virtual keyboard.
Specified by:
showKeyboard in interface com.codename1.impl.VirtualKeyboardInterface
Parameters:
show - it show is true open the relevant keyboard, if close dispose the
displayed keyboard
setDefaultVirtualKeyboardClass
public static void setDefaultVirtualKeyboardClass(Class vkbClazz)
isVirtualKeyboardShowing
public boolean isVirtualKeyboardShowing()
Method Detail
1385
Class URLImage
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.EncodedImage
com.codename1.ui.URLImage
public class
extends EncodedImage
allows us to create an image from a URL. If the image was downloaded already it is fetched
from cache; if not it is downloaded optionally scaled/adapted and placed in cache.
URLImage
By default an image is fetched lazily as it is asked for by the GUI unless the fetch() method is invoked
in which case the IO code is executed immediately.
This sample code show a URLImage that is fetched to the title area background and scaled/cropped to
fit device specific dimensions.
This sample code shows the usage of the nestoria API to fill out an infinitely scrolling list in it we use
URLImage to fetch the icon.
Class URLImage
Allows applying resize logic to downloaded images you can use constant
resize behaviors defined in this class.
1386
Summary
Will fail if the downloaded image has a different size from the
placeholder image
RESIZE_SCALE
Scales the image to match the size of the new image exactly
RESIZE_SCALE_TO_FILL
Method Summary
Modifier and Type
boolean
static
URLImage.ImageAdapter
static URLImage
static URLImage
static URLImage
void
getImageData()
Returns the byte array data backing the image allowing the
image to be stored and discarded completely from RAM.
byte[]
getInternal()
protected Image
boolean
Field Summary
1387
Field Detail
RESIZE_FAIL
public static final URLImage.ImageAdapter RESIZE_FAIL
Will fail if the downloaded image has a different size from the placeholder image
RESIZE_SCALE
public static final URLImage.ImageAdapter RESIZE_SCALE
Scales the image to match the size of the new image exactly
RESIZE_SCALE_TO_FILL
public static final URLImage.ImageAdapter RESIZE_SCALE_TO_FILL
Scales the image to match to fill the area while preserving aspect ratio
Method Detail
createMaskAdapter
public static URLImage.ImageAdapter createMaskAdapter(Image imageMask)
Creates an adapter that uses an image as a Mask, this is roughly the same as
SCALE_TO_FILL with the exception that a mask will be applied later on. This adapter
requires that the resulting image be in the size of the imageMask!
Parameters:
imageMask - the mask image see the createMask() method of image for
details of what a mask is, it will be used as the reference size for the image
and resulting images must be of the same size!
Returns:
the adapter
fetch
public void fetch()
Images are normally fetched from storage or network only as needed, however if the
download must start before the image is drawn this method can be invoked.
getInternal
protected Image getInternal()
Returns the actual image represented by the encoded image, this image will be
cached in a weak/soft reference internally. This method is useful to detect when the
system actually created an image instance. You shouldn't invoke this method
manually!
Overrides:
getInternal in class EncodedImage
Returns:
drawable image instance
getImageData
public byte[] getImageData()
1388
Overrides:
animate
in class Image
isAnimation
public boolean isAnimation()
Method Detail
1389
Method Detail
1390
Interface URLImage.ImageAdapter
Enclosing class:
URLImage
Allows applying resize logic to downloaded images you can use constant resize behaviors defined in
this class. This class allows masking and various other effects to be applied to downloaded images.
Notice: adapters happen before the image is saved so they will only happen once and the image will
be saved as "adapted" which can be great for performance but is also permanent. E.g. If you mask an
image it will remain masked.
Method Summary
Modifier and
Type
EncodedImage
Allows the downloaded image to be adapted e.g if it isn't the same size of
the placeholder image.
isAsyncAdapter()
boolean
Method Detail
adaptImage
EncodedImage adaptImage(EncodedImage downloadedImage,
EncodedImage placeholderImage)
Allows the downloaded image to be adapted e.g if it isn't the same size of the
placeholder image.
Parameters:
downloadedImage - the downloaded image
placeholderImage - the placeholder image
Returns:
the adapted image or the same image
isAsyncAdapter
boolean isAsyncAdapter()
Return true if the adapter should work on a separate thread to avoid blocking the
EDT this is especially important for image masks and heavy image manipulation
Returns:
true to run off the EDT
Interface URLImage.ImageAdapter
1391
Class Transform
java.lang.Object
com.codename1.ui.Transform
public class
extends Object
Encapsulates a 3D transform that can be used in Graphics contexts or with Shapes to transform in
various ways. Use the isSupported() and isPerspectiveSupported() to check if transforms and
perspective transforms are supported on this platform. If they are not supported, this class will throw
RuntimeExceptions if you try to use it.
Field Summary
Modifier and Type
static int
static int
static int
static int
Method Summary
Modifier and
Type
void
Transform
boolean
Transform
Object
float
float
float
float
float
float
static
Transform
Method Detail
1392
isIdentity()
static
Transform
void
void
void
void
void
void
setIdentity()
Method Summary
1393
transformPoint(float[] point)
void
Transforms a provided point and places the result in the provided array.
void
translate(float x, float y)
translate(float x, float y, float z)
void
Field Detail
TYPE_UNKNOWN
public static final int TYPE_UNKNOWN
Method Detail
IDENTITY
public static Transform IDENTITY()
makeIdentity
public static Transform makeIdentity()
1394
Gets the x scale factor of this transformation. This value is only reliable if the
transform is a scale transform.
Returns:
The x scale factor of this transformation.
See Also:
isScale(), #setScale()
getScaleY
public float getScaleY()
Gets the y scale factor of this transformation. This value is only reliable if the
transform is a scale transform.
Returns:
The y scale factor of this transformation.
See Also:
isScale(), #setScale()
getScaleZ
public float getScaleZ()
Gets the z scale factor of this transformation. This value is only reliable if the
transform is a scale transform.
Returns:
The z scale factor of this transformation.
See Also:
isScale(), #setScale()
getTranslateX
public float getTranslateX()
Gets the x translation of this transformation. This value is only reliable if the transform
is a translation transform.
Returns:
The x translation of this transform.
See Also:
isTranslation(), #setTranslation(), #translate()
getTranslateY
public float getTranslateY()
Gets the y translation of this transformation. This value is only reliable if the transform
is a translation transform.
Returns:
The y translation of this transform.
See Also:
isTranslation(), #setTranslation(), #translate()
getTranslateZ
public float getTranslateZ()
Gets the z translation of this transformation. This value is only reliable if the transform
is a translation transform.
Returns:
The z translation of this transform.
See Also:
Method Detail
1395
isScale
public boolean isScale()
angle,
x,
y,
z)
Returns:
A transform that makes the appropriate rotation.
Throws:
RuntimeException - If isSupported() is false.
makeRotation
public static Transform makeRotation(float angle,
float x,
float y)
makeTranslation
public static Transform makeTranslation(float x,
float y,
float z)
makeScale
public static Transform makeScale(float x,
float y,
float z)
Method Detail
1396
fovy,
aspect,
zNear,
zFar)
Returns:
A transform for the given perspective.
makeOrtho
public static Transform makeOrtho(float
float
float
float
float
float
left,
right,
bottom,
top,
near,
far)
Returns:
A transform with the provided orthographic projection.
makeCamera
public static Transform makeCamera(float
float
float
float
float
float
float
float
float
eyeX,
eyeY,
eyeZ,
centerX,
centerY,
centerZ,
upX,
upY,
upZ)
Returns:
A transform with the provided camera's view perspective.
Method Detail
1397
angle,
x,
y,
z)
See Also:
setRotation(float, float, float, float)
rotate
public void rotate(float angle,
float px,
float py)
setRotation
public void setRotation(float
float
float
float
angle,
x,
y,
z)
Sets the transform to be the provided rotation. This replaces the current transform
whereas #rotate() further rotates the current transform.
Note: If isSupported() is false, then this will throw a Runtime Exception.
Parameters:
angle x - The
y - The
z - The
See Also:
#rotate()
setRotation
public void setRotation(float angle,
float px,
float py)
setIdentity
public void setIdentity()
Method Detail
1398
Translates the transform by the specified amounts. This adds additional translations
to whereas #setTranslation() replaces the transform with the specified translation.
Note: If isSupported() is false, then this may throw a Runtime Exception.
Parameters:
x - The x translation.
y - The y translation.
z - The z translation.
See Also:
#setTranslation()
translate
public void translate(float x,
float y)
setTranslation
public void setTranslation(float x,
float y,
float z)
Sets the current transform to be the specified translation. This replaces the current
transform with the given translation whereas #translate() adds additional translation
to the existing translation.
Parameters:
x - The x translation.
y - The y translation.
z - The z translation.
See Also:
#translate()
setTranslation
public void setTranslation(float x,
float y)
scale
public void scale(float x,
float y,
float z)
Scales the current transform by the provide scale factors. Not to be confused with
#setScale() which replaces the transform.
Note: If isSupported() is false, then this may throw a Runtime Exception.
Parameters:
x - The x-scale factor
y - The y-scale factor
z - The z-scale factor
See Also:
#setScale()
scale
public void scale(float x,
float y)
getInverse
public Transform getInverse()
Method Detail
1399
Sets the current transform to be the concatenation of the current transform and the
provided transform.
Note: If isSupported() is false, then this will throw a Runtime Exception.
Parameters:
t - The transform to concatenate to this one.
setPerspective
public void setPerspective(float
float
float
float
fovy,
aspect,
zNear,
zFar)
See Also:
#makePerspective()
setOrtho
public void setOrtho(float
float
float
float
float
float
left,
right,
bottom,
top,
near,
far)
setCamera
public void setCamera(float
float
float
float
float
float
Method Detail
eyeX,
eyeY,
eyeZ,
centerX,
centerY,
centerZ,
1400
transformPoint
public float[] transformPoint(float[] point)
Transforms a provided point and places the result in the provided array.
Note: If isSupported() is false, then this will throw a Runtime Exception.
Parameters:
in - A 2 or 3 element array representing either an (x,y) or (x,y,z) tuple.
out - A 2 or 3 element array in which the transformed point will be stored.
Should match the length of the in array.
getNativeTransform
public Object getNativeTransform()
Gets the native transform object. This object is implementation dependent so this
method should really only be used by the implementation.
Note: If isSupported() is false, then this will throw a Runtime Exception.
Returns:
The native transform object.
copy
public Transform copy()
Method Detail
1401
Checks if transforms are supported on this platform. If this returns false, you cannot
use this class.
Returns:
True if and only if this platform supports transforms.
isPerspectiveSupported
public static boolean isPerspectiveSupported()
Checks if perspective transforms are supported on this platform. If this returns false,
you cannot use this class.
Returns:
True if and only if this platform supports transforms.
equals
public boolean equals(Transform t2)
Method Detail
1402
Class Toolbar
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.Toolbar
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
Toolbar replaces the default title area with a powerful abstraction that allows functionality ranging from
side menus (hamburger) to title animations and any arbitrary component type. Toolbar allows
customizing the Form title with different commands on the title area, within the side menu or the
overflow menu.
The Toolbar allows placing components in one of 4 positions as illustrated by the sample below:
The following code demonstrates a more advanced search widget where the data is narrowed as we
type directly into the title area search. Notice that the TextField and its hint are styled to look like the
title.
Class Toolbar
1403
This sample code show off title animations that allow a title to change (and potentially shrink) as the
user scrolls down the UI. The 3 frames below show a step by step process in the change.
Class Toolbar
1404
Field Summary
Constructor Summary
Constructor and Description
Toolbar()
Empty Constructor
Toolbar(boolean layered)
This constructor places the Toolbar on a different layer on top of the Content Pane.
Method Summary
Modifier and
Type
void
Command
void
Command
Field Summary
addCommandToRightBar(Command cmd)
1405
Creates the list component containing the commands within the given vector
used for showing the menu dialog
createSideNavigationComponent(Vector commands, String placement)
Adds a status bar space to the north of the Component, subclasses can
override this default behavior.
isGlobalToolbar()
Creates a static side menu that doesn't fold instead of the standard
sidemenu.
isTitleCentered()
static void
void
void
Creates a static side menu that doesn't fold instead of the standard
sidemenu.
setScrollOffUponContentPane(boolean scrollOff)
Sets the Toolbar to scroll off the screen upon content scroll.
setTitle(String title)
void
void
protected
Command
void
Method Summary
Makes the title align to the center accurately by doing it at the layout level
which also takes into account right/left commands
setTitleComponent(Component titleCmp)
1406
1407
Constructor Detail
Toolbar
public Toolbar()
Empty Constructor
Toolbar
public Toolbar(boolean layered)
This constructor places the Toolbar on a different layer on top of the Content Pane.
Parameters:
layered - if true places the Toolbar on top of the Content Pane
Method Detail
setGlobalToolbar
public static void setGlobalToolbar(boolean gt)
Enables/disables the Toolbar for all the forms in the application. This flag can be
flipped via the theme constant globalToobarBool.
Parameters:
gt - true to enable the toolbar globally
isGlobalToolbar
public static boolean isGlobalToolbar()
Enables/disables the Toolbar for all the forms in the application. This flag can be
flipped via the theme constant globalToobarBool.
Returns:
true if the toolbar API is turned on by default
setTitle
public void setTitle(String title)
Makes the title align to the center accurately by doing it at the layout level which also
takes into account right/left commands
Parameters:
cent - whether the title should be centered
isTitleCentered
public boolean isTitleCentered()
1408
Creates a static side menu that doesn't fold instead of the standard sidemenu. This is
common for tablet UI's where folding the side menu doesn't make as much sense.
Parameters:
p - true to have a permanent side menu
isPermanentSideMenu
public static boolean isPermanentSideMenu()
Creates a static side menu that doesn't fold instead of the standard sidemenu. This is
common for tablet UI's where folding the side menu doesn't make as much sense.
Returns:
true if we will use a permanent sidemenu
setTitleComponent
public void setTitleComponent(Component titleCmp)
Sets the Toolbar title component. This method allow placing any component in the
Toolbar ceneter instead of the regular Label. Can be used to place a TextField to
preform search operations
Parameters:
titleCmp - Comoponent to place in the Toolbar center.
getTitleComponent
public Component getTitleComponent()
Method Detail
1409
Adds a Component to the side navigation menu. The Component is added to the
navigation menu and the command gets the events once the Component is being
pressed.
Parameters:
cmp - c Component to be added to the menu
cmd - a Command to handle the events
addComponentToSideMenu
public void addComponentToSideMenu(Component cmp)
Method Detail
1410
createOverflowCommandList
protected List createOverflowCommandList(Vector commands)
Creates the list component containing the commands within the given vector used for
showing the menu dialog
Parameters:
commands - list of command objects
Returns:
List object
initTitleBarStatus
protected void initTitleBarStatus()
Adds a status bar space to the north of the Component, subclasses can override this
default behavior.
setScrollOffUponContentPane
public void setScrollOffUponContentPane(boolean scrollOff)
Sets the Toolbar to scroll off the screen upon content scroll. This feature can only
work if the Form contentPane is scrollableY
Parameters:
scrollOff - if true the Toolbar needs to scroll off the screen when the Form
ContentPane is scrolled
hideToolbar
public void hideToolbar()
Method Detail
1411
Method Detail
1412
Class TextField
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.TextArea
com.codename1.ui.TextField
All Implemented Interfaces:
Animation, StyleListener
Direct Known Subclasses:
AutoCompleteTextField
public class
extends TextArea
A specialized version of TextArea with some minor deviations from the original specifically:
Blinking cursor is rendered on TextField only
com.codename1.ui.events.DataChangeListener is only available in TextField. This is crucial
for character by character input event tracking
setDoneListener(com.codename1.ui.events.ActionListener) is only available in TextField
Different UIID's ("TextField" vs. "TextArea")
The demo code below shows simple input using text fields:
TableLayout tl;
int spanButton = 2;
if(Display.getInstance().isTablet()) {
tl = new TableLayout(7, 2);
} else {
tl = new TableLayout(14, 1);
spanButton = 1;
}
tl.setGrowHorizontally(true);
hi.setLayout(tl);
TextField
TextField
TextField
TextField
TextField
TextField
TextField
TextField
TextField
num1
num2
num3
num4
=
=
=
=
new
new
new
new
TextField("",
TextField("",
TextField("",
TextField("",
"1234",
"1234",
"1234",
"1234",
4,
4,
4,
4,
TextArea.NUMERIC);
TextArea.NUMERIC);
TextArea.NUMERIC);
TextArea.NUMERIC);
Class TextField
1413
The following code demonstrates a more advanced search widget where the data is narrowed as we
type directly into the title area search. Notice that the TextField and its hint are styled to look like the
title.
Toolbar.setGlobalToolbar(true);
Style s = UIManager.getInstance().getComponentStyle("Title");
Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
TextField searchField = new TextField("", "Toolbar Search"); <1>
searchField.getHintLabel().setUIID("Title");
searchField.setUIID("Title");
searchField.getAllStyles().setAlignment(Component.LEFT);
hi.getToolbar().setTitleComponent(searchField);
FontImage searchIcon = FontImage.createMaterial(FontImage.MATERIAL_SEARCH, s);
searchField.addDataChangeListener((i1, i2) -> { <2>
String t = searchField.getText();
if(t.length() < 1) {
for(Component cmp : hi.getContentPane()) {
cmp.setHidden(false);
cmp.setVisible(true);
}
} else {
t = t.toLowerCase();
for(Component cmp : hi.getContentPane()) {
String val = null;
if(cmp instanceof Label) {
val = ((Label)cmp).getText();
} else {
if(cmp instanceof TextArea) {
val = ((TextArea)cmp).getText();
} else {
val = (String)cmp.getPropertyValue("text");
}
}
boolean show = val != null && val.toLowerCase().indexOf(t) > -1;
cmp.setHidden(!show); <3>
cmp.setVisible(show);
}
}
hi.getContentPane().animateLayout(250);
});
hi.getToolbar().addCommandToRightBar("", searchIcon, (e) -> {
searchField.startEditingAsync(); <4>
});
hi.add("A Game of Thrones").
add("A Clash Of Kings").
add("A Storm Of Swords").
add("A Feast For Crows").
add("A Dance With Dragons").
add("The Winds of Winter").
add("A Dream of Spring");
hi.show();
Class TextField
1414
Field Summary
Constructor Summary
Constructor and Description
TextField()
Default constructor
TextField(int columns)
Field Summary
1415
Method Summary
Modifier and
Type
void
Adds a listener for data change events it will be invoked for every change
made to the text field, notice most platforms will invoke only the
DataChangedListener.CHANGED event
addInputMode(String name, Hashtable values, boolean firstUpcase)
static void
boolean
protected
Dimension
void
protected void
static
TextArea
static
TextArea
static
TextArea
static
TextArea
protected
Container
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
animate()
Commit the changes made to the text field as a complete edit operation.
create()
protected void
void
protected void
void
void
Alert the TextField listeners the text has been changed on the TextField
fireDoneEvent()
protected char
Returns the character matching the given key code after the given amount
of user presses
getCommitTimeout()
int
int
int
int
int
Method Summary
1416
getCursorY()
static int
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
getDefaultInputModeOrder()
static
String[]
static int
ActionListener
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
getDefaultSymbolDialogKey()
String
String[]
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
getInputModeOrder()
protected int
The amount of time considered as a "long click" causing the long click
method to be invoked.
protected
String
getLongClickInputMode()
static char[]
void
protected
Command
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
installCommands(Command clear, Command t9)
Installs the clear and t9 commands onto the parent form, this method can
be overriden to provide device specific placement for these commands
isChangeInputMode(int keyCode)
protected
boolean
protected
boolean
protected
boolean
protected
boolean
protected
boolean
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
isClearKey(int keyCode)
Returns true if this is the clear key on the device, many devices don't
contain a clear key and even in those that contain it this might be an issue
isCursorPositionCycle()
Returns true if the cursor should cycle to the beginning of the text when the
user navigates beyond the edge of the text and visa versa.
isEditingEndTrigger(int keyCode)
Indicates whether the given key code should be ignored or should trigger
cause editing to end.
isEditingTrigger(int keyCode)
Indicates whether the given key code should be ignored or should trigger
editing, by default fire or any numeric key should trigger editing implicitly.
isEnableInputScroll()
boolean
Indicates whether text field input should scroll to the right side when no
more room for the input is present.
isImmediateInputMode(String mode)
protected
boolean
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
boolean
isLeftAndRightEditingTrigger()
Method Summary
1417
isOverwriteMode()
static boolean
Indicates whether the text field should try to auto detect qwerty and switch
the qwerty device flag implicitly
isQwertyDevice()
static boolean
boolean
The default value for the qwerty flag so it doesn't need setting for every text
field individually.
isQwertyInput()
boolean
Indicates whether the menu of the form should be replaced with the
T9/Clear commands for the duration of interactivity with the text field
isReplaceMenuDefault()
static boolean
Indicates whether the menu of the form should be replaced with the
T9/Clear commands for the duration of interactivity with the text field
isSelectableInteraction()
protected
boolean
protected
boolean
isSymbolDialogKey(int keyCode)
Returns true if this keycode is the one mapping to the symbol dialog popup
isUseNativeTextInput()
static boolean
boolean
void
void
void
Indicates that native text input should be used in text field when in place
editing is supported by the platform
isUseSoftkeys()
If this Component is focused, the key pressed event will call this method
keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
keyRepeated(int keyCode)
If this Component is focused, the key repeat event will call this method.
longKeyPress(int keyCode)
protected void
If this Component is focused this method is invoked when the user presses
and holds the key
paint(Graphics g)
void
void
If this Component is focused, the pointer released event will call this
method
removeCommands(Command clear, Command t9, Command originalClear)
protected void
void
void
static void
Removes the clear and t9 commands from the parent form, this method
can be overriden to provide device specific placement for these commands
removeDataChangeListener(DataChangedListener d)
Sets the Alignment of the TextArea to one of: CENTER, LEFT, RIGHT
setClearText(String text)
void
Method Summary
1418
setCursorBlinkTimeOff(int time)
static void
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
setDefaultInputModeOrder(String[] order)
static void
static void
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
setDefaultSymbolDialogKey(int d)
void
void
Sets a Done listener on the TextField - notice this listener will be called only
on supported platforms that supports done action on the keyboard
setEditable(boolean b)
void
Indicates whether text field input should scroll to the right side when no
more room for the input is present.
setInputMode(String inputMode)
void
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
setInputModeOrder(String[] order)
void
Deprecated.
this is a method for use only on old J2ME devices and is ignored
everywhere else
setLeftAndRightEditingTrigger(boolean leftAndRightEditingTrigger)
void
void
Indicates whether the left/right keys will trigger editing, this is true by
default.
setOverwriteMode(boolean overwriteMode)
static void
Indicates whether the text field should try to auto detect qwerty and switch
the qwerty device flag implicitly
setQwertyDevice(boolean v)
static void
void
The default value for the qwerty flag so it doesn't need setting for every text
field individually.
setQwertyInput(boolean qwerty)
void
Indicates whether the menu of the form should be replaced with the
T9/Clear commands for the duration of interactivity with the text field
setReplaceMenuDefault(boolean replaceMenu)
static void
static void
static void
void
Indicates whether the menu of the form should be replaced with the
T9/Clear commands for the duration of interactivity with the text field
setSymbolTable(char[] table)
Sets the symbol table to show when the user clicks the symbol table key
setT9Text(String text)
static void
Method Summary
Indicates that native text input should be used in text field when in place
editing is supported by the platform
1419
void
protected void
boolean
1420
Constructor Detail
TextField
public TextField()
Default constructor
TextField
public TextField(int columns)
1421
Method Detail
isUseNativeTextInput
public static boolean isUseNativeTextInput()
Indicates that native text input should be used in text field when in place editing is
supported by the platform
Returns:
the useNativeTextInput
setUseNativeTextInput
public static void setUseNativeTextInput(boolean aUseNativeTextInput)
Indicates that native text input should be used in text field when in place editing is
supported by the platform
Parameters:
aUseNativeTextInput - the useNativeTextInput to set
setClearText
public static void setClearText(String text)
Indicates whether text field input should scroll to the right side when no more room for
the input is present.
Overrides:
isEnableInputScroll in class TextArea
Returns:
true if scrolling is enabled
setEnableInputScroll
public void setEnableInputScroll(boolean enableInputScroll)
Indicates whether text field input should scroll to the right side when no more room for
the input is present.
Parameters:
enableInputScroll - true to enable scrolling to the side
deleteChar
public void deleteChar()
Method Detail
1422
Commit the changes made to the text field as a complete edit operation. This is used
in a numeric keypad to allow the user to repeatedly press a number to change
values.
isPendingCommit
public boolean isPendingCommit()
The amount of time in milliseconds it will take for a change to get committed into the
field.
Parameters:
commitTimeout - indicates the amount of time that should elapse for a commit
to automatically occur
getCommitTimeout
public int getCommitTimeout()
The amount of time in milliseconds it will take for a change to get committed into the
field.
Returns:
the time for a commit timeout
setInputMode
public void setInputMode(String inputMode)
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Sets the current selected input mode matching one of the existing input modes
Parameters:
Method Detail
1423
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Returns the currently selected input mode
Overrides:
getInputMode in class TextArea
Returns:
the display name of the input mode by default the following modes are
supported: Abc, ABC, abc, 123
isChangeInputMode
protected boolean isChangeInputMode(int keyCode)
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Indicates whether the key changes the current input mode
Parameters:
keyCode - the code
Returns:
true for the hash (#) key code
addInputMode
public static void addInputMode(String name,
Hashtable values,
boolean firstUpcase)
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Adds a new inputmode hashtable with the given name and set of values
Parameters:
name - a unique display name for the input mode e.g. ABC, 123 etc...
values - The key for the hashtable is an Integer keyCode and the value is a
String containing the characters to toggle between for the given keycode
firstUpcase - indicates if this input mode in an input mode used for the
special case where the first letter is an upper case letter
getInputModeOrder
public String[] getInputModeOrder()
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Sets the order in which input modes are toggled and allows disabling/hiding an input
mode
Parameters:
order - the order for the input modes in this field
getDefaultInputModeOrder
public static String[] getDefaultInputModeOrder()
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Returns the order in which input modes are toggled by default
Returns:
Method Detail
1424
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Sets the order in which input modes are toggled by default and allows
disabling/hiding an input mode
Parameters:
order - the order for the input modes in all future created fields
getLongClickInputMode
protected String getLongClickInputMode()
Returns the character matching the given key code after the given amount of user
presses
Parameters:
pressCount - number of times this keycode was pressed
keyCode - the actual keycode input by the user
longClick - does this click constitute a long click
Returns:
the char mapping to this key or 0 if no appropriate char was found
(navigation, input mode change etc...).
setCursorPosition
public void setCursorPosition(int pos)
Returns the position of the cursor char position in the current line.
Overrides:
getCursorX in class TextArea
Returns:
the cursor char position in the current line
Method Detail
1425
Returns true if this is the clear key on the device, many devices don't contain a clear
key and even in those that contain it this might be an issue
Parameters:
keyCode - the key code that might be the clear key
Returns:
true if this is the clear key.
longKeyPress
protected void longKeyPress(int keyCode)
If this Component is focused this method is invoked when the user presses and holds
the key
Overrides:
longKeyPress in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
isQwertyInput
public boolean isQwertyInput()
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Returns true if the given input mode should commit immediately or wait for the
commit timeout
Parameters:
mode - the input mode
Returns:
returns true for input mode 123 by default
insertChars
public void insertChars(String c)
Method Detail
1426
Invoked to show the symbol dialog, this method can be overriden by subclasses to
manipulate the symbol table
createSymbolTable
protected Container createSymbolTable()
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class TextArea
Parameters:
keyCode - the key code value to indicate a physical key.
getLongClickDuration
protected int getLongClickDuration()
The amount of time considered as a "long click" causing the long click method to be
invoked.
Returns:
currently defaults to 800
getSymbolTable
public static char[] getSymbolTable()
Sets the symbol table to show when the user clicks the symbol table key
Parameters:
table - the symbol table of the device for the symbol table input
Method Detail
1427
Returns true if the cursor should cycle to the beginning of the text when the user
navigates beyond the edge of the text and visa versa.
Returns:
true by default
isSymbolDialogKey
protected boolean isSymbolDialogKey(int keyCode)
Returns true if this keycode is the one mapping to the symbol dialog popup
Parameters:
keyCode - the keycode to check
Returns:
true if this is the star symbol *
deinitialize
protected void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
setEditable
public void setEditable(boolean b)
If this Component is focused, the key repeat event will call this method.
Overrides:
keyRepeated in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
keyPressed
public void keyPressed(int keyCode)
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class TextArea
Parameters:
keyCode - the key code value to indicate a physical key.
installCommands
protected Command installCommands(Command clear,
Command t9)
Installs the clear and t9 commands onto the parent form, this method can be
overriden to provide device specific placement for these commands
Parameters:
clear - the clear command
t9 - the t9 command
Returns:
clear command already installed in the form if applicable, none if no clear
command was installed before or not applicable.
Method Detail
1428
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly. When overriding this
method you should also override isSelectableInteraction to indicate that a command
is placed appropriately on top of the fire key for 3 soft button phones.
Overrides:
fireClicked in class TextArea
removeCommands
protected void removeCommands(Command clear,
Command t9,
Command originalClear)
Removes the clear and t9 commands from the parent form, this method can be
overriden to provide device specific placement for these commands
Parameters:
clear - the clear command
t9 - the t9 command
originalClear - the command originally assigned as the clear command (or
null if no command was assigned before)
isEditingTrigger
protected boolean isEditingTrigger(int keyCode)
Indicates whether the given key code should be ignored or should trigger editing, by
default fire or any numeric key should trigger editing implicitly. This method is only
called when handles input is false.
Parameters:
keyCode - the keycode passed to the keyPressed method
Returns:
true if this key code should cause a switch to editing mode.
isEditingEndTrigger
protected boolean isEditingEndTrigger(int keyCode)
Indicates whether the given key code should be ignored or should trigger cause
editing to end. By default the fire key, up or down will trigger the end of editing.
Parameters:
keyCode - the keycode passed to the keyPressed method
Returns:
true if this key code should cause a switch to editing mode.
paint
public void paint(Graphics g)
Method Detail
1429
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class TextArea
Returns:
the calculated preferred size based on component content
setCursorBlinkTimeOn
public void setCursorBlinkTimeOn(int time)
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Component
Returns:
true if a repaint is desired or false if no repaint is necessary
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class TextArea
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
isUseSoftkeys
public boolean isUseSoftkeys()
Method Detail
1430
Sets a Done listener on the TextField - notice this listener will be called only on
supported platforms that supports done action on the keyboard
Parameters:
l - the listener
getDoneListener
public ActionListener getDoneListener()
Adds a listener for data change events it will be invoked for every change made to
the text field, notice most platforms will invoke only the
DataChangedListener.CHANGED event
Parameters:
d - the listener
removeDataChangeListener
public void removeDataChangeListener(DataChangedListener d)
Alert the TextField listeners the text has been changed on the TextField
Parameters:
type - the event type: Added, Removed or Change
index - cursor location of the event
isReplaceMenu
public boolean isReplaceMenu()
Indicates whether the menu of the form should be replaced with the T9/Clear
commands for the duration of interactivity with the text field
Returns:
true if the menu should be replaced
setReplaceMenu
public void setReplaceMenu(boolean replaceMenu)
Indicates whether the menu of the form should be replaced with the T9/Clear
commands for the duration of interactivity with the text field
Method Detail
1431
Indicates whether the menu of the form should be replaced with the T9/Clear
commands for the duration of interactivity with the text field
Returns:
true if the menu should be replaced
setReplaceMenuDefault
public static void setReplaceMenuDefault(boolean replaceMenu)
Indicates whether the menu of the form should be replaced with the T9/Clear
commands for the duration of interactivity with the text field
Parameters:
replaceMenu - true if the menu should be replaced
setQwertyAutoDetect
public static void setQwertyAutoDetect(boolean v)
Indicates whether the text field should try to auto detect qwerty and switch the qwerty
device flag implicitly
Parameters:
v - true for qwerty auto detection
setQwertyDevice
public static void setQwertyDevice(boolean v)
The default value for the qwerty flag so it doesn't need setting for every text field
individually.
Parameters:
v - true for qwerty device
isQwertyAutoDetect
public static boolean isQwertyAutoDetect()
Indicates whether the text field should try to auto detect qwerty and switch the qwerty
device flag implicitly
Returns:
true for qwerty auto detection
isQwertyDevice
public static boolean isQwertyDevice()
The default value for the qwerty flag so it doesn't need setting for every text field
individually.
Returns:
true for qwerty devices
setDefaultChangeInputModeKey
public static void setDefaultChangeInputModeKey(int k)
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Key to change the input mode on the device
Parameters:
k - key to change the input mode
getDefaultChangeInputModeKey
public static int getDefaultChangeInputModeKey()
Deprecated. this is a method for use only on old J2ME devices and is ignored
everywhere else
Key to change the input mode on the device
Returns:
Method Detail
1432
Indicates whether the left/right keys will trigger editing, this is true by default. Left and
right key edit trigger might be disabled for cases such as text field positioned
horizontally one next to the other.
Parameters:
leftAndRightEditingTrigger - Indicates whether the left/right keys will
trigger editing
isLeftAndRightEditingTrigger
public boolean isLeftAndRightEditingTrigger()
Indicates whether the left/right keys will trigger editing, this is true by default. Left and
right key edit trigger might be disabled for cases such as text field positioned
horizontally one next to the other.
Returns:
leftAndRightEditingTrigger Indicates whether the left/right keys will trigger
editing
setAlignment
public void setAlignment(int align)
Sets the Alignment of the TextArea to one of: CENTER, LEFT, RIGHT
Overrides:
setAlignment in class TextArea
Parameters:
align - alignment value
See Also:
Component.CENTER, Component.LEFT, Component.RIGHT
Method Detail
1433
Class TextArea
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.TextArea
All Implemented Interfaces:
Animation, StyleListener
Direct Known Subclasses:
TextField
public class
extends Component
An optionally multi-line editable region that can display text and allow a user to edit it. By default the
text area will grow based on its content.
TextArea is useful both for text input and for displaying multi-line data, it is used internally by
components such as SpanLabel & SpanButton.
& TextField are very similar, we discuss the main differences between the two here. In fact
they are so similar that our sample code below was written for TextField but should be
interchangeable with TextArea.
TextArea
TableLayout tl;
int spanButton = 2;
if(Display.getInstance().isTablet()) {
tl = new TableLayout(7, 2);
} else {
tl = new TableLayout(14, 1);
spanButton = 1;
}
tl.setGrowHorizontally(true);
hi.setLayout(tl);
TextField
TextField
TextField
TextField
TextField
TextField
TextField
TextField
TextField
num1
num2
num3
num4
=
=
=
=
new
new
new
new
TextField("",
TextField("",
TextField("",
TextField("",
"1234",
"1234",
"1234",
"1234",
4,
4,
4,
4,
TextArea.NUMERIC);
TextArea.NUMERIC);
TextArea.NUMERIC);
TextArea.NUMERIC);
Class TextArea
1434
Field Summary
Modifier
and Type
static int
Allows any type of input into a text field, if a constraint is not supported by an
underlying implementation this will be the default.
DECIMAL
static int
static int
The user is allowed to enter numeric values with optional decimal fractions, for
example "-123", "0.123", or ".5".
EMAILADDR
static int
This flag is a hint to the implementation that during text editing, the initial letter
of each sentence should be capitalized.
INITIAL_CAPS_WORD
static int
This flag is a hint to the implementation that during text editing, the initial letter
of each word should be capitalized.
NON_PREDICTIVE
static int
static int
Indicates that the text entered does not consist of words that are likely to be
found in dictionaries typically used by predictive input schemes.
NUMERIC
static int
static int
Indicates that the text entered is confidential data that should be obscured
whenever possible.
PHONENUMBER
static int
static int
Field Summary
Indicates that the text entered is sensitive data that the implementation must
never store into a dictionary or table for use in predictive, auto-completing, or
other accelerated input schemes.
UNEDITABLE
1435
URL
Constructor Summary
Constructor and Description
TextArea()
Creates an empty text area, this constructor will create a single line text area similar to a text
field!
TextArea(int rows, int columns)
Creates an area with the given text, this constructor will create a single line text area similar
to a text field!
TextArea(String text, int maxSize)
Creates an area with the given text and maximum size, this constructor will create a single
line text area similar to a text field!
TextArea(String text, int rows, int columns)
Creates an area with the given text, rows, columns and constraint
Method Summary
Modifier
and Type
void
Add an action listener which is invoked when the text area was modified not
during modification.
autoDetectWidestChar(String s)
static void
void
protected
Dimension
protected
Dimension
protected
void
Searches the given string for the widest character using char width, this
operation should only be performed once and it solves cases where a devices
language might have a char bigger than 'W' that isn't consistently bigger.
bindProperty(String prop, BindTarget target)
Method that can be overriden to represent the actual size of the component
when it differs from the desireable size for the viewport
fireClicked()
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly.
getAbsoluteAlignment()
int
Deprecated.
this method is redundant and no longer used
int
getActualRows()
1436
Deprecated.
use Style.getAlignment instead
getAsInt(int invalid)
int
Convenience method for numeric text fields, returns the value as a number or
invalid if the value in the text field isn't a number
getBindablePropertyNames()
String[]
Class[]
Object
int
int
int
int
int
Returns the names of the properties within this component that can be bound
for persistence, the order of these names mean that the first one will be the
first bound
getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
getBoundPropertyValue(String prop)
Returns the position of the cursor char position in the current line.
getCursorY()
static int
Indicates the default vertical alignment for a text field, only applies to single
line text fields
getGrowLimit()
int
String
Image
Label
String
String[]
int
int
int
int
int
Indicates the maximum number of rows in a text area after it has grown, -1
indicates no limit
getHint()
Style
String
Method Summary
Returns the current Component Style allowing code to draw the current
component, you should normally use getUnselected/Pressed/DisabledStyle()
and not this method since it will return different values based on component
state.
getText()
1437
getTextAt(int line)
String
int
Returns the vertical alignment of the text field, this only applies to single line
text field
getWidestChar()
static char
Indicates the widest character in the alphabet, this is useful for detecting
linebreaks internally.
protected
void
initLaf(UIManager uim)
static
boolean
boolean
boolean
Indicates whether a high value for default maxSize will be reduced to a lower
value if the underlying platform throws an exception.
isEditable()
boolean
boolean
protected
boolean
Indicates whether text field input should scroll to the right side when no more
room for the input is present.
isEndsWith3Points()
Simple getter
isEnterKey(int keyCode)
Indicates the enter key to be used for editing the text area and by the text field
isGrowByContent()
boolean
boolean
boolean
boolean
Indicates that the text area should "grow" in height based on the content
beyond the limits indicate by the rows variable
isPendingCommit()
protected
boolean
boolean
static
boolean
void
void
Indicates whether this is a single line text area, in which case "growing" won't
work as expected.
isUseStringWidth()
By default text area uses charWidth since its much faster on some devices
than string width.
keyPressed(int keyCode)
If this Component is focused, the key pressed event will call this method
keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
paint(Graphics g)
void
void
Invoked for devices where the pointer can hover without actually clicking the
display.
void
pointerHoverReleased(int[] x, int[] y)
Method Summary
1438
pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method
preprocess(String text)
protected
char[]
void
Override this to modify the text for rendering in cases of invalid characters for
display, this method allows the developer to replace such characters e.g.:
replace "\\t" with 4 spaces
removeActionListener(ActionListener a)
void
Deprecated.
use Style.setAlignment instead
setAutoDegradeMaxSize(boolean value)
static void
Indicates whether a high value for default maxSize will be reduced to a lower
value if the underlying platform throws an exception.
setBoundPropertyValue(String prop, Object value)
void
void
void
static void
Sets the value of a bound property within this component, notice that this
method MUST NOT fire the property change event when invoked to prevent
recursion!
setColumns(int columns)
Sets the default limit for the native text box size
setDefaultValign(int aDefaultValign)
static void
void
Indicates the default vertical alignment for a text field, only applies to single
line text fields
setEditable(boolean b)
void
If the TextArea text is too long to fit the text to the widget add "..." points at the
last displayable row.
setGrowByContent(boolean growByContent)
void
Indicates that the text area should "grow" in height based on the content
beyond the limits indicate by the rows variable
setGrowLimit(int growLimit)
void
Indicates the maximum number of rows in a text area after it has grown, -1
indicates no limit
setHint(String hint)
void
Sets the TextArea hint text, the hint text is displayed on the TextArea When
there is no text in the TextArea
setHint(String hint, Image icon)
void
Sets the TextArea hint text and Icon, the hint text and icon are displayed on
the TextArea when there is no text in the TextArea
setHintIcon(Image icon)
void
void
void
void
void
void
Method Summary
Sets the TextArea hint icon, the hint is displayed on the TextArea When there
is no text in the TextArea
setLinesToScroll(int linesToScroll)
1439
void
void
setUseStringWidth(boolean aUseStringWidth)
static void
By default text area uses charWidth since its much faster on some devices
than string width.
setVerticalAlignment(int valign)
Sets the vertical alignment of the text field to one of: CENTER, TOP,
BOTTOM
only applies to single line text field
void
setWidestChar(char widestC)
static void
Indicates the widest character in the alphabet, this is useful for detecting
linebreaks internally.
setWidth(int width)
Sets the Component width, this method is exposed for the purpose of external
layout managers and should not be invoked directly.
If a user wishes to effect the component size setPreferredSize should be
used.
void
startEditing()
Launches the text field editing, notice that calling this in a callSerially is
generally considered good practice
void
startEditingAsync()
void
void
void
1440
Field Detail
ANY
public static final int ANY
Allows any type of input into a text field, if a constraint is not supported by an
underlying implementation this will be the default.
See Also:
Constant Field Values
EMAILADDR
public static final int EMAILADDR
The user is allowed to enter numeric values with optional decimal fractions, for
example "-123", "0.123", or ".5".
1441
Indicates that the text entered is confidential data that should be obscured whenever
possible.
See Also:
Constant Field Values
UNEDITABLE
public static final int UNEDITABLE
Indicates that the text entered is sensitive data that the implementation must never
store into a dictionary or table for use in predictive, auto-completing, or other
accelerated input schemes.
See Also:
Constant Field Values
NON_PREDICTIVE
public static final int NON_PREDICTIVE
Indicates that the text entered does not consist of words that are likely to be found in
dictionaries typically used by predictive input schemes.
See Also:
Constant Field Values
INITIAL_CAPS_WORD
public static final int INITIAL_CAPS_WORD
This flag is a hint to the implementation that during text editing, the initial letter of
each word should be capitalized.
See Also:
Constant Field Values
INITIAL_CAPS_SENTENCE
public static final int INITIAL_CAPS_SENTENCE
This flag is a hint to the implementation that during text editing, the initial letter of
each sentence should be capitalized.
See Also:
Constant Field Values
Constructor Detail
TextArea
public TextArea(int rows,
int columns)
Field Detail
1442
Creates an area with the given text, rows, columns and constraint
Parameters:
text - the text to be displayed; if text is null, the empty string "" will be
displayed
rows - the number of rows
columns - - the number of columns
constraint - one of ANY, EMAILADDR, NUMERIC, PHONENUMBER, URL,
DECIMAL it can be bitwised or'd with one of PASSWORD, UNEDITABLE,
SENSITIVE, NON_PREDICTIVE, INITIAL_CAPS_SENTENCE,
INITIAL_CAPS_WORD. E.g. ANY | PASSWORD.
Throws:
IllegalArgumentException - if rows <= 0 or columns <= 1
TextArea
public TextArea(String text,
int maxSize)
Creates an area with the given text and maximum size, this constructor will create a
single line text area similar to a text field!
Parameters:
text - the text to be displayed; if text is null, the empty string "" will be
displayed
maxSize - text area maximum size
TextArea
public TextArea(String text)
Creates an area with the given text, this constructor will create a single line text area
similar to a text field!
Parameters:
Constructor Detail
1443
public TextArea()
Creates an empty text area, this constructor will create a single line text area similar
to a text field!
Method Detail
getDefaultValign
public static int getDefaultValign()
Indicates the default vertical alignment for a text field, only applies to single line text
fields
Returns:
the defaultValign
setDefaultValign
public static void setDefaultValign(int aDefaultValign)
Indicates the default vertical alignment for a text field, only applies to single line text
fields
Parameters:
aDefaultValign - the defaultValign to set
initLaf
protected void initLaf(UIManager uim)
setWidth
public void setWidth(int width)
Sets the Component width, this method is exposed for the purpose of external layout
managers and should not be invoked directly.
If a user wishes to effect the component size setPreferredSize should be used.
Overrides:
setWidth in class Component
Parameters:
width - the width of the component
See Also:
Component.setPreferredSize(com.codename1.ui.geom.Dimension)
Constructor Detail
1444
Convenience method for numeric text fields, returns the value as a number or invalid
if the value in the text field isn't a number
Parameters:
invalid - in case the text isn't an integer this number will be returned
Returns:
the int value of the text field
isEditable
public boolean isEditable()
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
fireClicked
protected void fireClicked()
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly. When overriding this
Method Detail
1445
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
isScrollableY
public boolean isScrollableY()
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHover in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerHoverReleased
public void pointerHoverReleased(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHoverReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
Method Detail
1446
Returns the number of actual rows in the text area taking into consideration
growsByContent
Returns:
the number of rows in the text area
getRows
public int getRows()
Override this to modify the text for rendering in cases of invalid characters for display,
this method allows the developer to replace such characters e.g.: replace "\\t" with 4
spaces
Parameters:
text - the text to process
Returns:
the given string as a processed char array ready for rendering
Method Detail
1447
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Component
Returns:
the calculated preferred size based on component content
calcScrollSize
protected Dimension calcScrollSize()
Method that can be overriden to represent the actual size of the component when it
differs from the desireable size for the viewport
Overrides:
calcScrollSize in class Component
Returns:
scroll size, by default this is the same as the preferred size
addActionListener
public void addActionListener(ActionListener a)
Add an action listener which is invoked when the text area was modified not during
modification. A text field might never fire an action event if it is edited in place and
the user never leaves the text field!
Parameters:
a - actionListener
removeActionListener
public void removeActionListener(ActionListener a)
Method Detail
1448
Sets the default limit for the native text box size
Parameters:
value - default value for the size of the native text box
isGrowByContent
public boolean isGrowByContent()
Indicates that the text area should "grow" in height based on the content beyond the
limits indicate by the rows variable
Returns:
true if the text component should grow and false otherwise
setGrowByContent
public void setGrowByContent(boolean growByContent)
Indicates that the text area should "grow" in height based on the content beyond the
limits indicate by the rows variable
Parameters:
growByContent - true if the text component should grow and false otherwise
setAutoDegradeMaxSize
public static void setAutoDegradeMaxSize(boolean value)
Indicates whether a high value for default maxSize will be reduced to a lower value if
the underlying platform throws an exception.
Parameters:
value - new value for autoDegradeMaxSize
isAutoDegradeMaxSize
public static boolean isAutoDegradeMaxSize()
Indicates whether a high value for default maxSize will be reduced to a lower value if
the underlying platform throws an exception.
Returns:
value for autoDegradeMaxSize
getUnsupportedChars
public String getUnsupportedChars()
Unsupported characters is a string that contains characters that cause issues when
rendering on some problematic fonts. The rendering engine can thus remove them
when drawing.
Returns:
unsupported characters string
setUnsupportedChars
public void setUnsupportedChars(String unsupportedChars)
Unsupported characters is a string that contains characters that cause issues when
rendering on some problematic fonts. The rendering engine can thus remove them
when drawing.
Parameters:
unsupportedChars - the unsupported character string
getLinesToScroll
public int getLinesToScroll()
Method Detail
1449
Indicates the widest character in the alphabet, this is useful for detecting linebreaks
internally. In CJK languages the widest char is different than W hence this
functionality is exposed to developers.
Parameters:
widestC - the widest character
getWidestChar
public static char getWidestChar()
Indicates the widest character in the alphabet, this is useful for detecting linebreaks
internally. In CJK languages the widest char is different than W hence this
functionality is exposed to developers.
Returns:
the widest character
setSingleLineTextArea
public void setSingleLineTextArea(boolean singleLineTextArea)
Indicates whether this is a single line text area, in which case "growing" won't work as
expected.
Parameters:
singleLineTextArea - set to true to force a single line text
isSingleLineTextArea
public boolean isSingleLineTextArea()
Indicates whether this is a single line text area, in which case "growing" won't work as
expected.
Returns:
true if this is a single line text area
setAlignment
public void setAlignment(int align)
Method Detail
1450
Returns the position of the cursor char position in the current line.
Returns:
the cursor char position in the current line
isQwertyInput
public boolean isQwertyInput()
Indicates whether text field input should scroll to the right side when no more room for
the input is present.
Returns:
true if scrolling is enabled
Method Detail
1451
Indicates the enter key to be used for editing the text area and by the text field
Parameters:
keyCode - the key tested
autoDetectWidestChar
public static void autoDetectWidestChar(String s)
Searches the given string for the widest character using char width, this operation
should only be performed once and it solves cases where a devices language might
have a char bigger than 'W' that isn't consistently bigger. Notice that this method will
use the TextArea style font which might differ when switching themes etc.
Parameters:
s - string to search using charWidth
isUseStringWidth
public static boolean isUseStringWidth()
By default text area uses charWidth since its much faster on some devices than
string width. However, with some fonts and especially some languages (such as
Arabic, Korean etc.) the width of the string drawn might not equal the summary of the
width of the chars. Hence for portability to those languages/fonts this flag must be set
to true.
Returns:
the value of useStringWidth
setUseStringWidth
public static void setUseStringWidth(boolean aUseStringWidth)
By default text area uses charWidth since its much faster on some devices than
string width. However, with some fonts and especially some languages (such as
Arabic, Korean etc.) the width of the string drawn might not equal the summary of the
width of the chars. Hence for portability to those languages/fonts this flag must be set
to true.
Parameters:
aUseStringWidth - the new value for useStringWidth
setHint
public void setHint(String hint)
Sets the TextArea hint text, the hint text is displayed on the TextArea When there is
no text in the TextArea
Parameters:
hint - the hint text to display
getHint
public String getHint()
Sets the TextArea hint icon, the hint is displayed on the TextArea When there is no
text in the TextArea
Parameters:
icon - the icon
getHintIcon
public Image getHintIcon()
Method Detail
1452
Sets the TextArea hint text and Icon, the hint text and icon are displayed on the
TextArea when there is no text in the TextArea
Parameters:
hint - the hint text to display
icon - the hint icon to display
getHintLabel
public Label getHintLabel()
Sets the vertical alignment of the text field to one of: CENTER, TOP, BOTTOM
only applies to single line text field
Parameters:
valign - alignment value
See Also:
Component.CENTER, Component.TOP, Component.BOTTOM
getVerticalAlignment
public int getVerticalAlignment()
Returns the vertical alignment of the text field, this only applies to single line text field
Returns:
the vertical alignment of the TextField one of: CENTER, TOP, BOTTOM
See Also:
Component.CENTER, Component.TOP, Component.BOTTOM
getBindablePropertyNames
public String[] getBindablePropertyNames()
Returns the names of the properties within this component that can be bound for
persistence, the order of these names mean that the first one will be the first bound
Overrides:
getBindablePropertyNames in class Component
Returns:
a string array of property names or null
getBindablePropertyTypes
public Class[] getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
Overrides:
getBindablePropertyTypes in class Component
Returns:
the class for binding
bindProperty
public void bindProperty(String prop,
BindTarget target)
Method Detail
1453
Sets the value of a bound property within this component, notice that this method
MUST NOT fire the property change event when invoked to prevent recursion!
Overrides:
setBoundPropertyValue in class Component
Parameters:
prop - the property whose value should be set
value - the value
getGrowLimit
public int getGrowLimit()
Indicates the maximum number of rows in a text area after it has grown, -1 indicates
no limit
Returns:
the growLimit
setGrowLimit
public void setGrowLimit(int growLimit)
Indicates the maximum number of rows in a text area after it has grown, -1 indicates
no limit
Parameters:
growLimit - the growLimit to set
setEndsWith3Points
public void setEndsWith3Points(boolean endsWith3Points)
If the TextArea text is too long to fit the text to the widget add "..." points at the last
displayable row. By default this is set to false
Parameters:
endsWith3Points - true if text should add "..." at the end
isEndsWith3Points
public boolean isEndsWith3Points()
Simple getter
Returns:
true if this TextArea adds "..." when the text is too long
Method Detail
1454
Launches the text field editing, notice that calling this in a callSerially is generally
considered good practice
startEditingAsync
public void startEditingAsync()
Returns the current Component Style allowing code to draw the current component,
you should normally use getUnselected/Pressed/DisabledStyle() and not this method
since it will return different values based on component state. We override get style
here to return the selected style when editing
Overrides:
getStyle in class Component
Returns:
the selected style if editing, super.getStyle() otherwise
Method Detail
1455
Class Tabs
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.Tabs
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
A component that lets the user switch between a group of components by clicking on a tab with a
given title and/or icon.
Tabs/components are added to a Tabs object by using the addTab and insertTab methods. A tab is
represented by an index corresponding to the position it was added in, where the first tab has an
index equal to 0 and the last tab has an index equal to the tab count minus 1.
The Tabs uses a SingleSelectionModel to represent the set of tab indices and the currently selected
index. If the tab count is greater than 0, then there will always be a selected index, which by default
will be initialized to the first tab. If the tab count is 0, then the selected index will be -1.
A simple Tabs sample looks a bit like this:
Form hi = new Form("Tabs", new BorderLayout());
Tabs t = new Tabs();
Style s = UIManager.getInstance().getComponentStyle("Tab");
FontImage icon1 = FontImage.createMaterial(FontImage.MATERIAL_QUESTION_ANSWER, s);
Container container1 = BoxLayout.encloseY(new Label("Label1"), new Label("Label2"));
t.addTab("Tab1", icon1, container1);
t.addTab("Tab2", new SpanLabel("Some text directly in the tab"));
hi.add(BorderLayout.CENTER, t);
Class Tabs
1456
Style s = UIManager.getInstance().getComponentStyle("Button");
FontImage radioEmptyImage = FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_UNCHECKED, s);
FontImage radioFullImage = FontImage.createMaterial(FontImage.MATERIAL_RADIO_BUTTON_CHECKED, s);
((DefaultLookAndFeel)UIManager.getInstance().getLookAndFeel()).setRadioButtonImages(radioFullImage, radioEmptyImage, r
Container container1 = BoxLayout.encloseY(new Label("Swipe the tab to see more"),
new Label("You can put anything here"));
t.addTab("Tab1", container1);
t.addTab("Tab2", new SpanLabel("Some text directly in the tab"));
RadioButton firstTab = new RadioButton("");
RadioButton secondTab = new RadioButton("");
firstTab.setUIID("Container");
secondTab.setUIID("Container");
new ButtonGroup(firstTab, secondTab);
firstTab.setSelected(true);
Container tabsFlow = FlowLayout.encloseCenter(firstTab, secondTab);
hi.add(t);
hi.add(BorderLayout.south(tabsFlow));
t.addSelectionListener((i1, i2) -> {
switch(i2) {
case 0:
if(!firstTab.isSelected()) {
firstTab.setSelected(true);
}
break;
case 1:
if(!secondTab.isSelected()) {
secondTab.setSelected(true);
}
break;
}
});
Field Summary
Field Summary
1457
Constructor Summary
Constructor and Description
Tabs()
Creates an empty TabbedPane with the specified tab placement of either: Component.TOP,
Component.BOTTOM, Component.LEFT, or Component.RIGHT.
Method Summary
Modifier
and Type
void
void
Deprecated.
should use radio button as an argument
void
void
addTabsFocusListener(FocusListener listener)
void
boolean
Deprecated.
use addSelectionListener instead
animate()
protected
void
protected
Component
protected
Motion
protected
void
Container
Creates a tab component by default this is a RadioButton but subclasses can use this to r
Allows developers to customize the motion object for the slide effect to provide a linear sl
deinitialize()
Invoked to indicate that the component initialization is being reversed since the componen
the container hierarchy.
getContentPane()
String[]
A component may expose mutable property names for a UI designer to manipulate, this A
usage internally by the GUI builder code
getPropertyTypeNames()
String[]
Class[]
Object
Component
This method is here to workaround an XMLVM array type bug where property types aren'
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListM
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI builder
getSelectedComponent()
1458
getSelectedIndex()
protected
void
initComponent()
protected
void
initLaf(UIManager manager)
Allows subclasses to bind functionality that relies on fully initialized and "ready for action"
This method initializes the Component defaults constants
insertTab(Component tab, Component component, int index)
void
void
Deprecated.
should use radio button as an argument
insertTab(String title, Image icon, Component component, int index)
Inserts a component, at index, represented by a title and/or icon, either of which
may be
isAnimateTabSelection()
boolean
Indicates whether clicking on a tab button should result in an animation to the selected ta
switch
isChangeTabContainerStyleOnFocus()
boolean
boolean
Indicates that the tabs container should have its style changed to the selected style when
focus this allows incorporating it into the theme of the application
isChangeTabOnFocus()
Indicates that a tab should change when the focus changes without the user physically pr
isEagerSwipeMode()
boolean
boolean
Allows marking tabs as swipe "eager" which instantly triggers swipe on movement rather
swipe.
isSwipeActivated()
Returns true if the swipe between tabs is activated, this is relevant for touch devices only
refreshTheme(boolean merge)
void
void
Method Summary
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS ME
CHANGED THE THEME!
removeSelectionListener(SelectionListener listener)
1459
void
removeTabsFocusListener(FocusListener listener)
void
Deprecated.
use addSelectionListener instead
protected
void
selectTab(Component tab)
Invoked to select a specific tab, this method should be overriden for subclasses overriding
setAnimateTabSelection(boolean animateTabSelection)
Indicates whether clicking on a tab button should result in an animation to the selected ta
switch
void
setChangeTabContainerStyleOnFocus(boolean changeTabContainerStyleOnFocus)
Indicates that the tabs container should have its style changed to the selected style when
focus this allows incorporating it into the theme of the application
void
setChangeTabOnFocus(boolean changeTabOnFocus)
void
Indicates that a tab should change when the focus changes without the user physically pr
setEagerSwipeMode(boolean eagerSwipeMode)
Allows marking tabs as swipe "eager" which instantly triggers swipe on movement rather
swipe.
void
String
Sets a new value to the given property, returns an error message if failed and null if succe
setSelectedIndex(int index)
void
void
void
void
void
This method allows setting the Tabs content pane spacing (right and left), This can be us
where the selected tab is smaller and the right and left tabs are visible on the sides
protected
void
void
void
protected
void
void
void
protected
void
Invokes set text position on the given tab, the tab should be a toggle button radio by defa
showTabs()
void
String
toString()
1460
Constructor Detail
1461
Method Detail
initLaf
protected void initLaf(UIManager manager)
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Container
Parameters:
merge - indicates if the current styles should be merged with the new styles
deinitialize
protected void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
initComponent
protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
animate
public boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Component
Returns:
true if a repaint is desired or false if no repaint is necessary
Constructor Detail
1462
Invokes set text position on the given tab, the tab should be a toggle button radio by
default but can be anything
Parameters:
tabComponent - the component representing the tab
textPosition - the text position
getTabTextPosition
public int getTabTextPosition()
Sets the tab placement for this tabbedpane. Possible values are:
Component.TOP
Component.BOTTOM
Component.LEFT
Component.RIGHT
The default value, if not set, is Component.TOP.
Parameters:
tabPlacement - the placement for the tabs relative to the content
addTab
public void addTab(String title,
Image icon,
Component component)
Adds a component represented by a title and/or icon, either of which can be null.
Cover method for insertTab.
Parameters:
title - the title to be displayed in this tab
icon - the icon to be displayed in this tab
component - the component to be displayed when this tab is clicked
See Also:
insertTab(java.lang.String, com.codename1.ui.Image,
com.codename1.ui.Component, int), removeTabAt(int)
addTab
public void addTab(String title,
Component component)
Adds a component represented by a title and no icon. Cover method for insertTab.
Parameters:
title - the title to be displayed in this tab
component - the component to be displayed when this tab is clicked
See Also:
Method Detail
1463
addTab
public void addTab(Button tab,
Component component)
createTab
protected Component createTab(String title,
Image icon)
Creates a tab component by default this is a RadioButton but subclasses can use this
to return anything
Parameters:
title - the title of the tab
icon - the icon of the tab
Returns:
component instance
insertTab
public void insertTab(String title,
Image icon,
Component component,
int index)
insertTab
public void insertTab(Component tab,
Component component,
int index)
bindTabActionListener
protected void bindTabActionListener(Component tab,
ActionListener l)
Method Detail
1464
Updates the tabs title . This method should be used when overriding createTab
Parameters:
tab - the tab component
title - the title
icon - the new icon
getTabTitle
public String getTabTitle(int index)
Returns the title of the tab component. This method should be used when overriding
createTab
Parameters:
tab - the tab component
Returns:
label of the tab
getTabIcon
protected Image getTabIcon(Component tab)
Returns the icon of the tab component. This method should be used when overriding
createTab
Parameters:
tab - the tab component
Returns:
icon of the tab
getTabIcon
public Image getTabIcon(int index)
Method Detail
1465
Returns the selected icon of the tab component. This method should be used when
overriding createTab
Parameters:
tab - the tab component
Returns:
icon of the tab
getTabSelectedIcon
public Image getTabSelectedIcon(int index)
Sets the selected icon of the tab. This method should be used when overriding
createTab
Parameters:
tab - the tab component
icon - of the tab
removeTabAt
public void removeTabAt(int index)
Removes the tab at index. After the component associated with index is removed, its
visibility is reset to true to ensure it will be visible if added to other containers.
Parameters:
index - the index of the tab to be removed
Throws:
IndexOutOfBoundsException - if index is out of range (index < 0 || index >=
tab count)
See Also:
addTab(java.lang.String, com.codename1.ui.Image,
com.codename1.ui.Component), insertTab(java.lang.String,
com.codename1.ui.Image, com.codename1.ui.Component, int)
getTabComponentAt
public Component getTabComponentAt(int index)
Method Detail
1466
indexOfComponent
public int indexOfComponent(Component component)
Returns the index of the tab for the specified component. Returns -1 if there is no tab
for this component.
Parameters:
component - the component for the tab
Returns:
the first tab which matches this component, or -1 if there is no tab for this
component
getTabCount
public int getTabCount()
Returns the currently selected index for this tabbedpane. Returns -1 if there is no
currently selected tab.
Returns:
the index of the selected tab
getSelectedComponent
public Component getSelectedComponent()
Returns the component associated with the tab at the given index
Returns:
the component is now showing in the tabbed pane
addTabsFocusListener
public void addTabsFocusListener(FocusListener listener)
Method Detail
1467
getContentPane
public Container getContentPane()
Invoked to select a specific tab, this method should be overriden for subclasses
overriding createTab
Parameters:
tab - the tab
setSelectedIndex
public void setSelectedIndex(int index)
Sets the selected index for this tabbedpane. The index must be a valid tab index.
Parameters:
index - the index to be selected
Throws:
IndexOutOfBoundsException - if index is out of range (index < 0 || index >=
tab count)
hideTabs
public void hideTabs()
Method Detail
1468
Returns true if the swipe between tabs is activated, this is relevant for touch devices
only
Returns:
swipe activated flag
setSwipeActivated
public void setSwipeActivated(boolean swipeActivated)
Indicates that a tab should change when the focus changes without the user
physically pressing a button
Returns:
the changeTabOnFocus
setChangeTabOnFocus
public void setChangeTabOnFocus(boolean changeTabOnFocus)
Indicates that a tab should change when the focus changes without the user
physically pressing a button
Parameters:
changeTabOnFocus - the changeTabOnFocus to set
isChangeTabContainerStyleOnFocus
public boolean isChangeTabContainerStyleOnFocus()
Indicates that the tabs container should have its style changed to the selected style
when one of the tabs has focus this allows incorporating it into the theme of the
application
Returns:
the changeTabContainerStyleOnFocus
setChangeTabContainerStyleOnFocus
Indicates that the tabs container should have its style changed to the selected style
when one of the tabs has focus this allows incorporating it into the theme of the
application
Parameters:
changeTabContainerStyleOnFocus - the changeTabContainerStyleOnFocus to
set
setTabsContentGap
public void setTabsContentGap(int tabsGap)
This method allows setting the Tabs content pane spacing (right and left), This can
be used to create an effect where the selected tab is smaller and the right and left
tabs are visible on the sides
Parameters:
tabsGap - the gap on the sides of the content in pixels, the value must be
positive.
Method Detail
1469
The UIID for a tab button which defaults to Tab. Tab buttons used to have two
separate styles for selected and unselected. This was later consolidated so the tabs
behave as a single toggle button (radio button) however one thing that remained is a
call to setUIID that is implicitly made to restore the original "Tab" style.
Effectively Tabs invokes the setUIID call on the Tab switch so if you want to
manipulate the tab UIID manually (have one red and one green tab) this is a
problem..
To enable such code add all the tabs then just just invoke setTabUIID(null) to
disable this behavior.
Parameters:
tabUIID - the tabUIID to set
isEagerSwipeMode
public boolean isEagerSwipeMode()
Allows marking tabs as swipe "eager" which instantly triggers swipe on movement
rather than threshold the swipe.
Returns:
the eagerSwipeMode
setEagerSwipeMode
public void setEagerSwipeMode(boolean eagerSwipeMode)
Allows marking tabs as swipe "eager" which instantly triggers swipe on movement
rather than threshold the swipe.
Parameters:
eagerSwipeMode - the eagerSwipeMode to set
isAnimateTabSelection
public boolean isAnimateTabSelection()
Allows developers to customize the motion object for the slide effect to provide a
linear slide effect.
Parameters:
start - start position
end - end position for the motion
Method Detail
1470
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
1471
Class SwipeableContainer
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.SwipeableContainer
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
Class SwipeableContainer
1472
Summary
Constructor Summary
Constructor and Description
SwipeableContainer(Component bottomLeft, Component top)
Simple Constructor
SwipeableContainer(Component bottomLeft, Component bottomRight, Component top)
Simple Constructor
Method Summary
Modifier and
Type
void
boolean
void
protected
void
Component
protected
void
boolean
boolean
boolean
boolean
Allows subclasses to bind functionality that relies on fully initialized and "ready
for action" component state
isOpen()
void
This method will open the top Component to the left if there is a Component
to expose on the right.
openToRight()
void
void
void
Field Summary
This method will open the top Component to the right if there is a Component
to expose on the left.
removeSwipeOpenListener(ActionListener l)
1473
1474
Constructor Detail
SwipeableContainer
public SwipeableContainer(Component bottomLeft,
Component top)
Simple Constructor
Parameters:
- the Component below the top, this Component is exposed when
dragging the top to the right
top - the component on top.
SwipeableContainer
bottomLeft
Simple Constructor
Parameters:
- the Component below the top, this Component is exposed when
dragging the top to the right
bottomRight - the Component below the top, this Component is exposed
when dragging the top to the Left
top - the component on top.
bottomLeft
Method Detail
deinitialize
protected void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
initComponent
protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
openToRight
public void openToRight()
This method will open the top Component to the right if there is a Component to
expose on the left.
openToLeft
public void openToLeft()
This method will open the top Component to the left if there is a Component to
expose on the right.
1475
animate
public boolean animate()
Adds a listener to the SwipeableContainer which will cause an event to dispatch once
the SwipeableContainer is fully opened
Parameters:
Method Detail
1476
Method Detail
1477
Class Stroke
java.lang.Object
com.codename1.ui.Stroke
public class
extends Object
Field Summary
Modifier and Type
static int
static int
static int
static int
static int
static int
Constructor Summary
Constructor and Description
Stroke()
Method Summary
Modifier and Type
boolean
int
int
float
float
int
Class Stroke
1478
void
void
void
void
Field Detail
JOIN_MITER
public static final int JOIN_MITER
Join style constant to join strokes MITER (i.e. pointy) Examples can be seen at here.
See Also:
setJoinStyle(int), getJoinStyle(), Constant Field Values
JOIN_ROUND
public static final int JOIN_ROUND
Join style constant to join strokes rounded. Examples can be seen here.
See Also:
setJoinStyle(int), getJoinStyle(), Constant Field Values
JOIN_BEVEL
public static final int JOIN_BEVEL
Join style constant to join strokes bevel. Examples can be seen here.
See Also:
setJoinStyle(int), getJoinStyle(), Constant Field Values
CAP_BUTT
public static final int CAP_BUTT
Cap style constant to cap strokes with a butt (or flat). Examples can be seen here.
See Also:
setCapStyle(int), getCapStyle(), Constant Field Values
CAP_ROUND
public static final int CAP_ROUND
Cap style constant to cap strokes with a round end. Examples can be seen here
See Also:
setCapStyle(int), getCapStyle(), Constant Field Values
CAP_SQUARE
public static final int CAP_SQUARE
Cap style constant to cap strokes with a square end. Examples can be seen here
See Also:
setCapStyle(int), getCapStyle(), Constant Field Values
Constructor Detail
Method Summary
1479
JOIN_MITER
CAP_BUTT
1.0
4.0
Method Detail
getJoinStyle
public int getJoinStyle()
Returns the join style used for this stroke. See visual examples of join styles here.
Returns:
the joinStyle This will be one of JOIN_MITER, JOIN_ROUND, and JOIN_BEVEL.
See Also:
JOIN_MITER, JOIN_BEVEL, JOIN_ROUND
setJoinStyle
public void setJoinStyle(int joinStyle)
Sets the join style of the stroke. See visual examples of join styles here.
Parameters:
joinStyle - the joinStyle to set. This should be one of JOIN_MITER,
JOIN_ROUND, and JOIN_BEVEL.
See Also:
JOIN_MITER, JOIN_BEVEL, JOIN_ROUND
getCapStyle
public int getCapStyle()
Gets the cap style of the stroke. See visual examples of cap styles here.
Returns:
the capStyle. This will be one of CAP_BUTT, CAP_ROUND, and CAP_SQUARE.
See Also:
CAP_BUTT, CAP_SQUARE, CAP_ROUND
setCapStyle
public void setCapStyle(int capStyle)
Gets the cap style of the stroke. See visual examples of cap styles here.
Parameters:
Constructor Detail
1480
See Also:
CAP_BUTT, CAP_SQUARE, CAP_ROUND
getLineWidth
public float getLineWidth()
Gets the miter limit of the stroke. The Miter limit controls the point at which a Miter
join automatically is converted to a Bevel join. If the distance from the inner
intersection point to the tip of the triangle measured in stroke widths is more than the
Miter limit, the join will be drawn in the Bevel style.
Returns:
the miterLimit
setMiterLimit
public void setMiterLimit(float miterLimit)
Sets the miter limit of the stroke. The Miter limit controls the point at which a Miter join
automatically is converted to a Bevel join. If the distance from the inner intersection
point to the tip of the triangle measured in stroke widths is more than the Miter limit,
the join will be drawn in the Bevel style.
Parameters:
miterLimit - the miterLimit to set
equals
public boolean equals(Object obj)
Method Detail
1481
Method Detail
1482
Class Slider
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.Slider
All Implemented Interfaces:
Animation, StyleListener
Direct Known Subclasses:
SliderBridge
public class
extends Label
The slider component serves both as a slider widget to allow users to select a value on a scale via
touch/arrows and also to indicate progress. The slider defaults to percentage display but can
represent any positive set of values.
is very versatile and can be used to represent things as diverse as the 5 star ranking UI
demonstrated below. Notice that for the UI to work correctly you need to enclose it in a layout that
preserves its preferred size like flow layout.
Slider
Class Slider
1483
Summary
Constructor Summary
Constructor and Description
Slider()
Method Summary
Modifier
and Type
void
Action listeners give a more coarse event only when the user lifts the finger
from the slider
addDataChangedListener(DataChangedListener l)
void
boolean
Adds a listener to data changed events, notice that the status argument to the
data change listener shouldn't be relied upon.
animate()
protected
Dimension
calcPreferredSize()
static
Slider
createInfinite()
void
protected
void
protected
String
int
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy.
fireClicked()
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly.
formattedValue(int value)
Allows formatting the appearance of the progress when text is drawn on top
getIncrements()
The increments when the user presses a key to the left/right/up/down etc.
int
getMaxValue()
int
getMinValue()
int
getProgress()
Style
getSliderEmptySelectedStyle()
Returns the Style used to paint the
Style
getSliderEmptyUnselectedStyle()
Returns the Style used to paint the
Style
getSliderFullSelectedStyle()
Returns the Style used to paint
Style
getSliderFullUnselectedStyle()
Returns the Style used to paint the
Style
getStyle()
Returns the current Component Style allowing code to draw the current
component, you should normally use getUnselected/Pressed/DisabledStyle()
Field Summary
1484
getThumbImage()
void
boolean
Allows subclasses to bind functionality that relies on fully initialized and "ready
for action" component state
isEditable()
boolean
The infinite slider functionality is used to animate progress for which there is no
defined value.
isRenderPercentageOnTop()
boolean
Indicates that the value of the slider should be rendered with a percentage sign
on top of the slider.
boolean
isRenderValueOnTop()
isSelectableInteraction()
protected
boolean
protected
boolean
boolean
void
void
void
void
void
void
If this Component is focused, the key pressed event will call this method
keyReleased(int code)
If this Component is focused, the key released event will call this method
paintComponentBackground(Graphics g)
If this Component is focused, the pointer dragged event will call this method
pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method
pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method
refreshTheme(boolean merge)
void
Makes sure the component is up to date with the current theme, ONLY
INVOKE THIS METHOD IF YOU CHANGED THE THEME!
removeActionListener(ActionListener l)
void
Action listeners give a more coarse event only when the user lifts the finger
from the slider
removeDataChangedListener(DataChangedListener l)
void
void
void
Removes a listener from data changed events, notice that the status argument
to the data change listener shouldn't be relied upon.
setEditable(boolean editable)
The increments when the user presses a key to the left/right/up/down etc.
setInfinite(boolean i)
void
void
setMaxValue(int maxValue)
void
setMinValue(int minValue)
void
setProgress(int value)
Indicates the value of progress made, this method is thread safe and can be
invoked from any thread although discretion should still be kept so one thread
Method Summary
1485
Indicates that the value of the slider should be rendered with a percentage sign
on top of the slider.
void
setRenderValueOnTop(boolean renderValueOnTop)
setThumbImage(Image thumbImage)
void
void
void
protected
boolean
shouldBlockSideSwipe()
A component that might need side swipe such as the slider could block it from
being used for some other purpose when on top of said component.
1486
Constructor Detail
Slider
public Slider()
Method Detail
setUIID
public void setUIID(String id)
This method sets the Component the Unique identifier. This method should be used
before a component has been initialized
Overrides:
setUIID in class Component
Parameters:
id - UIID unique identifier for component type
isStickyDrag
protected boolean isStickyDrag()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
deinitialize
public void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
1487
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Label
Returns:
true if a repaint is desired or false if no repaint is necessary
isInfinite
public boolean isInfinite()
The infinite slider functionality is used to animate progress for which there is no
defined value.
Returns:
true for infinite progress
setInfinite
public void setInfinite(boolean i)
Activates/disables the infinite slider functionality used to animate progress for which
there is no defined value.
Parameters:
i - true for infinite progress
createInfinite
public static Slider createInfinite()
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Component
Parameters:
merge - indicates if the current styles should be merged with the new styles
getProgress
public int getProgress()
Indicates the value of progress made, this method is thread safe and can be invoked
from any thread although discretion should still be kept so one thread doesn't regress
progress made by another thread...
Parameters:
value - new value for progress
formattedValue
protected String formattedValue(int value)
Allows formatting the appearance of the progress when text is drawn on top
Parameters:
Method Detail
1488
Returns the Style used to paint the slider when its full
Returns:
the Style object that shows a completely full style.
getSliderFullSelectedStyle
public Style getSliderFullSelectedStyle()
Returns the Style used to paint the slider when its full and selected
Returns:
the Style object that shows a completely full style.
getSliderEmptyUnselectedStyle
public Style getSliderEmptyUnselectedStyle()
Returns the Style used to paint the slider when its full
Returns:
the Style object that shows a completely full style.
getSliderEmptySelectedStyle
public Style getSliderEmptySelectedStyle()
Returns the Style used to paint the slider when its full and selected
Returns:
the Style object that shows a completely full style.
getStyle
public Style getStyle()
Returns the current Component Style allowing code to draw the current component,
you should normally use getUnselected/Pressed/DisabledStyle() and not this method
since it will return different values based on component state.
Overrides:
getStyle in class Component
Returns:
the component Style object
calcPreferredSize
protected Dimension calcPreferredSize()
Method Detail
1489
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
fireClicked
protected void fireClicked()
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly. When overriding this
method you should also override isSelectableInteraction to indicate that a command
is placed appropriately on top of the fire key for 3 soft button phones.
Overrides:
fireClicked in class Component
isSelectableInteraction
protected boolean isSelectableInteraction()
Method Detail
1490
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
keyReleased
public void keyReleased(int code)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Component
Parameters:
code - the key code value to indicate a physical key.
keyPressed
public void keyPressed(int code)
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class Component
Parameters:
code - the key code value to indicate a physical key.
getIncrements
public int getIncrements()
The increments when the user presses a key to the left/right/up/down etc.
Returns:
increment value
setIncrements
public void setIncrements(int increments)
The increments when the user presses a key to the left/right/up/down etc.
Parameters:
increments - increment value
addDataChangedListener
public void addDataChangedListener(DataChangedListener l)
Adds a listener to data changed events, notice that the status argument to the data
change listener shouldn't be relied upon.
Parameters:
l - new listener
removeDataChangedListener
public void removeDataChangedListener(DataChangedListener l)
Removes a listener from data changed events, notice that the status argument to the
data change listener shouldn't be relied upon.
Parameters:
l - listener to remove
addActionListener
public void addActionListener(ActionListener l)
Action listeners give a more coarse event only when the user lifts the finger from the
slider
Parameters:
l - the listener
Method Detail
1491
Action listeners give a more coarse event only when the user lifts the finger from the
slider
Parameters:
l - the listener
isRenderPercentageOnTop
public boolean isRenderPercentageOnTop()
Indicates that the value of the slider should be rendered with a percentage sign on
top of the slider.
Returns:
true if so
setRenderPercentageOnTop
public void setRenderPercentageOnTop(boolean renderPercentageOnTop)
Indicates that the value of the slider should be rendered with a percentage sign on
top of the slider.
Parameters:
renderPercentageOnTop - true to render percentages
isRenderValueOnTop
public boolean isRenderValueOnTop()
Returns:
the renderValueOnTop
setRenderValueOnTop
public void setRenderValueOnTop(boolean renderValueOnTop)
Parameters:
renderValueOnTop
getMaxValue
public int getMaxValue()
Returns:
the maxValue
setMaxValue
public void setMaxValue(int maxValue)
Parameters:
maxValue
getMinValue
public int getMinValue()
Returns:
the minValue
setMinValue
public void setMinValue(int minValue)
Parameters:
minValue
getThumbImage
public Image getThumbImage()
Method Detail
1492
A component that might need side swipe such as the slider could block it from being
used for some other purpose when on top of said component.
Overrides:
shouldBlockSideSwipe in class Component
Method Detail
1493
Class SideMenuBar
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.MenuBar
com.codename1.ui.SideMenuBar
All Implemented Interfaces:
Animation, ActionListener, StyleListener, Iterable<Component>
public class
extends MenuBar
This is Menu Bar that displays it's commands on a side bar navigation similar to Google+/Facbook
apps navigation
Field Summary
Modifier
and
Type
static
String
static
String
static
String
static
String
When using a side component we might want to only have it behave as a visual
tool and still execute the command when it is clicked.
COMMAND_PLACEMENT_KEY
This string can be used in putClientProperty within command to hint about the
placement of the command
COMMAND_PLACEMENT_VALUE_RIGHT
This string can be used in putClientProperty within command to hint about the
placement of the command e.g.
COMMAND_PLACEMENT_VALUE_TOP
This string can be used in putClientProperty within command to hint about the
placement of the command e.g.
COMMAND_SIDE_COMPONENT
static
String
Allows placing a component instance into the client properties of the command so
it is shown instead of the command e.g.:
putClientProperty(SideMenuBar.COMMAND_SIDE_COMPONENT,
myCustomComponentInstance);
Constructor Summary
Constructor and Description
SideMenuBar()
Empty Constructor
Class SideMenuBar
1494
Method Summary
Modifier and
Type
void
protected
void
protected
void
static void
Folds the current side menu if it is open, notice that the menu will close
asynchronously
closeCurrentMenu(Runnable callback)
static void
void
Folds the current side menu if it is open, when the menu is closed it will
invoke the runnable callback method
closeMenu()
protected
Container
constructSideNavigationComponent()
protected
Button
createOpenButton()
protected
Container
createSideNavigationComponent(Vector commands)
protected
Container
protected
Button
createTouchCommandButton(Command c)
int
getCommandBehavior()
protected
int
Form
Indicates if the section within the X/Y area is a "drag region" where we expect
people to drag or press in which case we can instantly start dragging making
perceived performance faster.
getParentForm()
protected
void
initMenuBar(Form parent)
protected
void
installMenuBar()
boolean
static
boolean
void
void
If this Component is focused, the key released event will call this method
openMenu(String direction)
protected
void
removeAllCommands()
protected
void
removeCommand(Command cmd)
void
protected
void
Method Summary
Indicates the command that is defined as the back command out of this form.
unInstallMenuBar()
1495
1496
Field Detail
COMMAND_PLACEMENT_KEY
public static final String COMMAND_PLACEMENT_KEY
This string can be used in putClientProperty within command to hint about the
placement of the command
See Also:
Constant Field Values
COMMAND_PLACEMENT_VALUE_RIGHT
public static final String COMMAND_PLACEMENT_VALUE_RIGHT
This string can be used in putClientProperty within command to hint about the
placement of the command e.g.
putClientProperty(SideMenuBar.COMMAND_PLACEMENT_KEY,
SideMenuBar.COMMAND_PLACEMENT_VALUE_RIGHT);
See Also:
Constant Field Values
COMMAND_PLACEMENT_VALUE_TOP
public static final String COMMAND_PLACEMENT_VALUE_TOP
This string can be used in putClientProperty within command to hint about the
placement of the command e.g.
putClientProperty(SideMenuBar.COMMAND_PLACEMENT_KEY,
SideMenuBar.COMMAND_PLACEMENT_VALUE_TOP);
See Also:
Constant Field Values
COMMAND_SIDE_COMPONENT
public static final String COMMAND_SIDE_COMPONENT
Allows placing a component instance into the client properties of the command so it is
shown instead of the command e.g.:
putClientProperty(SideMenuBar.COMMAND_SIDE_COMPONENT,
myCustomComponentInstance);
See Also:
Constant Field Values
COMMAND_ACTIONABLE
public static final String COMMAND_ACTIONABLE
When using a side component we might want to only have it behave as a visual tool
and still execute the command when it is clicked. The default behavior is to delegate
events to the component, however if this flag is used the command will act as normal
1497
Constructor Detail
SideMenuBar
public SideMenuBar()
Empty Constructor
Method Detail
initMenuBar
protected void initMenuBar(Form parent)
Folds the current side menu if it is open, notice that the menu will close
asynchronously
closeCurrentMenu
public static void closeCurrentMenu(Runnable callback)
Folds the current side menu if it is open, when the menu is closed it will invoke the
runnable callback method
Parameters:
callback - will be invoked when the menu is actually closed
removeAllCommands
protected void removeAllCommands()
Field Detail
1498
Indicates if the section within the X/Y area is a "drag region" where we expect people
to drag or press in which case we can instantly start dragging making perceived
performance faster. This is invoked by the implementation code to optimize drag start
behavior
Overrides:
getDragRegionStatus in class MenuBar
Parameters:
x - x location for the touch
y - y location for the touch
Returns:
one of the DRAG_REGION_* values
addCommand
public void addCommand(Command cmd)
Indicates the command that is defined as the back command out of this form. A back
command can be used both to map to a hardware button (e.g. on the Sony Ericsson
devices) and by elements such as transitions etc. to change the behavior based on
direction (e.g. slide to the left to enter screen and slide to the right to exit with back).
Overrides:
setBackCommand in class MenuBar
Parameters:
backCommand - the command to treat as the back Command
getCommandBehavior
public int getCommandBehavior()
Overrides:
getCommandBehavior
in class MenuBar
addCommand
protected void addCommand(Command cmd,
int index)
Method Detail
1499
Method Detail
1500
Method Detail
1501
Class RadioButton
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.Button
com.codename1.ui.RadioButton
All Implemented Interfaces:
Animation, StyleListener
public class
extends Button
RadioButton is a Button that maintains a selection state exclusively within a specific ButtonGroup.
Check out CheckBox for a looser selection approach. Both components support a toggle button mode
using the Button.setToggle(boolean) API.
CheckBox cb1 = new CheckBox("CheckBox No Icon");
cb1.setSelected(true);
CheckBox cb2 = new CheckBox("CheckBox With Icon", icon);
CheckBox cb3 = new CheckBox("CheckBox Opposite True", icon);
CheckBox cb4 = new CheckBox("CheckBox Opposite False", icon);
cb3.setOppositeSide(true);
cb4.setOppositeSide(false);
RadioButton rb1 = new RadioButton("Radio 1");
RadioButton rb2 = new RadioButton("Radio 2");
RadioButton rb3 = new RadioButton("Radio 3", icon);
new ButtonGroup(rb1, rb2, rb3);
rb2.setSelected(true);
hi.add(cb1).add(cb2).add(cb3).add(cb4).add(rb1).add(rb2).add(rb3);
Field Summary
Class RadioButton
1502
Constructor Summary
Constructor and Description
RadioButton()
Method Summary
Modifier and
Type
void
protected
Dimension
static
RadioButton
static
RadioButton
static
RadioButton
static
RadioButton
Shorthand for creating the radio button, adding it to a group, setting the
command and making it into a toggle button
createToggle(Image icon, ButtonGroup bg)
Shorthand for creating the radio button, adding it to a group, setting the
icon/text and making it into a toggle button
createToggle(String text, ButtonGroup bg)
Shorthand for creating the radio button, adding it to a group, setting the
icon/text and making it into a toggle button
createToggle(String text, Image icon, ButtonGroup bg)
Shorthand for creating the radio button, adding it to a group, setting the
icon/text and making it into a toggle button
getBindablePropertyNames()
String[]
Class[]
Object
String
protected void
boolean
Returns the names of the properties within this component that can be
bound for persistence, the order of these names mean that the first one will
be the first bound
getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
getBoundPropertyValue(String prop)
Places the radio box on the opposite side at the far end
1503
isSelected()
void
released(int x, int y)
void
Sets the value of a bound property within this component, notice that this
method MUST NOT fire the property change event when invoked to
prevent recursion!
void
setGroup(String groupName)
void
void
Places the radio box on the opposite side at the far end
setSelected(boolean selected)
void
String
toString()
void
Method Summary
1504
Constructor Detail
RadioButton
public RadioButton(String text)
1505
Method Detail
createToggle
public static RadioButton createToggle(String text,
Image icon,
ButtonGroup bg)
Shorthand for creating the radio button, adding it to a group, setting the icon/text and
making it into a toggle button
Parameters:
text - the text for the button
icon - the icon for the button
bg - the button group
Returns:
a radio button
createToggle
public static RadioButton createToggle(String text,
ButtonGroup bg)
Shorthand for creating the radio button, adding it to a group, setting the icon/text and
making it into a toggle button
Parameters:
text - the text for the button
bg - the button group
Returns:
a radio button
createToggle
public static RadioButton createToggle(Image icon,
ButtonGroup bg)
Shorthand for creating the radio button, adding it to a group, setting the icon/text and
making it into a toggle button
Parameters:
icon - the icon for the button
bg - the button group
Returns:
a radio button
createToggle
public static RadioButton createToggle(Command cmd,
ButtonGroup bg)
Shorthand for creating the radio button, adding it to a group, setting the command
and making it into a toggle button
Parameters:
cmd - the command
bg - the button group
Returns:
a radio button
initLaf
protected void initLaf(UIManager uim)
Method Detail
1506
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Button
Returns:
the calculated preferred size based on component content
setGroup
public void setGroup(String groupName)
Method Detail
1507
Places the radio box on the opposite side at the far end
Overrides:
isOppositeSide in class Button
Returns:
the oppositeSide
setOppositeSide
public void setOppositeSide(boolean oppositeSide)
Places the radio box on the opposite side at the far end
Parameters:
oppositeSide - the oppositeSide to set
getBindablePropertyNames
public String[] getBindablePropertyNames()
Returns the names of the properties within this component that can be bound for
persistence, the order of these names mean that the first one will be the first bound
Overrides:
getBindablePropertyNames in class Label
Returns:
a string array of property names or null
getBindablePropertyTypes
public Class[] getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
Overrides:
getBindablePropertyTypes in class Label
Returns:
the class for binding
bindProperty
public void bindProperty(String prop,
BindTarget target)
Method Detail
1508
Sets the value of a bound property within this component, notice that this method
MUST NOT fire the property change event when invoked to prevent recursion!
Overrides:
setBoundPropertyValue in class Label
Parameters:
prop - the property whose value should be set
value - the value
Method Detail
1509
Class RGBImage
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.RGBImage
public class
extends Image
An image that stores its data as an integer RGB array internally, this image cannot be manipulated via
Graphics primitives however its array is accessible and modifiable programmatically. This is very
useful for 2 distinct use cases.
The first use case allows us to manipulate images in a custom way while still preserving alpha
information where applicable.
The second use case allows us to store images in the Java heap which is useful for some constrained
devices. In small devices images are often stored in a separate "heap" which runs out eventually, this
allows us to place the image in the Java heap which is potentially more wasteful but might sometimes
be more abundant.
Note that unless specified otherwise most methods inherited from Image will fail when invoked on this
subclass often with a NullPointerException. This image can be drawn on graphics as usual
Constructor Summary
Constructor and Description
RGBImage(Image img)
Converts an image to an RGB image after which the original image can be GC'd
RGBImage(int[] rgb, int width, int height)
Creates an RGB image from scratch the array isn't copied and can be saved and
manipulated
Method Summary
Modifier
and Type
protected
void
Graphics
int
int[]
int
Returns a mutable array that can be used to change the appearance of the
image arranged as AARRGGBB.
getWidth()
boolean
Image
Class RGBImage
1510
New label optimizations don't invoke drawImage and instead just pass the
native image directly to the underlying renderer.
rotate(int degrees)
Image
Scale the image to the given width and height, this is a fast algorithm that
preserves translucent information
void
Returns a scaled version of this image image using the given width and
height, this is a fast algorithm that preserves translucent information.
void
setOpaque(boolean opaque)
subImage(int x, int y, int width, int height, boolean processAlpha)
Image
Constructor Detail
RGBImage
public RGBImage(Image img)
Converts an image to an RGB image after which the original image can be GC'd
Parameters:
img - the image to convert to an RGB image
RGBImage
public RGBImage(int[] rgb,
int width,
int height)
Creates an RGB image from scratch the array isn't copied and can be saved and
manipulated
Parameters:
rgb - AARRGGBB array
width - width of image
height - height of image
Method Detail
Method Summary
1511
Extracts a subimage from the given image allowing us to breakdown a single large
image into multiple smaller images in RAM, this actually creates a standalone version
of the image for use.
Overrides:
subImage in class Image
Parameters:
x - the x offset from the image
y - the y offset from the image
width - the width of internal images
height - the height of internal images
processAlpha - whether alpha should be processed as well as part of the
cutting
Returns:
An array of all the possible images that can be created from the source
scaled
public Image scaled(int width,
int height)
Returns a scaled version of this image image using the given width and height, this is
a fast algorithm that preserves translucent information. The method accepts -1 to
preserve aspect ratio in the given axis.
Overrides:
scaled in class Image
Parameters:
width - width for the scaling
height - height of the scaled image
Returns:
new image instance scaled to the given height and width
scale
public void scale(int width,
int height)
Scale the image to the given width and height, this is a fast algorithm that preserves
translucent information
Overrides:
scale in class Image
Parameters:
width - width for the scaling
height - height of the scaled image
rotate
public Image rotate(int degrees)
Method Detail
1512
Returns a mutable array that can be used to change the appearance of the image
arranged as AARRGGBB.
Overrides:
getRGB in class Image
Returns:
ARGB int array
drawImage
protected void drawImage(Graphics g,
Object nativeGraphics,
int x,
int y)
Callback invoked internally by Codename One to draw the image/frame onto the
display. Image subclasses can override this method to perform drawing of custom
image types.
Overrides:
drawImage in class Image
Parameters:
g - the graphics object
nativeGraphics - the underlying native graphics which might be essential for
some image types
x - the x coordinate
y - the y coordinate
setOpaque
public void setOpaque(boolean opaque)
isOpaque
public boolean isOpaque()
Indicates if an image should be treated as opaque, this can improve support for fast
drawing of RGB images without alpha support.
Overrides:
isOpaque in class Image
Returns:
true if the image is completely opqaque which allows for some heavy
optimizations
getWidth
public int getWidth()
Method Detail
1513
New label optimizations don't invoke drawImage and instead just pass the native
image directly to the underlying renderer. This is problematic for some image types
specifically timeline & FontImage and this method allows these classes to indicate
that they need that legacy behavior of calling drawImage.
Overrides:
requiresDrawImage in class Image
Returns:
true if a drawImage call is a required
Method Detail
1514
Class PeerComponent
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.PeerComponent
All Implemented Interfaces:
Animation, StyleListener
public class
extends Component
A peer component is essentially a "dummy" Codename One component used to calculate the position
of the actual native platform specific component. The behavior of a peer component is very platform
specific, it is meant for platforms where a native component can be integrated with a Codename One
component. Codename One features such as glass pane, z-ordering, dialogs & menus might not work
as expected in all situations where peer components are involved. E.g. a peer component might hide
itself when a menu/dialog is shown and recreate itself when it is hidden/disposed.
Field Summary
Constructor Summary
Modifier
protected
Method Summary
Modifier and
Type
boolean
protected
Dimension
protected
Dimension
static
PeerComponent
protected void
protected void
Class PeerComponent
1515
focusGained()
protected Image
Object
protected Image
boolean
The peer image is drawn when the component doesn't exist or during
transition a placeholder image can be placed in the beginning to show
something while the peer is being created asynchronously.
handlesInput()
protected void
void
void
void
void
If this Component is focused, the key pressed event will call this method
keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
keyRepeated(int keyCode)
If this Component is focused, the key repeat event will call this method.
onPositionSizeChange()
protected void
void
protected void
void
protected void
protected void
Paints the UI for the scrollbars on the component, this will be invoked
only for scrollable components.
paintScrollbarX(Graphics g)
protected void
Paints the UI for the scrollbar on the X axis, this method allows
component subclasses to customize the look of a scrollbar
paintScrollbarY(Graphics g)
protected void
Paints the UI for the scrollbar on the Y axis, this method allows
component subclasses to customize the look of a scrollbar
pointerDragged(int[] x, int[] y)
void
If this Component is focused, the pointer dragged event will call this
method
pointerDragged(int x, int y)
void
If this Component is focused, the pointer dragged event will call this
method
pointerHover(int[] x, int[] y)
void
Method Summary
Invoked for devices where the pointer can hover without actually clicking
the display.
1516
Invoked for devices where the pointer can hover without actually clicking
the display.
void
pointerPressed(int[] x, int[] y)
If this Component is focused, the pointer pressed event will call this
method
void
pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this
method
void
pointerReleased(int[] x, int[] y)
If this Component is focused, the pointer released event will call this
method
void
pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this
method
void
setLightweightMode(boolean l)
protected void
An optional callback for peers indicating that the peer is now rendered as
part of a transition or some other state and is thus not truly visible.
setPeerImage(Image i)
protected void
protected
boolean
The peer image is drawn when the component doesn't exist or during
transition a placeholder image can be placed in the beginning to show
something while the peer is being created asynchronously.
shouldRenderPeerImage()
Subclasses should return true here if the peer image should be rendered
instead of the actual peer
1517
Constructor Detail
PeerComponent
protected PeerComponent(Object nativePeer)
Method Detail
getPeerImage
protected Image getPeerImage()
The peer image is drawn when the component doesn't exist or during transition a
placeholder image can be placed in the beginning to show something while the peer
is being created asynchronously. This image might be replaced by an internal image
representing the actual content of the peer
Returns:
an image
generatePeerImage
protected Image generatePeerImage()
The native implementation should implement this method to generate a native peer
image representing the component
Returns:
a screenshot of the component
setPeerImage
protected void setPeerImage(Image i)
The peer image is drawn when the component doesn't exist or during transition a
placeholder image can be placed in the beginning to show something while the peer
is being created asynchronously. This image might be replaced by an internal image
representing the actual content of the peer
Parameters:
i - the peer image
shouldRenderPeerImage
protected boolean shouldRenderPeerImage()
Subclasses should return true here if the peer image should be rendered instead of
the actual peer
Returns:
true to render the peer image
1518
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Component
Returns:
true if a repaint is desired or false if no repaint is necessary
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Component
Returns:
the calculated preferred size based on component content
calcScrollSize
protected Dimension calcScrollSize()
Method that can be overriden to represent the actual size of the component when it
differs from the desireable size for the viewport
Overrides:
calcScrollSize in class Component
Returns:
scroll size, by default this is the same as the preferred size
deinitialize
protected void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
fireClicked
protected void fireClicked()
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly. When overriding this
method you should also override isSelectableInteraction to indicate that a command
is placed appropriately on top of the fire key for 3 soft button phones.
Overrides:
fireClicked in class Component
Method Detail
1519
Prevents key events from being grabbed for focus traversal. E.g. a list component
might use the arrow keys for internal navigation so it will switch this flag to true in
order to prevent the focus manager from moving to the next component.
Overrides:
handlesInput in class Component
Returns:
true if key events are being used for focus traversal ; otherwise false
initComponent
protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
keyPressed
public void keyPressed(int keyCode)
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
keyReleased
public void keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
keyRepeated
public void keyRepeated(int keyCode)
If this Component is focused, the key repeat event will call this method.
Overrides:
keyRepeated in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
paint
public void paint(Graphics g)
Method Detail
1520
in interface Animation
Overrides:
paint in class Component
Parameters:
g - the component graphics
paintBackground
protected void paintBackground(Graphics g)
Draws the component border if such a border exists. The border unlike the content of
the component will not be affected by scrolling for a scrollable component.
Overrides:
paintBorder in class Component
Parameters:
g - graphics context on which the border is painted
paintScrollbarX
protected void paintScrollbarX(Graphics g)
Paints the UI for the scrollbar on the X axis, this method allows component
subclasses to customize the look of a scrollbar
Overrides:
paintScrollbarX in class Component
Parameters:
g - the component graphics
paintScrollbarY
protected void paintScrollbarY(Graphics g)
Paints the UI for the scrollbar on the Y axis, this method allows component
subclasses to customize the look of a scrollbar
Overrides:
paintScrollbarY in class Component
Parameters:
g - the component graphics
paintScrollbars
protected void paintScrollbars(Graphics g)
Paints the UI for the scrollbars on the component, this will be invoked only for
scrollable components. This method invokes the appropriate X/Y versions to do all
the work.
Overrides:
paintScrollbars in class Component
Parameters:
g - the component graphics
Method Detail
1521
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerDragged
public void pointerDragged(int x,
int y)
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerHover
public void pointerHover(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHover in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerHoverReleased
public void pointerHoverReleased(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHoverReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerPressed
public void pointerPressed(int[] x,
int[] y)
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerPressed
public void pointerPressed(int x,
int y)
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
Method Detail
1522
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
invalidate
public void invalidate()
Callback useful for sublclasses that need to track the change in size/position of the
component (notice that this might be invoked too many times for a single change)!
setLightweightMode
protected void setLightweightMode(boolean l)
An optional callback for peers indicating that the peer is now rendered as part of a
transition or some other state and is thus not truly visible. In this case the peer should
either make itself invisible or render itself as an image instead of natively
Parameters:
l - true to enable lightweight mode, false to disable it
Method Detail
1523
Interface Painter
All Known Implementing Classes:
BackgroundPainter, GlassTutorial, PainterChain, Timeline
public interface
Painter can be used to draw on components backgrounds. The use of such painter allows reuse of a
background painters for various components. Note in order to view the painter drawing, component
need to have some level of transparency. Usage:
Painter p = new Painter(cmp) {
public void paint(Graphics g, Rectangle rect) {
boolean antiAliased = g.isAntiAliased();
g.setAntiAliased(true);
int r = Math.min(rect.getWidth(), rect.getHeight())/2;
int x = rect.getX() + rect.getWidth()/2 - r;
int y = rect.getY() + rect.getHeight()/2 - r;
switch (style) {
case CircleButtonStrokedDark:
case CircleButtonStrokedLight: {
if (cmp.getStyle().getBgTransparency() != 0) {
int alpha = cmp.getStyle().getBgTransparency();
if (alpha <0) {
alpha = 0xff;
}
g.setColor(cmp.getStyle().getBgColor());
g.setAlpha(alpha);
g.fillArc(x, y, 2*r-1, 2*r-1, 0, 360);
g.setAlpha(0xff);
}
g.setColor(cmp.getStyle().getFgColor());
g.drawArc(x, y, 2*r-1, 2*r-1, 0, 360);
break;
}
case CircleButtonFilledDark:
case CircleButtonFilledLight:
case CircleButtonTransparentDark:
case CircleButtonTransparentLight: {
int alpha = cmp.getStyle().getBgTransparency();
if (alpha < 0) {
alpha = 0xff;
}
g.setAlpha(alpha);
g.setColor(cmp.getStyle().getBgColor());
g.fillArc(x, y, 2*r, 2*r, 0, 360);
g.setAlpha(0xff);
break;
}
}
g.setAntiAliased(antiAliased);
}
};
cmp.getAllStyles().setBgPainter(p);
Method Summary
Modifier and Type
void
Method Detail
paint
void paint(Graphics g,
Rectangle rect)
Interface Painter
1524
Method Detail
1525
Class NavigationCommand
java.lang.Object
com.codename1.ui.Command
com.codename1.ui.NavigationCommand
All Implemented Interfaces:
ActionListener
public class
extends Command
Constructor Summary
Constructor and Description
NavigationCommand(String command)
Method Summary
Modifier and
Type
void
Form
void
Constructor Detail
Class NavigationCommand
1526
Method Detail
setNextForm
public void setNextForm(Form nextForm)
Sets the Form to navigate to when the actionPerformed is invoked on this Command
Parameters:
nextForm - The next Form
getNextForm
public Form getNextForm()
Constructor Detail
1527
Method Detail
1528
Class MenuBar
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.MenuBar
All Implemented Interfaces:
Animation, ActionListener, StyleListener, Iterable<Component>
Direct Known Subclasses:
SideMenuBar
public class
extends Container
implements ActionListener
This class represents the Form MenuBar. This class is responsible to show the Form Commands and
to handle device soft keys, back key, clear key, etc... This class can be overridden and replaced in the
LookAndFeel
See Also:
LookAndFeel.setMenuBarClass(java.lang.Class)
Field Summary
Constructor Summary
Constructor and Description
MenuBar()
Empty Constructor
Method Summary
Modifier
and Type
void
void
protected
void
protected
Dimension
calcPreferredSize()
protected
int
protected
Button
Calculates the amount of columns to give to the touch commands within the
grid
createBackCommandButton()
createCommandComponent(Vector commands)
Class MenuBar
1529
protected
List
Creates the component containing the commands within the given vector used
for showing the menu dialog, this method calls the createCommandList
method by default however it allows more elaborate menu creation.
createCommandList(Vector commands)
Creates the list component containing the commands within the given vector
used for showing the menu dialog
protected
Command
createMenuCancelCommand()
protected
Command
createMenuSelectCommand()
protected
Command
createSelectCommand()
protected
Button
createSoftButton(String uiid)
protected
Button
createTouchCommandButton(Command c)
Button
Command
protected
Command
Command
Command
int
int
protected
Vector
Indicates the command that is defined as the back command out of this form.
getCancelMenuItem()
This method returns the cancel menu item, when a menu is opened
getClearCommand()
Indicates the command that is defined as the clear command in this form.
getCommand(int index)
Command
Default command is invoked when a user presses fire, this functionality works
well in some situations but might collide with elements such as navigation and
combo boxes.
getDragRegionStatus(int x, int y)
protected
int
Style
Indicates if the section within the X/Y area is a "drag region" where we expect
people to drag or press in which case we can instantly start dragging making
perceived performance faster.
getMenuStyle()
Command
protected
Command
getSelectMenuItem()
protected
Container
getTitleAreaContainer()
protected
Component
getTitleComponent()
boolean
This method returns the select menu item, when a menu is opened
Returns the parent Form title area
Gets the Form titleComponent
handlesKeycode(int keyCode)
This method returns true if the MenuBar should handle the given keycode.
protected
void
initMenuBar(Form parent)
protected
void
installMenuBar()
boolean
Method Summary
When set to true the physical back button will minimize the application
1530
isReverseSoftButtons()
Allows an individual form to reverse the layout direction of the softbuttons, this
method is RTL sensitive and might reverse the result based on RTL state
keyPressed(int keyCode)
void
If this Component is focused, the key pressed event will call this method
keyReleased(int keyCode)
void
If this Component is focused, the key released event will call this method
refreshTheme(boolean merge)
void
Makes sure the component is up to date with the current theme, ONLY
INVOKE THIS METHOD IF YOU CHANGED THE THEME!
protected
void
removeAllCommands()
protected
void
removeCommand(Command cmd)
void
This method removes empty J2ME softbuttons that don't have a command
setBackCommand(Command backCommand)
void
Indicates the command that is defined as the back command out of this form.
setClearCommand(Command clearCommand)
void
Indicates the command that is defined as the clear command in this form.
setCommandUIID(Command cmd, String uiid)
Sets the command UIID to the given UIID, notice that this won't work for all
menu types since some menu types might be implemented natively or as a list
in which case the UIID won't apply!
void
setDefaultCommand(Command defaultCommand)
Default command is invoked when a user presses fire, this functionality works
well in some situations but might collide with elements such as navigation and
combo boxes.
void
setMenuCellRenderer(ListCellRenderer menuCellRenderer)
void
setMinimizeOnBack(boolean minimizeOnBack)
void
When set to true the physical back button will minimize the application
setSelectCommand(Command selectCommand)
void
void
Sets the menu transitions for showing/hiding the menu, can be null...
setUnselectedStyle(Style style)
Changes the Component Style by replacing the Component Style with the
given Style
void
showMenu()
void
protected
Command
protected
void
showMenuDialog(Dialog menu)
1531
Constructor Detail
1532
Empty Constructor
Method Detail
initMenuBar
protected void initMenuBar(Form parent)
This method removes empty J2ME softbuttons that don't have a command
getCommandBehavior
public int getCommandBehavior()
setDefaultCommand
public void setDefaultCommand(Command defaultCommand)
Default command is invoked when a user presses fire, this functionality works well in
some situations but might collide with elements such as navigation and combo boxes.
Use with caution.
Parameters:
defaultCommand - the command to treat as default
getDefaultCommand
public Command getDefaultCommand()
Default command is invoked when a user presses fire, this functionality works well in
some situations but might collide with elements such as navigation and combo boxes.
Use with caution.
Returns:
the command to treat as default
setClearCommand
public void setClearCommand(Command clearCommand)
Indicates the command that is defined as the clear command in this form. A clear
command can be used both to map to a "clear" hardware button if such a button
exists.
Parameters:
clearCommand - the command to treat as the clear Command
getClearCommand
public Command getClearCommand()
Indicates the command that is defined as the clear command in this form. A clear
command can be used both to map to a "clear" hardware button if such a button
exists.
Returns:
the command to treat as the clear Command
findCommandComponent
public Button findCommandComponent(Command c)
Constructor Detail
1533
Indicates the command that is defined as the back command out of this form. A back
command can be used both to map to a hardware button (e.g. on the Sony Ericsson
devices) and by elements such as transitions etc. to change the behavior based on
direction (e.g. slide to the left to enter screen and slide to the right to exit with back).
Parameters:
backCommand - the command to treat as the back Command
getBackCommand
public Command getBackCommand()
Indicates the command that is defined as the back command out of this form. A back
command can be used both to map to a hardware button (e.g. on the Sony Ericsson
devices) and by elements such as transitions etc. to change the behavior based on
direction (e.g. slide to the left to enter screen and slide to the right to exit with back).
Returns:
the command to treat as the back Command
getSelectCommand
public Command getSelectCommand()
Changes the Component Style by replacing the Component Style with the given Style
Overrides:
setUnselectedStyle in class Component
Parameters:
style - the component Style object
calcPreferredSize
protected Dimension calcPreferredSize()
Prevents scaling down of the menu when there is no text on the menu bar
Method Detail
1534
Sets the menu transitions for showing/hiding the menu, can be null...
showMenu
public void showMenu()
This method shows the menu on the Form. The method creates a Dialog with the
commands and calls showMenuDialog. The method blocks until the user dispose the
dialog.
createBackCommandButton
protected Button createBackCommandButton()
addCommand
public void addCommand(Command cmd)
Method Detail
1535
Factory method that returns the Form select Command. This Command is used when
Display.getInstance().isThirdSoftButton() returns true. This method can be overridden
to customize the Command on the Form.
Returns:
Command
createMenuSelectCommand
protected Command createMenuSelectCommand()
Factory method that returns the Form Menu select Command. This method can be
overridden to customize the Command on the Form.
Returns:
Command
createMenuCancelCommand
protected Command createMenuCancelCommand()
Factory method that returns the Form Menu cancel Command. This method can be
overridden to customize the Command on the Form.
Returns:
Command
setMenuCellRenderer
public void setMenuCellRenderer(ListCellRenderer menuCellRenderer)
The MenuBar default implementation shows the menu commands in a List contained
in a Dialog. This method replaces the menu ListCellRenderer of the Menu List.
Parameters:
menuCellRenderer getMenuStyle
public Style getMenuStyle()
This method returns true if the MenuBar should handle the given keycode.
Parameters:
keyCode - to determine if the MenuBar is responsible for.
Returns:
true if the keycode is a MenuBar related keycode such as softkey, back
button, clear button, ...
keyPressed
public void keyPressed(int keyCode)
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class Container
Parameters:
keyCode - the key code value to indicate a physical key.
Method Detail
1536
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Container
Parameters:
keyCode - the key code value to indicate a physical key.
refreshTheme
public void refreshTheme(boolean merge)
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Container
Parameters:
merge - indicates if the current styles should be merged with the new styles
showMenuDialog
protected Command showMenuDialog(Dialog menu)
A menu is implemented as a dialog, this method allows you to override dialog display
in order to customize the dialog menu in various ways
Parameters:
menu - a dialog containing menu options that can be customized
Returns:
the command selected by the user in the dialog (not menu) Select or Cancel
isReverseSoftButtons
protected boolean isReverseSoftButtons()
Allows an individual form to reverse the layout direction of the softbuttons, this
method is RTL sensitive and might reverse the result based on RTL state
Returns:
The value of
UIManager.getInstance().getLookAndFeel().isReverseSoftButtons()
calculateTouchCommandGridColumns
protected int calculateTouchCommandGridColumns(Container grid)
Calculates the amount of columns to give to the touch commands within the grid
Parameters:
grid - container that will be arranged in the grid containing the components
Returns:
an integer representing the touch command grid size
setCommandUIID
public void setCommandUIID(Command cmd,
String uiid)
Sets the command UIID to the given UIID, notice that this won't work for all menu
types since some menu types might be implemented natively or as a list in which
case the UIID won't apply!
Parameters:
cmd - the command
uiid - the uiid for the given command
createTouchCommandButton
protected Button createTouchCommandButton(Command c)
Method Detail
1537
Creates the component containing the commands within the given vector used for
showing the menu dialog, this method calls the createCommandList method by
default however it allows more elaborate menu creation.
Parameters:
commands - list of command objects
Returns:
Component that will result in the parent menu dialog recieving a command
event
getCommands
protected Vector getCommands()
Creates the list component containing the commands within the given vector used for
showing the menu dialog
Parameters:
commands - list of command objects
Returns:
List object
getSelectMenuItem
protected Command getSelectMenuItem()
This method returns the select menu item, when a menu is opened
Returns:
select Command
getCancelMenuItem
protected Command getCancelMenuItem()
This method returns the cancel menu item, when a menu is opened
Returns:
cancel Command
isMinimizeOnBack
public boolean isMinimizeOnBack()
When set to true the physical back button will minimize the application
Returns:
the minimizeOnBack
setMinimizeOnBack
public void setMinimizeOnBack(boolean minimizeOnBack)
When set to true the physical back button will minimize the application
Parameters:
minimizeOnBack - the minimizeOnBack to set
getDragRegionStatus
protected int getDragRegionStatus(int x,
int y)
Indicates if the section within the X/Y area is a "drag region" where we expect people
to drag or press in which case we can instantly start dragging making perceived
performance faster. This is invoked by the implementation code to optimize drag start
behavior
Overrides:
Method Detail
1538
Method Detail
1539
Class List<T>
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.List<T>
All Implemented Interfaces:
Animation, StyleListener
Direct Known Subclasses:
ComboBox, MultiList, RSSReader
public class
extends Component
A set of elements that is rendered using a ListCellRenderer and are extracted via the ListModel.
A list can represent many UI concepts ranging from a carousel to a "todo" checklist, this is made
possible thanks to extensive use of Swing's style of MVC. Specifically a list component is relatively
simple, it invokes the model in order to extract the displayed/selected information and shows it to the
user by invoking the cell renderer.
The list class itself is completely decoupled from everything, thus it allows us to extract its content
from any source (e.g. network, storage etc.) and display the information in any form (e.g. checkboxed
elemenents, icons etc.).
Important
List is a pretty complex class to use so we generally recommend developers use Container,
InfiniteScrollAdapter or InfiniteContainer coupled with widgets such as MultiButton. Arranging
those in a BoxLayout on the BoxLayout.Y_AXIS can produce the functionality of the List with better
Class List<T>
1540
See Also:
Container, InfiniteContainer, InfiniteScrollAdapter, MultiButton,
com.codename1.ui.list, MultiList
Field Summary
Modifier and
Type
static int
Indicates the list selection is fixed into place at the center of the list
FIXED_LEAD
static int
static int
static int
Indicates the list selection is fixed into place at the top of the list or at the left
of the list
FIXED_NONE
Indicates that the list is not fixed in place but cycles its elements
FIXED_NONE_ONE_ELEMENT_MARGIN_FROM_EDGE
static int
Indicates the list selection will only reach the edge when there are no more
elements in the list.
FIXED_TRAIL
static int
static int
static int
Important
Indicates the list selection is fixed into place at the bottom of the list or at the
right of the list
HORIZONTAL
1541
Constructor Summary
Constructor and Description
List()
Method Summary
Modifier and
Type
void
void
void
boolean
protected
Dimension
Allows adding an element to a list if the underlying model supports this, notice that
operation and if the model does not support it (default list model does) then this op
addSelectionListener(SelectionListener l)
protected void
protected void
This method allows us to detect an action event internally without implementing the
interface.
fireActionEvent(ActionEvent a)
protected void
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this met
button devices to work properly.
getActionListeners()
Vector
int
Deprecated.
use getListeners instead
getCurrentSelected()
Returns the visual selection during a drag operation, otherwise equivalent to mode
getDragRegionStatus(int x, int y)
protected int
Indicates if the section within the X/Y area is a "drag region" where we expect peop
which case we can instantly start dragging making perceived performance faster.
getFixedSelection()
Field Summary
int
Indicates whether selection is fixable to place in which case all the elements in the
stays in place.
protected int
getGridPosX()
1542
String
Image
int
Collection
int
int
int
ListModel<T>
int
ListCellRenderer
T
int
T
This method allows extracting the action listeners from the current list
getListSizeCalculationSampleCount()
Indicates the number of elements the list should check to determine the element si
getMaxElementHeight()
Maximum number of elements shown in a list, this member is used to calculate the
getMinElementHeight()
Minimum number of elements shown in a list, this member is used to calculate the
getModel()
Returns the current selected item in the list or null for no selection
getSelectedRect()
Rectangle
int
protected
Rectangle
protected void
Returns the component bounds with absolute screen coordinates, for components
selection behavior and are not containers (currently only List) this method allows re
the selection itself which is useful for things such as the popup dialog and similar U
reference the position of the selection externally
getSideGap()
Returns the gap to be left for the side scrollbar on the Y axis.
getVisibleBounds()
Returns the component bounds for scrolling which might differ from the getBounds
e.g.
initLaf(UIManager uim)
boolean
static boolean
static boolean
boolean
boolean
Indicates that the list should be treated as a list of commands, if the user "clicks" a
its action performed method is invoked.
isDefaultFireOnClick()
Indicates whether the list should not paint the focus component if the list itself has
isIgnoreFocusComponentWhenUnfocused()
Indicates whether the list should not paint the focus component if the list itself has
isLongPointerPressActionEnabled()
boolean
Indicates that the background of a cell renderer might mutate between one entry a
recommended that this flag remains false for performance reasons.
boolean
isNumericKeyActions()
Method Summary
1543
isScrollableX()
Elaborate components might not provide tactile feedback for all their areas (e.g.
keyPressed(int keyCode)
If this Component is focused, the key pressed event will call this method
keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
laidOut()
This is a callback method to inform the Component when it's been laidout on the pa
listSelectionChanged(int oldSelected, int newSelected)
void
protected void
If this Component is focused this method is invoked when the user presses and ho
Component
modelChanged(int status, int index)
void
protected String
void
void
void
void
void
This method paints the Component on the screen, it should be overriden by subcla
drawing or invoke the UI API's to let the PLAF perform the rendering.
paramString()
If this Component is focused, the pointer dragged event will call this method
pointerHover(int[] x, int[] y)
Invoked for devices where the pointer can hover without actually clicking the displa
pointerHoverReleased(int[] x, int[] y)
Invoked for devices where the pointer can hover without actually clicking the displa
pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method
pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method
refreshTheme(boolean merge)
void
void
void
void
Makes sure the component is up to date with the current theme, ONLY INVOKE TH
CHANGED THE THEME!
removeActionListener(ActionListener l)
Makes sure the selected index is visible if it is not in the current view rect the list w
setCommandList(boolean commandList)
void
static void
static void
Indicates that the list should be treated as a list of commands, if the user "clicks" a
its action performed method is invoked.
setDefaultFireOnClick(boolean aDefaultFireOnClick)
setDefaultIgnoreFocusComponentWhenUnfocused(boolean aDefaultIgnoreFocusCo
Indicates whether the list should not paint the focus component if the list itself has
setFireOnClick(boolean fireOnClick)
void
Method Summary
This method determines if the List fires the action event when the pointer was click
or only if the item was the selected item By default the value is true, this setting is o
fixed Lists
1544
void
void
Indicates whether selection is fixable to place in which case all the elements in the
stays in place.
setHandlesInput(boolean b)
Sets the TextArea hint text, the hint text is displayed on the TextArea When there i
setHint(String hint, Image icon)
void
void
void
Sets the TextArea hint text and Icon, the hint text and icon are displayed on the Te
text in the TextArea
setHintIcon(Image icon)
Sets the TextArea hint icon, the hint is displayed on the TextArea When there is no
setIgnoreFocusComponentWhenUnfocused(boolean ignoreFocusComponentWhenUnfo
Indicates whether the list should not paint the focus component if the list itself has
setInputOnFocus(boolean inputOnFocus)
void
void
A list can start handling input implicitly upon gaining focus, this can make for a mor
other focus elements exist or when their use case is infrequent.
setItemGap(int itemGap)
void
void
void
void
void
void
Deprecated.
use setRenderer instead, this method was deprecated to confirm better to JavaBea
the getter/setter with the same name
setListSizeCalculationSampleCount(int listSizeCalculationSampleCount)
Indicates the number of elements the list should check to determine the element si
setLongPointerPressActionEnabled(boolean longPointerPressAction)
Maximum number of elements shown in a list, this member is used to calculate the
setMinElementHeight(int minElementHeight)
Minimum number of elements shown in a list, this member is used to calculate the
setModel(ListModel model)
void
void
void
void
void
Indicates that the background of a cell renderer might mutate between one entry a
recommended that this flag remains false for performance reasons.
setNumericKeyActions(boolean numericKeyActions)
This method determines if the animated focus is drawn on top of the List or behind
setRenderer(ListCellRenderer renderer)
void
void
The rendering prototype is optionally used in calculating the size of the List and is r
performance reasons.
setScrollToSelected(boolean scrollToSelected)
This flag indicates to the List if the List should scroll to the selected element when
setSelectedIndex(int index)
void
void
void
void
Method Summary
Sets the current selected offset in the list, by default this implementation will scroll
the selection is outside of the screen
setSelectedIndex(int index, boolean scrollToSelection)
Indicates the values within the component have changed and preferred size should
1545
shouldRenderSelection()
Allows subclasses to override the selection rendering for the component, specifica
themes
size()
int
Field Detail
FIXED_NONE
public static final int FIXED_NONE
1546
Indicates that the list is not fixed in place but cycles its elements
See Also:
Constant Field Values
FIXED_NONE_ONE_ELEMENT_MARGIN_FROM_EDGE
public static final int FIXED_NONE_ONE_ELEMENT_MARGIN_FROM_EDGE
Indicates the list selection will only reach the edge when there are no more elements
in the list.
See Also:
Constant Field Values
FIXED_LEAD
public static final int FIXED_LEAD
Indicates the list selection is fixed into place at the top of the list or at the left of the
list
See Also:
Constant Field Values
FIXED_TRAIL
public static final int FIXED_TRAIL
Indicates the list selection is fixed into place at the bottom of the list or at the right of
the list
See Also:
Constant Field Values
FIXED_CENTER
public static final int FIXED_CENTER
Indicates the list selection is fixed into place at the center of the list
See Also:
Constant Field Values
VERTICAL
public static final int VERTICAL
Constructor Detail
List
public List(Vector items)
Field Detail
1547
Method Detail
isDefaultIgnoreFocusComponentWhenUnfocused
public static boolean isDefaultIgnoreFocusComponentWhenUnfocused()
Indicates whether the list should not paint the focus component if the list itself has no
focus.
Returns:
the defaultIgnoreFocusComponentWhenUnfocused
setDefaultIgnoreFocusComponentWhenUnfocused
Indicates whether the list should not paint the focus component if the list itself has no
focus.
Parameters:
aDefaultIgnoreFocusComponentWhenUnfocused - the
defaultIgnoreFocusComponentWhenUnfocused to set
isDefaultFireOnClick
public static boolean isDefaultFireOnClick()
This is a callback method to inform the Component when it's been laidout on the
parent Container
Constructor Detail
1548
in class Component
modelChanged
protected void modelChanged(int status,
int index)
Returns the gap to be left for the side scrollbar on the Y axis. This method is used by
layout managers to determine the room they should leave for the scrollbar. (note:
side scrollbar rather than left scrollbar is used for a future version that would support
bidi).
Overrides:
getSideGap in class Component
Returns:
the gap to be left for the side scrollbar on the Y axis
isScrollableY
public boolean isScrollableY()
Maximum number of elements shown in a list, this member is used to calculate the
list preferred size. If the number of elements in the model is larger than this then this
value is used in the calculations.
Returns:
the maximum number of elements
setMaxElementHeight
public void setMaxElementHeight(int maxElementHeight)
Maximum number of elements shown in a list, this member is used to calculate the
list preferred size. If the number of elements in the model is larger than this then this
value is used in the calculations.
Parameters:
Method Detail
1549
getMinElementHeight
public int getMinElementHeight()
Minimum number of elements shown in a list, this member is used to calculate the list
preferred size. If the number of elements in the model is smaller than this then this
value is used in the calculations.
Returns:
the minimum number of elements
setMinElementHeight
public void setMinElementHeight(int minElementHeight)
Minimum number of elements shown in a list, this member is used to calculate the list
preferred size. If the number of elements in the model is smaller than this then this
value is used in the calculations.
Parameters:
minElementHeight - the minimum number of elements
size
public int size()
Sets the current selected offset in the list, by default this implementation will scroll the
list to the selection if the selection is outside of the screen
Parameters:
index - the current selected offset in the list
getVisibleBounds
protected Rectangle getVisibleBounds()
Returns the component bounds for scrolling which might differ from the getBounds for
large components e.g. list.
Overrides:
getVisibleBounds in class Component
Returns:
the component bounds
See Also:
Component.getX(), Component.getY()
getDragRegionStatus
protected int getDragRegionStatus(int x,
int y)
Method Detail
1550
Returns the current selected item in the list or null for no selection
Returns:
the current selected item in the list
setSelectedItem
public void setSelectedItem(T item)
Indicates the values within the component have changed and preferred size should
be recalculated
Overrides:
setShouldCalcPreferredSize in class Component
Parameters:
shouldCalcPreferredSize - indicate whether this component need to
recalculate his preferred size
setModel
public void setModel(ListModel model)
Method Detail
1551
Indicates that the list should be treated as a list of commands, if the user "clicks" a
command from the list its action performed method is invoked.
Returns:
true if the list is treated as a command list
setCommandList
public void setCommandList(boolean commandList)
Indicates that the list should be treated as a list of commands, if the user "clicks" a
command from the list its action performed method is invoked.
Parameters:
commandList - true for the list to be treated as a command list
isIgnoreFocusComponentWhenUnfocused
public boolean isIgnoreFocusComponentWhenUnfocused()
Indicates whether the list should not paint the focus component if the list itself has no
focus.
Returns:
the ignoreFocusComponentWhenUnfocused
setIgnoreFocusComponentWhenUnfocused
Indicates whether the list should not paint the focus component if the list itself has no
focus.
Parameters:
ignoreFocusComponentWhenUnfocused - true to ignore the focus component
false otherwise
isMutableRendererBackgrounds
public boolean isMutableRendererBackgrounds()
Indicates that the background of a cell renderer might mutate between one entry and
the next, it is recommended that this flag remains false for performance reasons.
Returns:
the value of the flag
setMutableRendererBackgrounds
public void setMutableRendererBackgrounds(boolean mutableRendererBackgrounds)
Indicates that the background of a cell renderer might mutate between one entry and
the next, it is recommended that this flag remains false for performance reasons.
Parameters:
mutableRendererBackgrounds - the new value for the flag
getListSizeCalculationSampleCount
public int getListSizeCalculationSampleCount()
Indicates the number of elements the list should check to determine the element
sizes. This is ignored when a rendering prototype is present.
Returns:
the listSizeCalculationSampleCount
Method Detail
1552
Indicates the number of elements the list should check to determine the element
sizes. This is ignored when a rendering prototype is present.
Parameters:
listSizeCalculationSampleCount - the listSizeCalculationSampleCount to
set
isLongPointerPressActionEnabled
public boolean isLongPointerPressActionEnabled()
Deprecated. use setRenderer instead, this method was deprecated to confirm better
to JavaBean convention of having the getter/setter with the same name
Sets the renderer which is used to draw list elements
Parameters:
renderer - cell renderer instance
getRenderer
public ListCellRenderer getRenderer()
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Component
Parameters:
merge - indicates if the current styles should be merged with the new styles
Method Detail
1553
Makes sure the selected index is visible if it is not in the current view rect the list will
scroll so it fits within
Parameters:
rect - the rectangle area to scroll to
setHandlesInput
public void setHandlesInput(boolean b)
Prevents key events from being grabbed for focus traversal. E.g. a list component
might use the arrow keys for internal navigation so it will switch this flag to true in
order to prevent the focus manager from moving to the next component.
Overrides:
setHandlesInput in class Component
Parameters:
b - indicates whether key events can be grabbed for focus traversal
fireClicked
protected void fireClicked()
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly. When overriding this
method you should also override isSelectableInteraction to indicate that a command
is placed appropriately on top of the fire key for 3 soft button phones.
Overrides:
fireClicked in class Component
isSelectableInteraction
protected boolean isSelectableInteraction()
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
keyPressed
public void keyPressed(int keyCode)
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
Method Detail
1554
Allows subclasses to override the selection rendering for the component, specifically
the spinner in some themes
Returns:
true to render the selection, false otherwise.
addSelectionListener
public void addSelectionListener(SelectionListener l)
This method allows extracting the action listeners from the current list
Returns:
Collection containing the action listeners on the list
removeActionListener
public void removeActionListener(ActionListener l)
Method Detail
1555
This method allows us to detect an action event internally without implementing the
action listener interface.
fireActionEvent
protected void fireActionEvent(ActionEvent a)
A list can start handling input implicitly upon gaining focus, this can make for a more
intuitive UI when no other focus elements exist or when their use case is infrequent.
However, it might be odd in some cases where the list "steals" focus.
Parameters:
inputOnFocus - true is a list can start handling input implicitly upon gaining
focus
setPaintFocusBehindList
public void setPaintFocusBehindList(boolean paintFocusBehindList)
This method determines if the animated focus is drawn on top of the List or behind
the List when moving.
Parameters:
paintFocusBehindList getItemGap
public int getItemGap()
The rendering prototype is optionally used in calculating the size of the List and is
recommended for performance reasons. You should invoke it with an object
representing a theoretical value in the list which will be used to calculate the size
required for each element in the list.
This allows list size calculations to work across look and feels and allows developers
to predetermine size for list elements.
e.g. For a list of Strings which you would like to always be 5 characters wide you can
use a prototype "XXXXX" which would use the preferred size of the XXXXX String to
determine the size of the list element. E.g. for a list of dates you can use new
Date(30, 12, 00) etc..
The example below was designed for MultiList but should work for any list. Its goal
is to render 2 lines of text with 20 characters and a 5mm square icon:
Map<String, Object> proto = new HashMap<>();
Method Detail
1556
Parameters:
- a value that can be passed to the renderer to indicate
the preferred size of a list component.
getRenderingPrototype
renderingPrototype
public T getRenderingPrototype()
longPointerPress
public void longPointerPress(int x,
int y)
If this Component is focused this method is invoked when the user presses and holds
the pointer on the Component
Overrides:
longPointerPress in class Component
pointerPressed
public void pointerPressed(int x,
int y)
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerHover
public void pointerHover(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHover in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerDragged
public void pointerDragged(int x,
int y)
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
getSelectedRect
public Rectangle getSelectedRect()
Returns the component bounds with absolute screen coordinates, for components
that include an internal selection behavior and are not containers (currently only List)
this method allows returning the position of the selection itself which is useful for
things such as the popup dialog and similar UI's that need to reference the position of
Method Detail
1557
This method determines if the List fires the action event when the pointer was clicked
on one of the items, or only if the item was the selected item By default the value is
true, this setting is only relevant for none fixed Lists
Parameters:
fireOnClick pointerHoverReleased
public void pointerHoverReleased(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHoverReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Component
Returns:
the calculated preferred size based on component content
addItem
public void addItem(T item)
Allows adding an element to a list if the underlying model supports this, notice that it
is an optional operation and if the model does not support it (default list model does)
then this operation may failed.
Parameters:
item - the item to be added to a list model
getFixedSelection
public int getFixedSelection()
Indicates whether selection is fixable to place in which case all the elements in the list
move and selection stays in place.
Returns:
one of: FIXED_NONE, FIXED_TRAIL, FIXED_LEAD, FIXED_CENTER,
FIXED_NONE_CYCLIC
Method Detail
1558
Indicates whether selection is fixable to place in which case all the elements in the list
move and selection stays in place.
Parameters:
fixedSelection - one of: FIXED_NONE, FIXED_TRAIL, FIXED_LEAD,
FIXED_CENTER, FIXED_NONE_CYCLIC
animate
public boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Component
Returns:
true if a repaint is desired or false if no repaint is necessary
isTactileTouch
protected boolean isTactileTouch(int x,
int y)
Elaborate components might not provide tactile feedback for all their areas (e.g. Lists)
this method defaults to returning the value of isTactileTouch
Overrides:
isTactileTouch in class Component
Parameters:
x - the x position
y - the y position
Returns:
True if the device should vibrate
setScrollToSelected
public void setScrollToSelected(boolean scrollToSelected)
This flag indicates to the List if the List should scroll to the selected element when it's
been initialized.
Parameters:
scrollToSelected - if true the List scrolls to the selected element when It's
been initialized.
getGridPosY
protected int getGridPosY()
Method Detail
1559
Returns a string representing the state of this component. This method is intended to
be used only for debugging purposes, and the content and format of the returned
string may vary between implementations. The returned string may be empty but may
not be null.
Overrides:
paramString in class Component
Returns:
a string representation of this component's state
setHint
public void setHint(String hint)
Sets the TextArea hint text, the hint text is displayed on the TextArea When there is
no text in the TextArea
Parameters:
hint - the hint text to display
getHint
public String getHint()
Sets the TextArea hint icon, the hint is displayed on the TextArea When there is no
text in the TextArea
Parameters:
icon - the icon
getHintIcon
public Image getHintIcon()
Sets the TextArea hint text and Icon, the hint text and icon are displayed on the
TextArea when there is no text in the TextArea
Parameters:
hint - the hint text to display
icon - the hint icon to display
Method Detail
1560
Class Label
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
All Implemented Interfaces:
Animation, StyleListener
Direct Known Subclasses:
Button, DefaultListCellRenderer, ScaleImageLabel, Slider
public class
extends Component
Allows displaying a single line of text and icon (both optional) with different alignment options. This
class is a base class for several components allowing them to declare alignment/icon appearance
universally.
Label text can be positioned in one of 4 locations as such:
Label left = new Label("Left", icon);
left.setTextPosition(Component.LEFT);
Label right = new Label("Right", icon);
right.setTextPosition(Component.RIGHT);
Label bottom = new Label("Bottom", icon);
bottom.setTextPosition(Component.BOTTOM);
Label top = new Label("Top", icon);
top.setTextPosition(Component.TOP);
hi.add(left).add(right).add(bottom).add(top);
Field Summary
Class Label
1561
Constructor Summary
Constructor and Description
Label()
Constructs a new label with the specified string of text, left justified.
Label(String text, Image icon)
Constructs a new label with the specified icon text and UIID
Label(String text, String uiid)
Constructs a new label with the specified string of text and uiid
Method Summary
Modifier
and Type
boolean
void
protected
Dimension
int
Deprecated.
use Style.getAlignment instead
getBaseline(int width, int height)
int
int
The baseline for the component text according to which it should be aligned with other co
visual look.
getBaselineResizeBehavior()
Returns a constant indicating how the baseline varies with the size of the component.
getBindablePropertyNames()
String[]
Class[]
Object
int
Image
Object
Image
String
Returns the names of the properties within this component that can be bound for persiste
names mean that the first one will be the first bound
getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
getBoundPropertyValue(String prop)
Returns the gap in pixels between the icon/text to the Label boundaries
getIcon()
If a mask is applied returns the icon with a mask, otherwise returns the icon
getMaskName()
1562
Determines the name of the mask from the image constants thus allowing the mask to be
theme
getPropertyNames()
String[]
A component may expose mutable property names for a UI designer to manipulate, this A
usage internally by the GUI builder code
getPropertyTypeNames()
String[]
Class[]
Object
int
int
int
String
int
This method is here to workaround an XMLVM array type bug where property types aren'
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListM
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI builder
getShiftMillimeters()
Simple getter to return how many pixels to shift the text inside the Label
getStringWidth(Font fnt)
int
Returns the vertical alignment of the Label, this will only work when the icon is in the side
above or bellow it.
static
boolean
isDefaultTickerEnabled()
boolean
boolean
Simple getter
isLegacyRenderer()
Fallback to the old default look and feel renderer for cases where compatibility is essentia
isShouldLocalize()
boolean
Indicates if text should be localized when set to the label, by default all text is localized so
automatic localization for a specific label.
isShowEvenIfBlank()
boolean
boolean
boolean
By default labels and subclasses become 0 sized when they are blank even ignoring their
to true makes the padding take effect even in a blank field.
isTickerEnabled()
void
This method paints the Component on the screen, it should be overriden by subclasses to
drawing or invoke the UI API's to let the PLAF perform the rendering.
protected
String
paramString()
void
Deprecated.
use Style.setAlignment instead
setBoundPropertyValue(String prop, Object value)
void
Sets the value of a bound property within this component, notice that this method MUST N
change event when invoked to prevent recursion!
static
void
setDefaultTickerEnabled(boolean aDefaultTickerEnabled)
void
void
Method Summary
If the Label text is too long fit the text to the widget and add "..." points at the end.
setGap(int gap)
Set the gap in pixels between the icon/text to the Label boundaries
1563
void
Sets the Label icon, if the icon is unmodified a repaint would not be triggered
setLegacyRenderer(boolean legacyRenderer)
void
Fallback to the old default look and feel renderer for cases where compatibility is essentia
setMask(Object mask)
A mask image can be applied to the label (see the image mask method for details) which
rounded image appearance etc.
void
setMaskName(String maskName)
Determines the name of the mask from the image constants thus allowing the mask to be
theme
void
String
Sets a new value to the given property, returns an error message if failed and null if succe
setShiftMillimeters(int shiftMillimeters)
void
void
Indicates if text should be localized when set to the label, by default all text is localized so
automatic localization for a specific label.
void
setShowEvenIfBlank(boolean showEvenIfBlank)
By default labels and subclasses become 0 sized when they are blank even ignoring their
to true makes the padding take effect even in a blank field.
void
setText(String text)
void
void
void
Sets the vertical alignment of the Label to one of: CENTER, TOP, BOTTOM The valign p
relevant relatively to the icon and not the entire label, this will only work when there
void
boolean
shouldTickerStart()
Returns true if a ticker should be started since there is no room to show the text in the lab
startTicker()
void
void
void
void
1564
Constructor Detail
Label
public Label(String text)
Constructs a new label with the specified string of text, left justified.
Parameters:
text - the string that the label presents.
Label
public Label(String text,
String uiid)
Constructs a new label with the specified string of text and uiid
Parameters:
text - the string that the label presents.
uiid - the uiid for the label
Label
public Label()
1565
Constructs a new label with the specified icon text and UIID
Parameters:
text - the text of the label
icon - the image that the label presents.
uiid - the uiid for the label
Label
public Label(String text,
Image icon)
Method Detail
getBaselineResizeBehavior
public int getBaselineResizeBehavior()
Returns a constant indicating how the baseline varies with the size of the component.
Overrides:
getBaselineResizeBehavior in class Component
Returns:
one of BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT,
BRB_CENTER_OFFSET or BRB_OTHER
getBaseline
public int getBaseline(int width,
int height)
Constructor Detail
1566
Sets the Label icon, if the icon is unmodified a repaint would not be triggered
Parameters:
icon - the image that the label presents.
getIcon
public Image getIcon()
Sets the vertical alignment of the Label to one of: CENTER, TOP, BOTTOM The
valign property is only relevant relatively to the icon and not the entire label,
this will only work when there is an icon
Parameters:
valign - alignment value
See Also:
Component.CENTER, Component.TOP, Component.BOTTOM
getVerticalAlignment
public int getVerticalAlignment()
Returns the vertical alignment of the Label, this will only work when the icon is in the
side of the text and not above or bellow it. The valign property is only relevant
relatively to the icon and not the entire label, this will only work when there is
an icon
Returns:
the vertical alignment of the Label one of: CENTER, TOP, BOTTOM
See Also:
Component.CENTER, Component.TOP, Component.BOTTOM
getAlignment
public int getAlignment()
Method Detail
1567
Set the gap in pixels between the icon/text to the Label boundaries
Parameters:
gap - the gap in pixels
getGap
public int getGap()
Returns the gap in pixels between the icon/text to the Label boundaries
Returns:
the gap in pixels between the icon/text to the Label boundaries
paramString
protected String paramString()
Returns a string representing the state of this component. This method is intended to
be used only for debugging purposes, and the content and format of the returned
string may vary between implementations. The returned string may be empty but may
not be null.
Overrides:
paramString in class Component
Returns:
a string representation of this component's state
paint
public void paint(Graphics g)
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Component
Returns:
Method Detail
1568
Simple getter to return how many pixels to shift the text inside the Label
Returns:
number of pixels to shift
setShiftText
public void setShiftText(int shiftText)
This method shifts the text from it's position in pixels. The value can be
positive/negative to move the text to the right/left
Parameters:
shiftText - The number of pixels to move the text
shouldTickerStart
public boolean shouldTickerStart()
Returns true if a ticker should be started since there is no room to show the text in the
label.
Returns:
true if a ticker should start running
startTicker
public void startTicker()
Method Detail
1569
If the Label text is too long fit the text to the widget and add "..." points at the end. By
default this is set to true
Parameters:
endsWith3Points - true if text should add "..." at the end
isEndsWith3Points
public boolean isEndsWith3Points()
Simple getter
Returns:
true if this Label adds "..." when the text is too long
animate
public boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Component
Returns:
true if a repaint is desired or false if no repaint is necessary
isDefaultTickerEnabled
public static boolean isDefaultTickerEnabled()
A mask image can be applied to the label (see the image mask method for details)
which allows for things like rounded image appearance etc.
Parameters:
mask - the mask returned from the image object
getMask
public Object getMask()
Determines the name of the mask from the image constants thus allowing the mask
to be applied from the theme
Returns:
the maskName
Method Detail
1570
Determines the name of the mask from the image constants thus allowing the mask
to be applied from the theme
Parameters:
maskName - the maskName to set
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
1571
If a mask is applied returns the icon with a mask, otherwise returns the icon
Returns:
the icon masked or otherwise
getBindablePropertyNames
public String[] getBindablePropertyNames()
Returns the names of the properties within this component that can be bound for
persistence, the order of these names mean that the first one will be the first bound
Overrides:
getBindablePropertyNames in class Component
Returns:
a string array of property names or null
getBindablePropertyTypes
public Class[] getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
Overrides:
getBindablePropertyTypes in class Component
Returns:
the class for binding
bindProperty
public void bindProperty(String prop,
BindTarget target)
Sets the value of a bound property within this component, notice that this method
MUST NOT fire the property change event when invoked to prevent recursion!
Overrides:
Method Detail
1572
in class Component
Parameters:
prop - the property
value - the value
isShouldLocalize
public boolean isShouldLocalize()
Indicates if text should be localized when set to the label, by default all text is
localized so this allows disabling automatic localization for a specific label.
Returns:
the shouldLocalize value
setShouldLocalize
public void setShouldLocalize(boolean shouldLocalize)
Indicates if text should be localized when set to the label, by default all text is
localized so this allows disabling automatic localization for a specific label.
Parameters:
shouldLocalize - the shouldLocalize to set
getShiftMillimeters
public int getShiftMillimeters()
By default labels and subclasses become 0 sized when they are blank even ignoring
their padding setting this to true makes the padding take effect even in a blank field.
Returns:
the showEvenIfBlank
setShowEvenIfBlank
public void setShowEvenIfBlank(boolean showEvenIfBlank)
By default labels and subclasses become 0 sized when they are blank even ignoring
their padding setting this to true makes the padding take effect even in a blank field.
Parameters:
showEvenIfBlank - the showEvenIfBlank to set
getStringWidth
public int getStringWidth(Font fnt)
Fallback to the old default look and feel renderer for cases where compatibility is
essential
Returns:
Method Detail
1573
Fallback to the old default look and feel renderer for cases where compatibility is
essential
Parameters:
legacyRenderer - the legacyRenderer to set
Method Detail
1574
Class InfiniteContainer
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.InfiniteContainer
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
This abstract Container can scroll indefinitely (or at least until we run out of data). This class uses the
InfiniteScrollAdapter to bring more data and the pull to refresh feature to refresh current displayed
data.
The sample code shows the usage of the nestoria API to fill out an infinitely scrolling list.
Form hi = new Form("InfiniteContainer", new BorderLayout());
Style s = UIManager.getInstance().getComponentStyle("MultiLine1");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 3), false);
InfiniteContainer ic = new InfiniteContainer() {
{@literal @}Override
public Component[] fetchComponents(int index, int amount) {
java.util.List<Map<String, Object>> data = fetchPropertyData("Leeds");
MultiButton[] cmps = new MultiButton[data.size()];
for(int iter = 0 ; iter < cmps.length ; iter++) {
Map<String, Object> currentListing = data.get(iter);
if(currentListing == null) {
return null;
}
String thumb_url = (String)currentListing.get("thumb_url");
String guid = (String)currentListing.get("guid");
String summary = (String)currentListing.get("summary");
cmps[iter] = new MultiButton(summary);
cmps[iter].setIcon(URLImage.createToStorage(placeholder, guid, thumb_url));
}
return cmps;
}
};
hi.add(BorderLayout.CENTER, ic);
Class InfiniteContainer
1575
int pageNumber = 1;
java.util.List<Map<String, Object>> fetchPropertyData(String text) {
try {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("http://api.nestoria.co.uk/api");
r.addArgument("pretty", "0");
r.addArgument("action", "search_listings");
r.addArgument("encoding", "json");
r.addArgument("listing_type", "buy");
r.addArgument("page", "" + pageNumber);
pageNumber++;
r.addArgument("country", "uk");
r.addArgument("place_name", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getRes
Map<String, Object> response = (Map<String, Object>)result.get("response");
return (java.util.List<Map<String, Object>>)response.get("listings");
} catch(Exception err) {
Log.e(err);
return null;
}
}
Field Summary
Constructor Summary
Constructor and Description
InfiniteContainer()
Field Summary
1576
Method Summary
Modifier and Type
abstract
Component[]
InfiniteProgress
protected void
Method Summary
1577
Constructor Detail
InfiniteContainer
public InfiniteContainer()
Method Detail
initComponent
protected void initComponent()
This is an abstract method that should be implemented by the sub classes to fetch
the data. This method is invoked on a background thread, sub classes should
preform their networking/data fetching here. Notice - this method might cause EDT
violations warnings, since the subclasses will need to create the Components not on
the EDT, these warnings are legit and can be ignored.
Parameters:
index - the index from which to bring data
amount - the size of components to bring
Returns:
Components array of the returned data, size of the array can be the size of
the amount or smaller, if no data to fetch method can return null.
1578
Lets us manipulate the infinite progress object e.g. set the animation image etc.
Returns:
the infinite progress component underlying this container
Method Detail
1579
Class Image
java.lang.Object
com.codename1.ui.Image
Direct Known Subclasses:
EncodedImage, FontImage, RGBImage, Timeline
public class
extends Object
Abstracts the underlying platform images allowing us to treat them as a uniform object.
Constructor Summary
Modifier
protected
Subclasses may use this and point to an underlying native image which might be
null for a case of an image that doesn't use native drawing
Method Summary
Modifier
and Type
boolean
Image
Applies the given alpha mask onto this image and returns the resulting image
see the createMask method for indication on how to convert an image into an
alpha mask.
applyMask(Object mask, int x, int y)
Image
Applies the given alpha mask onto this image and returns the resulting image
see the createMask method for indication on how to convert an image into an
alpha mask.
applyMaskAutoScale(Object mask)
Image
Applies the given alpha mask onto this image and returns the resulting image
see the createMask method for indication on how to convert an image into an
alpha mask.
asyncLock(Image internal)
void
Async lock is the equivalent of a lock operation, however it uses the given
image as the hard cache and performs the actual image loading
asynchronously.
static
Image
static
Image
createImage(InputStream stream)
static
Image
static
Image
static
Image
Class Image
1580
static
Image
static
Image
Deprecated.
this method is deprecated as a warning! Don't use this method unless you
actually know what you are doing, if you are invoking this method without
understanding the distinction between native image and Codename One image
then you are using the wrong method.
createImage(String path)
Deprecated.
try to avoid using indexed images explicitly
createMask()
Object
static
Image
Creates a mask from the given image, a mask can be used to apply an arbitrary
alpha channel to any image.
createSVG(String baseURL, boolean animated, byte[] data)
Creates an SVG Image from the given byte array data and the base URL, this
method will throw an exception if SVG is unsupported.
dispose()
void
protected
void
protected
void
Image
Image
Graphics
int
DO NOT CALL THIS METHOD UNLESS YOU KNOW WHAT YOU ARE
DOING! Images dispose automatically for most cases except for very rare
special cases.
drawImage(Graphics g, Object nativeGraphics, int x, int y)
Object
String
int[]
The name of the image is set for some images mostly to ease the debugging of
Codename One application
getRGB()
int[]
Returns the content of this image as a newly created ARGB array or a cached
instance if possible.
getSVGDocument()
Object
int
static
boolean
boolean
boolean
Method Summary
Returns a platform specific DOM object that can be manipulated by the user to
change the SVG Image
getWidth()
1581
isOpaque()
void
This callback indicates that a component pointing at this image is initialized, this
allows an image to make performance sensitive considerations e.g.
mirror()
Image
Creates a mirror image for the given image which is useful for some RTL
scenarios.
modifyAlpha(byte alpha)
Image
Image
Image
Creates a new image instance with the alpha channel of opaque pixels within
the image using the new alpha value.
requiresDrawImage()
boolean
Image
Image
Image
Image
New label optimizations don't invoke drawImage and instead just pass the
native image directly to the underlying renderer.
rotate(int degrees)
Rotates the image by 270 degrees while changing the ratio of the picture
rotate90Degrees(boolean maintainOpacity)
Rotates this image by 90 degrees while changing the ratio of the picture
scale(int width, int height)
void
Deprecated.
scale should return an image rather than modify the image in place use
scaled(int, int) instead
scaled(int width, int height)
Image
Returns a scaled version of this image image using the given width and height,
this is a fast algorithm that preserves translucent information.
scaledHeight(int height)
Image
Image
Image
Scales the image to the given height while updating the width based on the
aspect ratio of the height
scaledLargerRatio(int width, int height)
Scales the image while maintaining the aspect ratio to the larger size image
scaledSmallerRatio(int width, int height)
Scales the image while maintaining the aspect ratio to the smaller size image
scaledWidth(int width)
Image
Scales the image to the given width while updating the height based on the
aspect ratio of the width
setImageName(String imageName)
void
The name of the image is set for some images mostly to ease the debugging of
Codename One application
subImage(int x, int y, int width, int height, boolean processAlpha)
Image
void
Method Summary
1582
void
Constructor Detail
Image
protected Image(Object image)
Subclasses may use this and point to an underlying native image which might be null
for a case of an image that doesn't use native drawing
Parameters:
image - native image object passed to the Codename One implementation
Method Detail
asyncLock
public void asyncLock(Image internal)
Async lock is the equivalent of a lock operation, however it uses the given image as
the hard cache and performs the actual image loading asynchronously. On
completion this method will invoke repaint on the main form if applicable.
Parameters:
internal - the image to show while the actual image loads.
lock
public void lock()
This callback indicates that a component pointing at this image is initialized, this
allows an image to make performance sensitive considerations e.g. an encoded
image might choose to cache itself in RAM. This method may be invoked multiple
times.
isLocked
public boolean isLocked()
This callback indicates that a component pointing at this image is now deinitilized
This method may be invoked multiple times.
isSVGSupported
public static boolean isSVGSupported()
1583
Returns a platform specific DOM object that can be manipulated by the user to
change the SVG Image
Returns:
Platform dependent object, when JSR 226 is supported an SVGSVGElement
might be returned.
createSVG
public static Image createSVG(String baseURL,
boolean animated,
byte[] data)
throws IOException
Creates an SVG Image from the given byte array data and the base URL, this
method will throw an exception if SVG is unsupported.
Parameters:
baseURL - URL which is used to resolve relative references within the SVG file
animated - indicates if the SVG features an animation
data - the conten of the SVG file
Returns:
an image object that can be used as any other image object.
Throws:
IOException - if resource lookup fail SVG is unsupported
isSVG
public boolean isSVG()
Creates a mask from the given image, a mask can be used to apply an arbitrary
alpha channel to any image. A mask is derived from the blue channel (LSB) of the
given image. The generated mask can be used with the apply mask method.
Returns:
mask object that can be used with applyMask
applyMask
public Image applyMask(Object mask,
int x,
int y)
Applies the given alpha mask onto this image and returns the resulting image see the
createMask method for indication on how to convert an image into an alpha mask.
Parameters:
mask - mask object created by the createMask() method.
x - starting x where to apply the mask
y - starting y where to apply the mask
Returns:
image masked based on the given object
applyMask
public Image applyMask(Object mask)
Applies the given alpha mask onto this image and returns the resulting image see the
createMask method for indication on how to convert an image into an alpha mask.
Parameters:
mask - mask object created by the createMask() method.
Returns:
image masked based on the given object
Throws:
Method Detail
1584
applyMaskAutoScale
public Image applyMaskAutoScale(Object mask)
Applies the given alpha mask onto this image and returns the resulting image see the
createMask method for indication on how to convert an image into an alpha mask. If
the image is of a different size it will be scaled to mask size.
Parameters:
mask - mask object created by the createMask() method.
Returns:
image masked based on the given object
subImage
public Image subImage(int x,
int y,
int width,
int height,
boolean processAlpha)
Extracts a subimage from the given image allowing us to breakdown a single large
image into multiple smaller images in RAM, this actually creates a standalone version
of the image for use.
Parameters:
x - the x offset from the image
y - the y offset from the image
width - the width of internal images
height - the height of internal images
processAlpha - whether alpha should be processed as well as part of the
cutting
Returns:
An array of all the possible images that can be created from the source
mirror
public Image mirror()
Creates a mirror image for the given image which is useful for some RTL scenarios.
Notice that this method isn't the most efficient way to perform this task and is
designed for portability over efficiency.
Returns:
a mirrored image
rotate
public Image rotate(int degrees)
Returns an instance of this image rotated by the given number of degrees. By default
90 degree angle divisions are supported, anything else is implementation dependent.
This method assumes a square image. Notice that it is inefficient in the current
implementation to rotate to non-square angles,
E.g. rotating an image to 45, 90 and 135 degrees is inefficient. Use rotatate to 45, 90
and then rotate the 45 to another 90 degrees to achieve the same effect with less
memory.
Parameters:
- A degree in right angle must be larger than 0 and up to 359
degrees
Returns:
new image instance with the closest possible rotation
createIndexed
degrees
Method Detail
1585
Creates a new image instance with the alpha channel of opaque/translucent pixels
within the image using the new alpha value. Transparent (alpha == 0) pixels remain
transparent. All other pixels will have the new alpha value.
Parameters:
alpha - New value for the entire alpha channel
Returns:
Translucent/Opaque image based on the alpha value and the pixels of this
image
modifyAlphaWithTranslucency
public Image modifyAlphaWithTranslucency(byte alpha)
Creates a new image instance with the alpha channel of opaque pixels within the
image using the new alpha value. Transparent (alpha == 0) pixels remain
transparent. Semi translucent pixels will be multiplied by the ratio difference and their
translucency reduced appropriately.
Parameters:
alpha - New value for the entire alpha channel
Returns:
Translucent/Opaque image based on the alpha value and the pixels of this
image
modifyAlpha
public Image modifyAlpha(byte alpha,
int removeColor)
Creates a new image instance with the alpha channel of opaque/translucent pixels
within the image using the new alpha value. Transparent (alpha == 0) pixels remain
transparent. All other pixels will have the new alpha value.
Parameters:
alpha - New value for the entire alpha channel
removeColor - pixels matching this color are made transparent (alpha channel
ignored)
Returns:
Translucent/Opaque image based on the alpha value and the pixels of this
image
createImage
public static Image createImage(String path)
throws IOException
createImage
public static Image createImage(Object nativeImage)
Deprecated. this method is deprecated as a warning! Don't use this method unless
you actually know what you are doing, if you are invoking this method without
understanding the distinction between native image and Codename One image then
you are using the wrong method.
Method Detail
1586
createImage
public static Image createImage(int[] rgb,
int width,
int height)
Parameters:
width - the image width
height - the image height
Returns:
an image in a given width and height dimension
isAlphaMutableImageSupported
public static boolean isAlphaMutableImageSupported()
Method Detail
1587
Parameters:
width - the image width
height - the image height
fillColor - the color with
Method Detail
1588
Callback invoked internally by Codename One to draw the image/frame onto the
display. Image subclasses can override this method to perform drawing of custom
image types.
Parameters:
g - the graphics object
nativeGraphics - the underlying native graphics which might be essential for
some image types
x - the x coordinate
y - the y coordinate
drawImage
protected void drawImage(Graphics g,
Object nativeGraphics,
int x,
int y,
int w,
int h)
Callback invoked internally by Codename One to draw the image/frame onto the
display. Image subclasses can override this method to perform drawing of custom
image types.
Parameters:
g - the graphics object
nativeGraphics - the underlying native graphics which might be essential for
some image types
x - the x coordinate
y - the y coordinate
w - the width to occupy
h - the height to occupy
toRGB
public void toRGB(RGBImage image,
int destX,
int destY,
int x,
int y,
int width,
int height)
Returns the content of this image as a newly created ARGB array or a cached
instance if possible. Note that cached instances may be garbage collected.
Returns:
Method Detail
1589
Scales the image to the given width while updating the height based on the aspect
ratio of the width
Parameters:
width - the given new image width
Returns:
the newly created image
scaledHeight
public Image scaledHeight(int height)
Scales the image to the given height while updating the width based on the aspect
ratio of the height
Parameters:
height - the given new image height
Returns:
the newly created image
scaledSmallerRatio
public Image scaledSmallerRatio(int width,
int height)
Scales the image while maintaining the aspect ratio to the smaller size image
Parameters:
width - the given new image width
height - the given new image height
Returns:
the newly created image
scaledLargerRatio
public Image scaledLargerRatio(int width,
int height)
Scales the image while maintaining the aspect ratio to the larger size image
Parameters:
width - the given new image width
height - the given new image height
Returns:
the newly created image
scaled
public Image scaled(int width,
int height)
Returns a scaled version of this image image using the given width and height, this is
a fast algorithm that preserves translucent information. The method accepts -1 to
preserve aspect ratio in the given axis.
Parameters:
width - width for the scaling
height - height of the scaled image
Returns:
new image instance scaled to the given height and width
getImage
public Object getImage()
Method Detail
1590
Deprecated. scale should return an image rather than modify the image in place use
scaled(int, int) instead
Scale the image to the given width and height, this is a fast algorithm that preserves
translucent information
Parameters:
width - width for the scaling
height - height of the scaled image
isAnimation
public boolean isAnimation()
isOpaque
public boolean isOpaque()
The name of the image is set for some images mostly to ease the debugging of
Codename One application
Returns:
the imageName
setImageName
public void setImageName(String imageName)
The name of the image is set for some images mostly to ease the debugging of
Codename One application
Parameters:
imageName - the imageName to set
dispose
public void dispose()
DO NOT CALL THIS METHOD UNLESS YOU KNOW WHAT YOU ARE DOING!
Images dispose automatically for most cases except for very rare special cases.
Images on devices usually holds a native memory, some platforms garbage
collectors might fail to release the native and to fail with out of memory errors. Use
this method to make sure the image will be released from memory, after calling this
the image will become unusable.
rotate90Degrees
public Image rotate90Degrees(boolean maintainOpacity)
Rotates this image by 90 degrees while changing the ratio of the picture
Parameters:
maintainOpacity - whether the opacity in the image should be maintained
Returns:
a new image rotated by 90 degrees
Method Detail
1591
Rotates the image by 270 degrees while changing the ratio of the picture
Parameters:
maintainOpacity - whether the opacity in the image should be maintained
Returns:
a new image rotated by 270 degrees
flipHorizontally
public Image flipHorizontally(boolean maintainOpacity)
New label optimizations don't invoke drawImage and instead just pass the native
image directly to the underlying renderer. This is problematic for some image types
specifically timeline & FontImage and this method allows these classes to indicate
that they need that legacy behavior of calling drawImage.
Returns:
true if a drawImage call is a required
Method Detail
1592
Class Graphics
java.lang.Object
com.codename1.ui.Graphics
Abstracts the underlying platform graphics context thus allowing us to achieve portability between
MIDP devices and CDC devices. This abstaction simplifies and unifies the Graphics implementations
of various platforms.
A graphics instance should never be created by the developer and is always accessed using either a
paint callback or a mutable image. There is no supported way to create this object directly.
Method Summary
Modifier
and Type
Object
Starts accessing the native graphics in the underlying OS, when accessing the
native graphics Codename One shouldn't be used! The native graphics is
unclipped and untranslated by default and its the responsibility of the caller to
clip/translate appropriately.
clipRect(int x, int y, int width, int height)
void
void
void
Clips the given rectangle by intersecting with the current clipping region, this
method can thus only shrink the clipping region and never increase it.
darkerColor(int factor)
Makes the current color slightly darker, this is useful for many visual effects
drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle)
Draws a circular or elliptical arc based on the given angles and bounding box
void
Draw the given char using the current font and color in the x,y coordinates.
drawChars(char[] data, int offset, int length, int x, int y)
void
void
Draw the given char array using the current font and color in the x,y
coordinates.
drawImage(Image img, int x, int y)
void
void
void
void
void
void
void
Class Graphics
Draws the image so its top left coordinate corresponds to x/y and scales it to
width/height
drawLine(int x1, int y1, int x2, int y2)
1593
Draw a string using the current font and color in the x,y coordinates.
drawString(String str, int x, int y, int textDecoration)
Draw a string using the current font and color in the x,y coordinates.
drawStringBaseline(String str, int x, int y)
void
void
Invoke this to restore Codename One's graphics settings into the native
graphics
fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle)
Fills a circular or elliptical arc based on the given angles and bounding box.
void
void
void
Draws a linear gradient in the given coordinates with the given colors, doesn't
take alpha into consideration when drawing the gradient
fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
Draws a radial gradient in the given coordinates with the given colors, doesn't
take alpha into consideration when drawing the gradient.
fillRect(int x, int y, int width, int height)
void
void
void
Fills the rectangle from the given position according to the width/height minus 1
pixel according to the convention in Java.
fillRect(int x, int y, int w, int h, byte alpha)
Draws a radial gradient in the given coordinates with the given colors, doesn't
take alpha into consideration when drawing the gradient.
void
fillShape(Shape shape)
Fills the given shape using the current alpha and color settings.
fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
int
int[]
int
int
int
int
int
Font
float
Method Summary
1594
getScaleY()
Gets the transformation matrix that is currently applied to this graphics context.
getTranslateX()
boolean
boolean
boolean
boolean
Indicates whether anti-aliasing for text is active, notice that text anti-aliasing is
a separate attribute from standard anti-alisaing.
isAntiAliasedTextSupported()
boolean
Returns true if anti-aliasing for text is supported, notice that text anti-aliasing is
a separate attribute from standard anti-alisaing.
isAntiAliasingSupported()
boolean
boolean
transforms
boolean
isShapeSupported()
lighterColor(int factor)
Makes the current color slightly lighter, this is useful for many visual effects
popClip()
Pops the top clip from the clip stack and sets it as the current clip.
pushClip()
Rotates the coordinate system around a radian angle using the affine transform
rotate(float angle, int pivotX, int pivotY)
Rotates the coordinate system around a radian angle using the affine transform
scale(float x, float y)
void
void
Sets alpha as a value between 0-255 (0 - 0xff) where 255 is completely opaque
and 0 is completely transparent
setAntiAliased(boolean a)
void
void
Method Summary
Set whether anti-aliasing for text is active, notice that text anti-aliasing is a
separate attribute from standard anti-alisaing.
setClip(int[] clip)
1595
void
Sets the current rgb color while ignoring any potential alpha component within
said color value.
void
setFont(Font font)
void
void
to apply to drawing in
void
void
void
Method Detail
translate
public void translate(int x,
int y)
Translates the X/Y location for drawing on the underlying surface. Translation is
incremental so the new value will be added to the current translation and in order to
reset translation we have to invoke translate(-getTranslateX(),
-getTranslateY())
Parameters:
x - the x coordinate
y - the y coordinate
getTranslateX
public int getTranslateX()
Sets the current rgb color while ignoring any potential alpha component within said
color value.
Parameters:
1596
getFont
public Font getFont()
x,
y,
width,
height)
Clips the given rectangle by intersecting with the current clipping region, this method
can thus only shrink the clipping region and never increase it.
Parameters:
x - the x coordinate of the rectangle to intersect the clip with
Method Detail
1597
setClip
public void setClip(int
int
int
int
x,
y,
width,
height)
Pushes the current clip onto the clip stack. It can later be restored using popClip().
popClip
public void popClip()
Pops the top clip from the clip stack and sets it as the current clip.
drawLine
public void drawLine(int
int
int
int
x1,
y1,
x2,
y2)
x,
y,
width,
height)
Fills the rectangle from the given position according to the width/height minus 1 pixel
according to the convention in Java.
Parameters:
x - the x coordinate of the rectangle to be filled.
y - the y coordinate of the rectangle to be filled.
width - the width of the rectangle to be filled.
height - the height of the rectangle to be filled.
drawRect
public void drawRect(int
int
int
int
x,
y,
width,
height)
Method Detail
1598
x,
y,
width,
height,
thickness)
x,
y,
width,
height,
arcWidth,
arcHeight)
Draws a rounded corner rectangle in the given coordinates with the arcWidth/height
matching the last two arguments respectively.
Parameters:
x - the x coordinate of the rectangle to be drawn.
y - the y coordinate of the rectangle to be drawn.
width - the width of the rectangle to be drawn.
height - the height of the rectangle to be drawn.
arcWidth - the horizontal diameter of the arc at the four corners.
arcHeight - the vertical diameter of the arc at the four corners.
lighterColor
public void lighterColor(int factor)
Makes the current color slightly lighter, this is useful for many visual effects
Parameters:
factor - the degree of lightening a color per channel a number from 1 to 255
darkerColor
public void darkerColor(int factor)
Makes the current color slightly darker, this is useful for many visual effects
Parameters:
factor - the degree of lightening a color per channel a number from 1 to 255
fillRoundRect
public void fillRoundRect(int
int
int
int
int
int
x,
y,
width,
height,
arcWidth,
arcHeight)
Method Detail
1599
x,
y,
width,
height,
startAngle,
arcAngle)
Fills a circular or elliptical arc based on the given angles and bounding box. The
resulting arc begins at startAngle and extends for arcAngle degrees. Usage:
Painter p = new Painter(cmp) {
public void paint(Graphics g, Rectangle rect) {
boolean antiAliased = g.isAntiAliased();
g.setAntiAliased(true);
int r = Math.min(rect.getWidth(), rect.getHeight())/2;
int x = rect.getX() + rect.getWidth()/2 - r;
int y = rect.getY() + rect.getHeight()/2 - r;
switch (style) {
case CircleButtonStrokedDark:
case CircleButtonStrokedLight: {
if (cmp.getStyle().getBgTransparency() != 0) {
int alpha = cmp.getStyle().getBgTransparency();
if (alpha <0) {
alpha = 0xff;
}
g.setColor(cmp.getStyle().getBgColor());
g.setAlpha(alpha);
g.fillArc(x, y, 2*r-1, 2*r-1, 0, 360);
g.setAlpha(0xff);
}
g.setColor(cmp.getStyle().getFgColor());
g.drawArc(x, y, 2*r-1, 2*r-1, 0, 360);
break;
}
case CircleButtonFilledDark:
case CircleButtonFilledLight:
case CircleButtonTransparentDark:
case CircleButtonTransparentLight: {
int alpha = cmp.getStyle().getBgTransparency();
if (alpha < 0) {
alpha = 0xff;
}
g.setAlpha(alpha);
g.setColor(cmp.getStyle().getBgColor());
g.fillArc(x, y, 2*r, 2*r, 0, 360);
g.setAlpha(0xff);
break;
}
}
g.setAntiAliased(antiAliased);
}
};
cmp.getAllStyles().setBgPainter(p);
Parameters:
x - the x coordinate of the upper-left corner of the arc to be filled.
y - the y coordinate of the upper-left corner of the arc to be filled.
width - the width of the arc to be filled.
height - the height of the arc to be filled.
startAngle - the beginning angle.
arcAngle - the angular extent of the arc, relative to the start angle.
drawArc
public void drawArc(int
int
int
int
int
int
x,
y,
width,
height,
startAngle,
arcAngle)
Draws a circular or elliptical arc based on the given angles and bounding box
Parameters:
x - the x coordinate of the upper-left corner of the arc to be drawn.
y - the y coordinate of the upper-left corner of the arc to be drawn.
width - the width of the arc to be drawn.
height - the height of the arc to be drawn.
startAngle - the beginning angle.
Method Detail
1600
drawString
public void drawString(String str,
int x,
int y,
int textDecoration)
Draw a string using the current font and color in the x,y coordinates. The font is
drawn from the top position and not the baseline.
Parameters:
str - the string to be drawn.
x - the x coordinate.
y - the y coordinate.
textDecoration - Text decoration bitmask (See Style's
TEXT_DECORATION_* constants)
drawStringBaseline
public void drawStringBaseline(String str,
int x,
int y)
drawStringBaseline
public void drawStringBaseline(String str,
int x,
int y,
int textDecoration)
drawString
public void drawString(String str,
int x,
int y)
Draw a string using the current font and color in the x,y coordinates. The font is
drawn from the top position and not the baseline.
Parameters:
str - the string to be drawn.
x - the x coordinate.
y - the y coordinate.
drawChar
public void drawChar(char character,
int x,
int y)
Draw the given char using the current font and color in the x,y coordinates. The font
is drawn from the top position and not the baseline.
Parameters:
character - - the character to be drawn
x - the x coordinate of the baseline of the text
y - the y coordinate of the baseline of the text
Method Detail
1601
Draw the given char array using the current font and color in the x,y coordinates. The
font is drawn from the top position and not the baseline.
Parameters:
data - the array of characters to be drawn
offset - the start offset in the data
length - the number of characters to be drawn
x - the x coordinate of the baseline of the text
y - the y coordinate of the baseline of the text
drawImage
public void drawImage(Image img,
int x,
int y)
Draws the image so its top left coordinate corresponds to x/y and scales it to
width/height
Parameters:
img - the specified image to be drawn. This method does nothing if img is
null.
x - the x coordinate.
y - the y coordinate.
w - the width to occupy
h - the height to occupy
drawShape
public void drawShape(Shape shape,
Stroke stroke)
Draws a outline shape inside the specified bounding box. The bounding box will
resize the shape to fit in its dimensions.
This is not supported on all platforms and contexts currently. Use
isShapeSupported() to check if the current context supports drawing shapes.
Parameters:
shape - The shape to be drawn.
stroke - the stroke to use
See Also:
#setStroke, isShapeSupported()
fillShape
public void fillShape(Shape shape)
Fills the given shape using the current alpha and color settings.
Method Detail
1602
See Also:
isShapeSupported()
isTransformSupported
public boolean isTransformSupported()
isPerspectiveTransformSupported
public boolean isPerspectiveTransformSupported()
isShapeSupported
public boolean isShapeSupported()
you call
Returns:
true If drawShape(com.codename1.ui.geom.Shape,
com.codename1.ui.Stroke) and fillShape(com.codename1.ui.geom.Shape)
are supported.
See Also:
drawShape(com.codename1.ui.geom.Shape, com.codename1.ui.Stroke),
fillShape(com.codename1.ui.geom.Shape)
setTransform
public void setTransform(Transform transform)
Method Detail
1603
#setTransform(com.codename1.ui.geom.Matrix,int,int)
getTransform
public Transform getTransform()
Gets the transformation matrix that is currently applied to this graphics context.
Returns:
The current transformation matrix.
See Also:
setTransform(com.codename1.ui.Transform)
fillTriangle
public void fillTriangle(int
int
int
int
int
int
x1,
y1,
x2,
y2,
x3,
y3)
startColor,
endColor,
x,
y,
width,
height)
Draws a radial gradient in the given coordinates with the given colors, doesn't take
alpha into consideration when drawing the gradient. Notice that a radial gradient will
result in a circular shape, to create a square use fillRect or draw a larger shape and
clip to the appropriate size.
Parameters:
startColor - the starting RGB color
endColor - the ending RGB color
x - the x coordinate
y - the y coordinate
width - the width of the region to be filled
height - the height of the region to be filled
Method Detail
1604
Draws a radial gradient in the given coordinates with the given colors, doesn't take
alpha into consideration when drawing the gradient. Notice that this method differs
from fillRadialGradient since it draws a square gradient at all times and can thus be
cached Notice that a radial gradient will result in a circular shape, to create a square
use fillRect or draw a larger shape and clip to the appropriate size.
Parameters:
startColor - the starting RGB color
endColor - the ending RGB color
x - the x coordinate
y - the y coordinate
width - the width of the region to be filled
height - the height of the region to be filled
relativeX - indicates the relative position of the gradient within the drawing
region
relativeY - indicates the relative position of the gradient within the drawing
region
relativeSize - indicates the relative size of the gradient within the drawing
region
fillLinearGradient
public void fillLinearGradient(int startColor,
int endColor,
int x,
int y,
int width,
int height,
boolean horizontal)
Draws a linear gradient in the given coordinates with the given colors, doesn't take
alpha into consideration when drawing the gradient
Parameters:
startColor - the starting RGB color
endColor - the ending RGB color
x - the x coordinate
y - the y coordinate
width - the width of the region to be filled
height - the height of the region to be filled
horizontal - indicating wheter it is a horizontal fill or vertical
fillRect
public void fillRect(int x,
int y,
int w,
int h,
byte alpha)
Method Detail
1605
Fills a closed polygon defined by arrays of x and y coordinates. Each pair of (x, y)
coordinates defines a point.
Parameters:
xPoints - - a an array of x coordinates.
yPoints - - a an array of y coordinates.
nPoints - - a the total number of points.
drawPolygon
public void drawPolygon(int[] xPoints,
int[] yPoints,
int nPoints)
Draws a closed polygon defined by arrays of x and y coordinates. Each pair of (x, y)
coordinates defines a point.
Parameters:
xPoints - - a an array of x coordinates.
yPoints - - a an array of y coordinates.
nPoints - - a the total number of points.
isAlphaSupported
public boolean isAlphaSupported()
Indicates whether invoking set/getAlpha would have an effect on all further rendering
from this graphics object.
Returns:
false if setAlpha has no effect true if it applies to everything some effect
setAlpha
public void setAlpha(int a)
Sets alpha as a value between 0-255 (0 - 0xff) where 255 is completely opaque and 0
is completely transparent
Parameters:
a - the alpha value
getAlpha
public int getAlpha()
Returnes the alpha as a value between 0-255 (0 - 0xff) where 255 is completely
opaque and 0 is completely transparent
Returns:
the alpha value
isAntiAliasingSupported
public boolean isAntiAliasingSupported()
Returns true if anti-aliasing for standard rendering operations is supported, notice that
text anti-aliasing is a separate attribute.
Returns:
true if anti aliasing is supported
isAntiAliasedTextSupported
public boolean isAntiAliasedTextSupported()
Returns true if anti-aliasing for text is supported, notice that text anti-aliasing is a
separate attribute from standard anti-alisaing.
Returns:
true if text anti aliasing is supported
Method Detail
1606
Set whether anti-aliasing for text is active, notice that text anti-aliasing is a separate
attribute from standard anti-alisaing.
Parameters:
a - true if text anti aliasing is supported
isAntiAliasedText
public boolean isAntiAliasedText()
Indicates whether anti-aliasing for text is active, notice that text anti-aliasing is a
separate attribute from standard anti-alisaing.
Returns:
true if text anti aliasing is supported
isAffineSupported
public boolean isAffineSupported()
Indicates whether the underlying implementation can draw using an affine transform
hence methods such as rotate, scale and shear would work
Returns:
true if an affine transformation matrix is present
resetAffine
public void resetAffine()
Rotates the coordinate system around a radian angle using the affine transform
Parameters:
angle - the rotation angle in radians
rotate
public void rotate(float angle,
int pivotX,
int pivotY)
Rotates the coordinate system around a radian angle using the affine transform
Parameters:
angle - the rotation angle in radians
Method Detail
1607
shear
public void shear(float x,
float y)
Starts accessing the native graphics in the underlying OS, when accessing the native
graphics Codename One shouldn't be used! The native graphics is unclipped and
untranslated by default and its the responsibility of the caller to clip/translate
appropriately.
When finished with the native graphics it is essential to invoke
endNativeGraphicsAccess
Returns:
an instance of the underlying native graphics object
endNativeGraphicsAccess
public void endNativeGraphicsAccess()
Invoke this to restore Codename One's graphics settings into the native graphics
tileImage
public void tileImage(Image img,
int x,
int y,
int w,
int h)
Method Detail
1608
Class Form
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.Form
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
Direct Known Subclasses:
Dialog
public class
extends Container
Top level component that serves as the root for the UI, this Container handles the menus and title
while placing content between them. By default a forms central content (the content pane) is
scrollable. Form contains Title bar, MenuBar and a ContentPane. Calling to addComponent on the
Form is delegated to the contenPane.addComponent
**************************
*
Title
*
**************************
*
*
*
*
*
ContentPane
*
*
*
*
*
**************************
*
MenuBar
*
**************************
Field Summary
Modifier and
Type
protected
boolean
Indicates whether lists and containers should scroll only via focus and thus
"jump" when moving to a larger component as was the case in older versions
of Codename One.
Constructor Summary
Constructor and Description
Form()
Class Form
1609
Method Summary
Modifier and
Type
protected void
void
Invoked to allow subclasses of form to handle a command from one point rather th
command instances.
addCommand(Command cmd)
void
Adds a command to the menu bar softkeys or into the menu dialog, this version of
command in an arbitrary location.
addCommandListener(ActionListener l)
void
void
void
void
void
void
void
void
void
void
boolean
void
void
Component
Component
AnimationManager
Command
Command
Command
int
Form
Constructor Summary
Add a game key listener to the given gamekey for a callback when the key is relea
addKeyListener(int keyCode, ActionListener listener)
Add a key listener to the given keycode for a callback when the key is released
addOrientationListener(ActionListener l)
This listener is invoked when device orientation changes on devices that support o
addShowListener(ActionListener l)
Dispatches a command via the standard form mechanism of firing a command eve
findNextFocusHorizontal(boolean right)
Returns the animation manager instance responsible for this form, this can be used
getBackCommand()
Indicates the command that is defined as the back command out of this form.
getClearCommand()
Indicates the command that is defined as the clear command in this form.
getCommand(int index)
A helper method to check the amount of commands within the form menu
getComponentForm()
1610
getComponentIndex(Component cmp)
Command
Default command is invoked when a user presses fire, this functionality works well
collide with elements such as navigation and combo boxes.
getDragRegionStatus(int x, int y)
int
TextArea
Component
Indicates if the section within the X/Y area is a "drag region" where we expect peop
case we can instantly start dragging making perceived performance faster.
getEditOnShow()
A text component that will receive focus and start editing immediately as the form i
getFocused()
Painter
Allows a developer that doesn't derive from the form to draw on top of the form reg
changes or animations.
getLayeredPane()
Container
Container
Layout
MenuBar
Style
This method returns the layered pane of the Form, the layered pane is laid on top o
created lazily upon calling this method the layer will be created.
getLayeredPane(Class c, boolean top)
Returns the layered pane for the class and if one doesn't exist a new one is create
getLayout()
String[]
String[]
Class[]
Object
This method is here to workaround an XMLVM array type bug where property type
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI bu
getScrollAnimationSpeed()
int
Button
int
int
String
Returns the button representing the softbutton, this allows modifying softbutton attr
programmatically rather than by using the command API.
getSoftButtonCount()
Returns the number of buttons on the menu bar for use with getSoftButton()
getTintColor()
Default color for the screen tint when a dialog or a menu is shown
getTitle()
Container
Label
Style
Method Summary
Deprecated.
this method was exposed to allow some hacks, you are advised not to use it. There
as command behavior (thru Display or the theme constants)
getTitleComponent()
1611
getToolbar()
This property allows us to define a an animation that will draw the transition for ent
getTransitionOutAnimator()
This property allows us to define a an animation that will draw the transition for exit
getUIManager()
This method should be used by the Component to retrieve the correct UIManager t
grabAnimationLock()
boolean
boolean
Deprecated.
this is effectively invalidated by the newer animation framework
hasMedia()
Used by the implementation to prevent flickering when flushing the double buffer
hideNotify()
protected void
protected void
This method is only invoked when the underlying canvas for the form is hidden this
based events and is generally usable for suspend/resume based behavior
initLaf(UIManager uim)
boolean
boolean
Enable the tensile drag to work even when a component doesn't have a scroll show
needs to be set to true)
isCyclicFocus()
boolean
Deprecated.
this method was replaced by getDragRegionStatus
isFocusScrolling()
boolean
Indicates whether lists and containers should scroll only via focus and thus "jump"
component as was the case in older versions of Codename One.
isFormBottomPaddingEditingMode()
boolean
boolean
boolean
boolean
boolean
void
void
void
protected void
Toggles the way the virtual keyboard behaves, enabling this mode shrinks the scre
possible when working with text fields that aren't in a scrollable container.
isMinimizeOnBack()
When set to true the physical back button will minimize the application
isScrollable()
If this Component is focused, the key pressed event will call this method
keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
keyRepeated(int keyCode)
If this Component is focused, the key repeat event will call this method.
longKeyPress(int keyCode)
If this Component is focused this method is invoked when the user presses and ho
longPointerPress(int x, int y)
void
protected void
If this Component is focused this method is invoked when the user presses and ho
Component
onShow()
Allows subclasses to bind functionality that occurs when a specific form or dialog a
onShowCompleted()
protected void
Allows subclasses to bind functionality that occurs when a specific form or dialog is
when the transition is totally complete (unlike onShow which is called on intent).
void
paint(Graphics g)
Method Summary
1612
This method paints the Component on the screen, it should be overriden by subcla
drawing or invoke the UI API's to let the PLAF perform the rendering.
void
protected String
void
void
void
void
void
void
void
paintBackground(Graphics g)
If this Component is focused, the pointer dragged event will call this method
pointerDragged(int x, int y)
If this Component is focused, the pointer dragged event will call this method
pointerHover(int[] x, int[] y)
Invoked for devices where the pointer can hover without actually clicking the displa
pointerHoverPressed(int[] x, int[] y)
Invoked for devices where the pointer can hover without actually clicking the displa
pointerHoverReleased(int[] x, int[] y)
Invoked for devices where the pointer can hover without actually clicking the displa
pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method
pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method
refreshTheme(boolean merge)
void
Makes sure the component is up to date with the current theme, ONLY INVOKE TH
CHANGED THE THEME!
registerAnimated(Animation cmp)
void
The given component is interested in animating its appearance and will start receiv
visible in the form allowing it to animate its appearance.
releaseAnimationLock()
void
void
void
void
void
Deprecated.
this is effectively invalidated by the newer animation framework
removeAll()
void
void
void
void
void
void
void
void
void
void
Method Summary
This listener is invoked when device orientation changes on devices that support o
removeShowListener(ActionListener l)
Remove SizeChangedListener
replace(Component current, Component next, Transition t)
This method replaces the current Component with the next Component.
replaceAndWait(Component current, Component next, Transition t)
This method replaces the current Component with the next Component.
scrollComponentToVisible(Component c)
Makes sure the component is visible in the scroll if this container is scrollable
1613
void
Enable the tensile drag to work even when a component doesn't have a scroll show
needs to be set to true)
setBackCommand(Command backCommand)
Indicates the command that is defined as the back command out of this form.
setBgImage(Image bgImage)
void
void
void
Deprecated.
Use the style directly
setClearCommand(Command clearCommand)
Indicates the command that is defined as the clear command in this form.
setCyclicFocus(boolean cyclicFocus)
void
void
void
Default command is invoked when a user presses fire, this functionality works well
collide with elements such as navigation and combo boxes.
setEditOnShow(TextArea editOnShow)
A text component that will receive focus and start editing immediately as the form i
setFocused(Component focused)
Sets the focused component and fires the appropriate events to make it so
setFocusScrolling(boolean focusScrolling)
void
Indicates whether lists and containers should scroll only via focus and thus "jump"
component as was the case in older versions of Codename One.
setFormBottomPaddingEditingMode(boolean b)
void
Toggles the way the virtual keyboard behaves, enabling this mode shrinks the scre
possible when working with text fields that aren't in a scrollable container.
setGlassPane(Painter glassPane)
void
void
void
void
void
void
String
void
void
void
void
Allows a developer that doesn't derive from the form to draw on top of the form reg
changes or animations.
setLayout(Layout layout)
Determine the cell renderer used to render menu elements for themeing the look o
setMenuTransitions(Transition transitionIn, Transition transitionOut)
Sets the menu transitions for showing/hiding the menu, can be null...
setMinimizeOnBack(boolean minimizeOnBack)
When set to true the physical back button will minimize the application
setPropertyValue(String name, Object value)
Sets a new value to the given property, returns an error message if failed and null
setRTL(boolean r)
void
void
void
void
void
Method Summary
Default color for the screen tint when a dialog or a menu is shown
setTitle(String title)
1614
Allows replacing the title with a different title component, thus allowing developers
objects.
void
setTitleStyle(Style s)
Deprecated.
this method doesn't take into consideration multiple styles
void
setToolbar(Toolbar toolbar)
void
Deprecated.
use setToolbar instead (lower case b)
void
setTransitionInAnimator(Transition transitionInAnimator)
void
This property allows us to define a an animation that will draw the transition for ent
setTransitionOutAnimator(Transition transitionOutAnimator)
void
This property allows us to define a an animation that will draw the transition for exit
setUIManager(UIManager uiManager)
Allows replacing the UIManager in a component hierarchy to update the look and f
hierarchy
void
setVisible(boolean visible)
void
protected
boolean
shouldSendPointerReleaseToOtherForm()
Indicates whether this form wants to receive pointerReleased events for touch eve
form
show()
void
Displays the current form on the screen, this version of the method is useful for "ba
reverses the direction of the transition.
void
showNotify()
protected void
protected void
This method is only invoked when the underlying canvas for the form is shown this
based events and is generally usable for suspend/resume based behavior
sizeChanged(int w, int h)
This method is only invoked when the underlying canvas for the form gets a size ch
1615
Field Detail
focusScrolling
protected boolean focusScrolling
Indicates whether lists and containers should scroll only via focus and thus "jump"
when moving to a larger component as was the case in older versions of Codename
One.
Constructor Detail
Form
public Form()
1616
Method Detail
getAnimationManager
public AnimationManager getAnimationManager()
Returns the animation manager instance responsible for this form, this can be used
to track/queue animations
Overrides:
getAnimationManager in class Component
Returns:
the animation manager
setFormBottomPaddingEditingMode
public void setFormBottomPaddingEditingMode(boolean b)
Toggles the way the virtual keyboard behaves, enabling this mode shrinks the screen
but makes editing possible when working with text fields that aren't in a scrollable
container.
Parameters:
b - true to enable false to disable
isFormBottomPaddingEditingMode
public boolean isFormBottomPaddingEditingMode()
Toggles the way the virtual keyboard behaves, enabling this mode shrinks the screen
but makes editing possible when working with text fields that aren't in a scrollable
container.
Returns:
true when this mode is enabled
isAlwaysTensile
public boolean isAlwaysTensile()
Enable the tensile drag to work even when a component doesn't have a scroll
showable (scrollable flag still needs to be set to true)
Overrides:
isAlwaysTensile in class Component
Returns:
the alwaysTensile
grabAnimationLock
public boolean grabAnimationLock()
Constructor Detail
1617
Enable the tensile drag to work even when a component doesn't have a scroll
showable (scrollable flag still needs to be set to true)
Overrides:
setAlwaysTensile in class Component
Parameters:
alwaysTensile - the alwaysTensile to set
getTitleArea
public Container getTitleArea()
Deprecated. this method was exposed to allow some hacks, you are advised not to
use it. There are some alternatives such as command behavior (thru Display or the
theme constants)
Title area manipulation might break with future changes to Codename One and might
damage themeing/functionality of the Codename One application in some platforms
Returns:
the container containing the title
getUIManager
public UIManager getUIManager()
Method Detail
1618
This listener is invoked when device orientation changes on devices that support
orientation change
Parameters:
l - listener
removeOrientationListener
public void removeOrientationListener(ActionListener l)
This listener is invoked when device orientation changes on devices that support
orientation change
Parameters:
l - the listener
addSizeChangedListener
public void addSizeChangedListener(ActionListener l)
Remove SizeChangedListener
Parameters:
l - the listener
hideNotify
protected void hideNotify()
This method is only invoked when the underlying canvas for the form is hidden this
method isn't called for form based events and is generally usable for suspend/resume
based behavior
showNotify
protected void showNotify()
This method is only invoked when the underlying canvas for the form is shown this
method isn't called for form based events and is generally usable for suspend/resume
based behavior
sizeChanged
protected void sizeChanged(int w,
int h)
This method is only invoked when the underlying canvas for the form gets a size
changed event. This method will trigger a relayout of the Form. This method will get
the callback only if this Form is the Current Form
Parameters:
w - the new width of the Form
h - the new height of the Form
setGlassPane
public void setGlassPane(Painter glassPane)
Allows a developer that doesn't derive from the form to draw on top of the form
regardless of underlying changes or animations. This is useful for watermarks or
special effects (such as tinting) it is also useful for generic drawing of validation errors
Method Detail
1619
Indicates if the section within the X/Y area is a "drag region" where we expect people
to drag or press in which case we can instantly start dragging making perceived
performance faster. This is invoked by the implementation code to optimize drag start
behavior
Overrides:
getDragRegionStatus in class Component
Parameters:
x - x location for the touch
y - y location for the touch
Returns:
one of the DRAG_REGION_* values
getGlassPane
public Painter getGlassPane()
Allows a developer that doesn't derive from the form to draw on top of the form
regardless of underlying changes or animations. This is useful for watermarks or
special effects (such as tinting) it is also useful for generic drawing of validation errors
etc... A glass pane is generally transparent or translucent and allows the the UI
bellow to be seen.
Returns:
the instance of the glass pane for this form
See Also:
PainterChain.installGlassPane(Form, com.codename1.ui.Painter)
setTitleStyle
public void setTitleStyle(Style s)
Allows modifying the title attributes beyond style (e.g. setting icon/alignment etc.)
Returns:
the component representing the title for the form
Method Detail
1620
Allows replacing the title with a different title component, thus allowing developers to
create more elaborate title objects.
Parameters:
title - new title component
setTitleComponent
public void setTitleComponent(Label title,
Transition t)
Allows replacing the title with a different title component, thus allowing developers to
create more elaborate title objects. This version of the method allows special effects
for title replacement such as transitions for title entering
Parameters:
title - new title component
t - transition for title replacement
addKeyListener
public void addKeyListener(int keyCode,
ActionListener listener)
Add a key listener to the given keycode for a callback when the key is released
Parameters:
keyCode - code on which to send the event
listener - listener to invoke when the key code released.
removeKeyListener
public void removeKeyListener(int keyCode,
ActionListener listener)
Add a game key listener to the given gamekey for a callback when the key is
released
Parameters:
keyCode - code on which to send the event
listener - listener to invoke when the key code released.
getSoftButtonCount
public int getSoftButtonCount()
Returns the number of buttons on the menu bar for use with getSoftButton()
Returns:
the number of softbuttons
getSoftButton
public Button getSoftButton(int offset)
Method Detail
1621
Default command is invoked when a user presses fire, this functionality works well in
some situations but might collide with elements such as navigation and combo boxes.
Use with caution.
Parameters:
defaultCommand - the command to treat as default
getDefaultCommand
public Command getDefaultCommand()
Default command is invoked when a user presses fire, this functionality works well in
some situations but might collide with elements such as navigation and combo boxes.
Use with caution.
Returns:
the command to treat as default
setClearCommand
public void setClearCommand(Command clearCommand)
Indicates the command that is defined as the clear command in this form. A clear
command can be used both to map to a "clear" hardware button if such a button
exists.
Parameters:
clearCommand - the command to treat as the clear Command
getClearCommand
public Command getClearCommand()
Indicates the command that is defined as the clear command in this form. A clear
command can be used both to map to a "clear" hardware button if such a button
exists.
Returns:
the command to treat as the clear Command
Method Detail
1622
Indicates the command that is defined as the back command out of this form. A back
command can be used both to map to a hardware button (e.g. on the Sony Ericsson
devices) and by elements such as transitions etc. to change the behavior based on
direction (e.g. slide to the left to enter screen and slide to the right to exit with back).
Parameters:
backCommand - the command to treat as the back Command
getBackCommand
public Command getBackCommand()
Indicates the command that is defined as the back command out of this form. A back
command can be used both to map to a hardware button (e.g. on the Sony Ericsson
devices) and by elements such as transitions etc. to change the behavior based on
direction (e.g. slide to the left to enter screen and slide to the right to exit with back).
Returns:
the command to treat as the back Command
getContentPane
public Container getContentPane()
This method returns the layered pane of the Form, the layered pane is laid on top of
the content pane and is created lazily upon calling this method the layer will be
created. This is equivalent to getLayeredPane(null, false).
Returns:
the LayeredPane
getLayeredPane
public Container getLayeredPane(Class c,
boolean top)
Returns the layered pane for the class and if one doesn't exist a new one is created
dynamically and returned
Parameters:
c - the class with which this layered pane is associated, null for the global
layered pane which is always on the bottom
top - if created this indicates whether the layered pane should be added on
top or bottom
Returns:
the layered pane instance
removeAll
public void removeAll()
Method Detail
1623
Method Detail
1624
This method replaces the current Component with the next Component. Current
Component must be contained in this Container. This method return immediately.
Overrides:
replace in class Container
Parameters:
current - a Component to remove from the Container
next - a Component that replaces the current Component
t - a Transition between the add and removal of the Components a Transition
can be null
replaceAndWait
public void replaceAndWait(Component current,
Component next,
Transition t)
This method replaces the current Component with the next Component. Current
Component must be contained in this Container. This method returns when transition
has finished.
Overrides:
replaceAndWait in class Container
Parameters:
current - a Component to remove from the Container
next - a Component that replaces the current Component
t - a Transition between the add and removal of the Components a Transition
can be null
removeComponent
public void removeComponent(Component cmp)
Used by the implementation to prevent flickering when flushing the double buffer
Returns:
true if the form has media components within it
registerAnimated
public void registerAnimated(Animation cmp)
The given component is interested in animating its appearance and will start
receiving callbacks when it is visible in the form allowing it to animate its appearance.
This method would not register a compnent instance more than once
Parameters:
cmp - component that would be animated
deregisterAnimated
public void deregisterAnimated(Animation cmp)
Method Detail
1625
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Component
Returns:
true if a repaint is desired or false if no repaint is necessary
refreshTheme
public void refreshTheme(boolean merge)
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Container
Parameters:
merge - indicates if the current styles should be merged with the new styles
paintBackground
public void paintBackground(Graphics g)
This property allows us to define a an animation that will draw the transition for
entering this form. A transition is an animation that would occur when switching from
one form to another.
Returns:
the Form in transition
setTransitionInAnimator
public void setTransitionInAnimator(Transition transitionInAnimator)
This property allows us to define a an animation that will draw the transition for
entering this form. A transition is an animation that would occur when switching from
one form to another.
Parameters:
transitionInAnimator - the Form in transition
getTransitionOutAnimator
public Transition getTransitionOutAnimator()
This property allows us to define a an animation that will draw the transition for exiting
this form. A transition is an animation that would occur when switching from one form
to another.
Returns:
the Form out transition
setTransitionOutAnimator
public void setTransitionOutAnimator(Transition transitionOutAnimator)
This property allows us to define a an animation that will draw the transition for exiting
this form. A transition is an animation that would occur when switching from one form
to another.
Parameters:
transitionOutAnimator - the Form out transition
Method Detail
1626
Invoked to allow subclasses of form to handle a command from one point rather than
implementing many command instances. All commands selected on the form will
trigger this method implicitly.
Parameters:
cmd - the form commmand object
dispatchCommand
public void dispatchCommand(Command cmd,
ActionEvent ev)
Dispatches a command via the standard form mechanism of firing a command event
Parameters:
cmd - The command to dispatch
ev - the event to dispatch
show
public void show()
Displays the current form on the screen, this version of the method is useful for
"back" navigation since it reverses the direction of the transition.
setSmoothScrolling
public void setSmoothScrolling(boolean smoothScrolling)
Method Detail
1627
Allows subclasses to bind functionality that occurs when a specific form or dialog
appears on the screen
onShowCompleted
protected void onShowCompleted()
Allows subclasses to bind functionality that occurs when a specific form or dialog is
"really" showing hence when the transition is totally complete (unlike onShow which is
called on intent). The necessity for this is for special cases like media that might
cause artifacts if played during a transition.
getComponentForm
public final Form getComponentForm()
Returns the Component Form or null if this Component is not added yet to a form
Overrides:
getComponentForm in class Component
Returns:
the Component Form
setFocused
public void setFocused(Component focused)
Sets the focused component and fires the appropriate events to make it so
Parameters:
focused - the newly focused component or null for no focus
getFocused
public Component getFocused()
If this Component is focused this method is invoked when the user presses and holds
the key
Overrides:
longKeyPress in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
Method Detail
1628
If this Component is focused this method is invoked when the user presses and holds
the pointer on the Component
Overrides:
longPointerPress in class Component
shouldSendPointerReleaseToOtherForm
protected boolean shouldSendPointerReleaseToOtherForm()
Indicates whether this form wants to receive pointerReleased events for touch events
that started in a different form
Returns:
false by default
keyPressed
public void keyPressed(int keyCode)
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class Container
Parameters:
keyCode - the key code value to indicate a physical key.
getLayout
public Layout getLayout()
When set to true the physical back button will minimize the application
Returns:
the minimizeOnBack
setMinimizeOnBack
public void setMinimizeOnBack(boolean minimizeOnBack)
When set to true the physical back button will minimize the application
Parameters:
minimizeOnBack - the minimizeOnBack to set
keyReleased
public void keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Container
Parameters:
keyCode - the key code value to indicate a physical key.
keyRepeated
public void keyRepeated(int keyCode)
If this Component is focused, the key repeat event will call this method.
Overrides:
keyRepeated in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
Method Detail
1629
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Container
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerDragged
public void pointerDragged(int x,
int y)
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerDragged
public void pointerDragged(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHoverReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerHoverPressed
public void pointerHoverPressed(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHoverPressed in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerHover
public void pointerHover(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHover in class Container
Parameters:
Method Detail
1630
Returns true if there is only one focusable member in this form. This is useful so
setHandlesInput would always be true for this case.
Returns:
true if there is one focusable component in this form, false for 0 or more
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
setScrollableY
public void setScrollableY(boolean scrollableY)
Adds a command to the menu bar softkeys or into the menu dialog, this version of
add allows us to place a command in an arbitrary location. This allows us to force a
command into the softkeys when order of command addition can't be changed.
Parameters:
cmd - the Form command to be added
offset - position in which the command is added
getCommandCount
public int getCommandCount()
A helper method to check the amount of commands within the form menu
Returns:
Method Detail
1631
Adds a command to the menu bar softkeys. The Commands are placed in the order
they are added. If the Form has 1 Command it will be placed on the right. If the Form
has 2 Commands the first one that was added will be placed on the right and the
second one will be placed on the left. If the Form has more then 2 Commands the
first one will stay on the left and a Menu will be added with all the remain Commands.
Parameters:
cmd - the Form command to be added
removeCommand
public void removeCommand(Command cmd)
Makes sure the component is visible in the scroll if this container is scrollable
Overrides:
scrollComponentToVisible in class Container
Method Detail
1632
Determine the cell renderer used to render menu elements for themeing the look of
the menu options
Parameters:
menuCellRenderer - the menu cell renderer
removeAllCommands
public void removeAllCommands()
Method Detail
1633
Default color for the screen tint when a dialog or a menu is shown
Returns:
the tint color when a dialog or a menu is shown
setTintColor
public void setTintColor(int tintColor)
Default color for the screen tint when a dialog or a menu is shown
Parameters:
tintColor - the tint color when a dialog or a menu is shown
setMenuTransitions
public void setMenuTransitions(Transition transitionIn,
Transition transitionOut)
Sets the menu transitions for showing/hiding the menu, can be null...
Parameters:
transitionIn - the transition that will play when the menu appears
transitionOut - the transition that will play when the menu is folded
paramString
protected String paramString()
Returns a string representing the state of this component. This method is intended to
be used only for debugging purposes, and the content and format of the returned
string may vary between implementations. The returned string may be empty but may
not be null.
Overrides:
paramString in class Container
Returns:
a string representation of this component's state
getMenuBar
public MenuBar getMenuBar()
Method Detail
1634
Indicates whether lists and containers should scroll only via focus and thus "jump"
when moving to a larger component as was the case in older versions of Codename
One.
Returns:
the value of focusScrolling
setFocusScrolling
public void setFocusScrolling(boolean focusScrolling)
Indicates whether lists and containers should scroll only via focus and thus "jump"
when moving to a larger component as was the case in older versions of Codename
One.
Parameters:
focusScrolling - the new value for focus scrolling
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
Method Detail
1635
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
getEditOnShow
public TextArea getEditOnShow()
A text component that will receive focus and start editing immediately as the form is
shown
Returns:
the component instance
setEditOnShow
public void setEditOnShow(TextArea editOnShow)
A text component that will receive focus and start editing immediately as the form is
shown
Parameters:
editOnShow - text component to edit when the form is shown
Method Detail
1636
Class FontImage
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.FontImage
public class
extends Image
Field Summary
Modifier and
Type
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
MATERIAL_ADD_A_PHOTO
Class FontImage
1637
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_AIRPLANEMODE_INACTIVE
1638
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_ARROW_UPWARD
1639
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_BATTERY_ALERT
1640
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_BORDER_ALL
1641
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_BRIGHTNESS_HIGH
1642
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_CAMERA_ALT
1643
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_CHECK_BOX_OUTLINE_BLANK
1644
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_COLLECTIONS
1645
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_CREDIT_CARD
1646
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_DESKTOP_WINDOWS
1647
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_DNS
1648
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_ERROR_OUTLINE
1649
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_FAST_REWIND
1650
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_FILTER_9
1651
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_FLIGHT
1652
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_FORMAT_INDENT_DECREASE
1653
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_FULLSCREEN
1654
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_GROUP_ADD
1655
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_HOURGLASS_EMPTY
1656
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_INSERT_PHOTO
1657
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_LAPTOP
1658
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_LIVE_HELP
1659
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_LOCAL_OFFER
1660
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_LOOKS_3
1661
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_MIC_OFF
1662
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_NATURE
1663
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_NOTIFICATIONS_OFF
1664
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_PAUSE_CIRCLE_OUTLINE
1665
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_PHONE_ANDROID
1666
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_PHOTO_SIZE_SELECT_LARGE
1667
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_POWER
1668
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_REDEEM
1669
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_RESTORE
1670
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_SCREEN_SHARE
1671
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_SETTINGS_PHONE
1672
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_SIM_CARD
1673
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_SPELLCHECK
1674
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_SUBSCRIPTIONS
1675
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_TAG_FACES
1676
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_TOLL
1677
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_USB
1678
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_VIEW_QUILT
1679
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Field Summary
static char
static char
MATERIAL_WB_INCANDESCENT
1680
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
static char
Method Summary
Modifier and
Type
Method Summary
1681
animate()
static
FontImage
static
FontImage
static
FontImage
static
FontImage
void
Does nothing
drawImage(Graphics g, Object nativeGraphics, int x, int y)
protected void
protected void
static int
static float
Default factor for image size, icons without a given size are sized as
defaultSize X default font height.
getFont()
Font
Graphics
int
Useful method to reuse the Font object when creating multiple image
objects
getGraphics()
String
The name of the image is set for some images mostly to ease the
debugging of Codename One application
getMaterialDesignFont()
static Font
int
int
boolean
boolean
The material design icon font allows creating icons based on the material
design icon catalog
getPadding()
boolean
Image
static void
New label optimizations don't invoke drawImage and instead just pass the
native image directly to the underlying renderer.
rotate(int degrees)
static void
Default factor for image size, icons without a given size are sized as
defaultSize X default font height.
setMaterialIcon(Label l, char icon)
static void
Applies a material design icon (one of the MATERIAL_* icons above) to the
given label using the styling of the label
static void
Method Summary
1682
Applies a material design icon (one of the MATERIAL_* icons above) to the
given component using the styling of the label
setPadding(int padding)
void
EncodedImage
toEncodedImage()
Image
Field Detail
MATERIAL_3D_ROTATION
public static final char MATERIAL_3D_ROTATION
1683
Field Detail
1684
Field Detail
1685
Field Detail
1686
Field Detail
1687
Field Detail
1688
Field Detail
1689
Field Detail
1690
Field Detail
1691
Field Detail
1692
Field Detail
1693
Field Detail
1694
Field Detail
1695
Field Detail
1696
Field Detail
1697
Field Detail
1698
Field Detail
1699
Field Detail
1700
Field Detail
1701
Field Detail
1702
Field Detail
1703
Field Detail
1704
Field Detail
1705
Field Detail
1706
Field Detail
1707
Field Detail
1708
Field Detail
1709
Field Detail
1710
Field Detail
1711
Field Detail
1712
Field Detail
1713
Field Detail
1714
Field Detail
1715
Field Detail
1716
Field Detail
1717
Field Detail
1718
Field Detail
1719
Field Detail
1720
Field Detail
1721
Field Detail
1722
Field Detail
1723
Field Detail
1724
Field Detail
1725
Field Detail
1726
Field Detail
1727
Field Detail
1728
Field Detail
1729
Field Detail
1730
Field Detail
1731
Field Detail
1732
Field Detail
1733
Field Detail
1734
Field Detail
1735
Field Detail
1736
Field Detail
1737
Field Detail
1738
Field Detail
1739
Field Detail
1740
Field Detail
1741
Field Detail
1742
Field Detail
1743
Field Detail
1744
Field Detail
1745
Field Detail
1746
Field Detail
1747
Field Detail
1748
Field Detail
1749
Field Detail
1750
Field Detail
1751
Field Detail
1752
Field Detail
1753
Field Detail
1754
Field Detail
1755
Field Detail
1756
Field Detail
1757
Field Detail
1758
Field Detail
1759
Field Detail
1760
Field Detail
1761
Field Detail
1762
Field Detail
1763
Field Detail
1764
Field Detail
1765
Field Detail
1766
Field Detail
1767
Field Detail
1768
Field Detail
1769
Field Detail
1770
Field Detail
1771
Field Detail
1772
Field Detail
1773
Field Detail
1774
Field Detail
1775
Field Detail
1776
Field Detail
1777
Field Detail
1778
Field Detail
1779
Field Detail
1780
Field Detail
1781
Field Detail
1782
Field Detail
1783
Field Detail
1784
Field Detail
1785
Field Detail
1786
Field Detail
1787
Field Detail
1788
Field Detail
1789
Field Detail
1790
Field Detail
1791
Field Detail
1792
Field Detail
1793
Method Detail
getMaterialDesignFont
public static Font getMaterialDesignFont()
The material design icon font allows creating icons based on the material design icon
catalog
Returns:
Field Detail
1794
Applies a material design icon (one of the MATERIAL_* icons above) to the given
label using the styling of the label
Parameters:
l - a label or subclass (e.g. Button etc.)
icon - one of the MATERIAL_* icons
setMaterialIcon
public static void setMaterialIcon(MultiButton l,
char icon)
Applies a material design icon (one of the MATERIAL_* icons above) to the given
component using the styling of the label
Parameters:
l - a multibutton
icon - one of the MATERIAL_* icons
setMaterialIcon
public static void setMaterialIcon(SpanButton l,
char icon)
Applies a material design icon (one of the MATERIAL_* icons above) to the given
component using the styling of the label
Parameters:
l - a SpanButton
icon - one of the MATERIAL_* icons
getDefaultSize
public static float getDefaultSize()
Default factor for image size, icons without a given size are sized as defaultSize X
default font height.
Returns:
the defaultSize
setDefaultSize
public static void setDefaultSize(float aDefaultSize)
Default factor for image size, icons without a given size are sized as defaultSize X
default font height.
Parameters:
aDefaultSize - the defaultSize to set
getDefaultPadding
public static int getDefaultPadding()
Method Detail
1795
Method Detail
1796
Callback invoked internally by Codename One to draw the image/frame onto the
display. Image subclasses can override this method to perform drawing of custom
image types.
Overrides:
drawImage in class Image
Parameters:
g - the graphics object
nativeGraphics - the underlying native graphics which might be essential for
some image types
x - the x coordinate
y - the y coordinate
drawImage
protected void drawImage(Graphics g,
Object nativeGraphics,
int x,
int y,
int w,
int h)
Callback invoked internally by Codename One to draw the image/frame onto the
display. Image subclasses can override this method to perform drawing of custom
image types.
Overrides:
drawImage in class Image
Parameters:
g - the graphics object
nativeGraphics - the underlying native graphics which might be essential for
some image types
x - the x coordinate
y - the y coordinate
w - the width to occupy
h - the height to occupy
getPadding
public int getPadding()
Useful method to reuse the Font object when creating multiple image objects
Method Detail
1797
Overrides:
animate
in class Image
isOpaque
public boolean isOpaque()
The name of the image is set for some images mostly to ease the debugging of
Codename One application
Overrides:
getImageName in class Image
Returns:
the imageName
dispose
public void dispose()
Does nothing
Overrides:
dispose
in class Image
rotate
public Image rotate(int degrees)
Returns an instance of this image rotated by the given number of degrees. By default
90 degree angle divisions are supported, anything else is implementation dependent.
This method assumes a square image. Notice that it is inefficient in the current
implementation to rotate to non-square angles,
E.g. rotating an image to 45, 90 and 135 degrees is inefficient. Use rotatate to 45, 90
and then rotate the 45 to another 90 degrees to achieve the same effect with less
memory.
Overrides:
rotate
in class Image
Parameters:
- A degree in right angle must be larger than 0 and up to 359
degrees
Returns:
new image instance with the closest possible rotation
degrees
Method Detail
1798
New label optimizations don't invoke drawImage and instead just pass the native
image directly to the underlying renderer. This is problematic for some image types
specifically timeline & FontImage and this method allows these classes to indicate
that they need that legacy behavior of calling drawImage.
Overrides:
requiresDrawImage in class Image
Returns:
true if a drawImage call is a required
Method Detail
1799
Class Font
java.lang.Object
com.codename1.ui.Font
public class
extends Object
Field Summary
Modifier and Type
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
Class Font
1800
Method Summary
Modifier
and Type
void
int
int
Deprecated.
bitmap font functionality is now deprecated
charsWidth(char[] ch, int offset, int length)
static void
Deprecated.
bitmap font functionality is now deprecated
create(String lookup)
static Font
static Font
static Font
static Font
Creates a new font instance based on the platform specific string name of the
font.
createBitmapFont(Image bitmap, int[] cutOffsets, int[] charWidth,
String charsets)
Deprecated.
bitmap font functionality is now deprecated
createBitmapFont(String name, Image bitmap, int[] cutOffsets,
int[] charWidth, String charsets)
Deprecated.
bitmap font functionality is now deprecated
createSystemFont(int face, int style, int size)
static Font
Creates a true type font with the given name/filename (font name might be
different from the file name and is required by some devices e.g.
derive(float sizePixels, int weight)
Font
boolean
int
Creates a font based on this truetype font with the given pixel, WARNING!
This method will only work in the case of truetype fonts!
Important some platforms e.g.
equals(Object o)
The ascent is the amount by which the character ascends above the baseline.
getBitmapFont(String fontName)
static Font
String
static Font
Deprecated.
bitmap font functionality is now deprecated
getCharset()
int
int
int
Object
The descent is the amount by which the character descends below the
baseline
getFace()
Return Optional operation returning the font face for system fonts
getHeight()
float
int
Method Summary
Returns the size with which the font object was created in case of truetype
fonts/derived fonts.
getSize()
Return Optional operation returning the font size for system fonts
1801
getStyle()
int
Return Optional operation returning the font style for system fonts
static
boolean
static
boolean
static
boolean
static
boolean
boolean
isBitmapFontEnabled()
Indicates whether bitmap fonts should be enabled when loading or the fallback
system font should be used instead.
isCreationByStringSupported()
Returns true if the underlying platform allows creating a font based on a user
submitted string.
isNativeFontSchemeSupported()
Returns true if the underlying platform supports loading truetype fonts from a
file.
isTTFNativeFont()
Indicates if this is a TTF native font that can be derived and manipulated.
setBitmapFontEnabled(boolean enabled)
static void
static void
int
int
Return the width of the given string subset in this font instance
Field Detail
FACE_MONOSPACE
public static final int FACE_MONOSPACE
1802
Method Detail
getBitmapFont
public static Font getBitmapFont(String fontName)
clearBitmapCache
public static void clearBitmapCache()
Field Detail
1803
Returns true if the underlying platform supports loading truetype fonts from a file.
Returns:
true if the underlying platform supports loading truetype fonts from a file
isCreationByStringSupported
public static boolean isCreationByStringSupported()
Returns true if the underlying platform allows creating a font based on a user
submitted string.
Returns:
true if the underlying platform allows creating a font based on a user
submitted string
isNativeFontSchemeSupported
public static boolean isNativeFontSchemeSupported()
Indicates whether the implementation supports loading a font "natively" to handle one
of the common native prefixes
Returns:
true if the "native:" prefix is supported by loadTrueTypeFont
createTrueTypeFont
public static Font createTrueTypeFont(String fontName,
String fileName)
Creates a true type font with the given name/filename (font name might be different
from the file name and is required by some devices e.g. iOS). The font file must
reside in the src root of the project in order to be detectable. The file name should
contain no slashes or any such value.
Important some platforms e.g. iOS don't support changing the weight of the font and
require you to use the font name matching the weight, so the weight argument to
derive will be ignored!
This system also supports a special "native:" prefix that uses system native fonts e.g.
HelveticaNeue on iOS and Roboto on Android. It supports the following types:
native:MainThin, native:MainLight, native:MainRegular, native:MainBold,
native:MainBlack, native:ItalicThin, native:ItalicLight, native:ItalicRegular,
native:ItalicBold, native:ItalicBlack. Important due to copyright restrictions we cannot
distribute Helvetica and thus can't simulate it. In the simulator you will see Roboto
and not the device font unless you are running on a Mac
Parameters:
fontName - the name of the font
fileName - the file name of the font as it appears in the src directory of the
project, it MUST end with the .ttf extension!
Returns:
the font object created or null if true type fonts aren't supported on this
platform
derive
public Font derive(float sizePixels,
int weight)
Creates a font based on this truetype font with the given pixel, WARNING! This
method will only work in the case of truetype fonts!
Important some platforms e.g. iOS don't support changing the weight of the font and
require you to use the font name matching the weight, so the weight argument to
derive will be ignored!
Parameters:
sizePixels - the size of the font in pixels
weight - PLAIN, BOLD or ITALIC weight based on the constants in this class
Returns:
scaled font instance
Method Detail
1804
Indicates if this is a TTF native font that can be derived and manipulated. This is true
for a font loaded from file (TTF) or using the native: font name
Returns:
true if this is a native font
create
public static Font create(String lookup)
Creates a new font instance based on the platform specific string name of the font.
This method isn't supported on some platforms.
Parameters:
lookup - a set of platform specific names delimited by commas, the first
succefully loaded font will be used
Returns:
newly created font or null if creation failed
addContrast
public void addContrast(byte value)
Method Detail
1805
the font
- The width of the character when drawing... this should not be
confused with the number of cutOffset[o + 1] - cutOffset[o]. They are
completely different since a character can be "wider" and "seep" into the next
region. This is especially true with italic characters all of which "lean" outside
of their bounds.
charsets - the set of characters in the font
Returns:
a font object to draw bitmap fonts
createSystemFont
charWidth
Return the width of the given string subset in this font instance
Parameters:
str - the given string
offset - the string offset
len - the len od string
Returns:
the width of the given string subset in this font instance
stringWidth
public int stringWidth(String str)
Method Detail
1806
Return Optional operation returning the font face for system fonts
Returns:
Optional operation returning the font face for system fonts
getSize
public int getSize()
Return Optional operation returning the font size for system fonts
Returns:
Optional operation returning the font size for system fonts
getStyle
public int getStyle()
Return Optional operation returning the font style for system fonts
Returns:
Optional operation returning the font style for system fonts
getCharset
public String getCharset()
Returns a string containing all the characters supported by this font. Will return null
for system fonts.
Returns:
String containing the characters supported by a bitmap font or null otherwise.
setBitmapFontEnabled
public static void setBitmapFontEnabled(boolean enabled)
Indicates whether bitmap fonts should be enabled by default when loading or the
fallback system font should be used instead. This allows easy toggling of font loading.
Parameters:
enabled - true to enable bitmap font loading (if they exist in the resource)
isBitmapFontEnabled
public static boolean isBitmapFontEnabled()
Indicates whether bitmap fonts should be enabled when loading or the fallback
system font should be used instead. This allows easy toggling of font loading.
Returns:
Method Detail
1807
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Object
getAscent
public int getAscent()
The ascent is the amount by which the character ascends above the baseline.
Returns:
the ascent in pixels
getDescent
public int getDescent()
The descent is the amount by which the character descends below the baseline
Returns:
the descent in pixels
getPixelSize
public float getPixelSize()
Returns the size with which the font object was created in case of truetype
fonts/derived fonts. This is useful since a platform might change things slightly based
on platform constraints but this value should be 100% consistent
Returns:
the size requested in the derive method
Method Detail
1808
Class EncodedImage
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.EncodedImage
Direct Known Subclasses:
FileEncodedImage, FileEncodedImageAsync, ReplaceableImage, StorageImage,
StorageImageAsync, URLImage
public class
extends Image
An image that only keeps the binary data of the source file used to load it in permanent memory. This
allows the bitmap to get collected while the binary data remains, a weak reference is used for
caching.
Constructor Summary
Modifier
protected
Allows subclasses to create more advanced variations of this class that lazily
store the data in an arbitrary location.
Method Summary
Modifier and
Type
void
static
EncodedImage
static
EncodedImage
static
EncodedImage
static
EncodedImage
Async lock is the equivalent of a lock operation, however it uses the given
image as the hard cache and performs the actual image loading
asynchronously.
create(byte[] data)
Creates an image from the given byte array with the variables set
appropriately.
create(InputStream i)
Creates an image from the input stream, this version of the method is
somewhat faster than the version that doesn't accept size
static
EncodedImage
create(String i)
static
EncodedImage
static Image
static
EncodedImage
Class EncodedImage
Deprecated.
this method is meant for internal use only, it would be very expensive to
use this method for real applications. Its here for simulators and
development purposes where screen DPI/resolution can vary significantly
in runtime (something that just doesn't happen on devices).
1809
protected void
Graphics
int
Object
byte[]
protected
Image
int
boolean
boolean
boolean
Returns the byte array data backing the image allowing the image to be
stored and discarded completely from RAM.
getInternal()
Returns the actual image represented by the encoded image, this image
will be cached in a weak/soft reference internally.
getWidth()
void
Image
Image
protected void
Image
void
Scale the image to the given width and height, this is a fast algorithm that
preserves translucent information
scaled(int width, int height)
Image
EncodedImage
Returns a scaled version of this image image using the given width and
height, this is a fast algorithm that preserves translucent information.
scaledEncoded(int width, int height)
Image
Scales the image to the given height while updating the width based on the
aspect ratio of the height
scaledSmallerRatio(int width, int height)
Image
Scales the image while maintaining the aspect ratio to the smaller size
image
Image
scaledWidth(int width)
Method Summary
1810
Image
void
void
Constructor Detail
EncodedImage
protected EncodedImage(int width,
int height)
Allows subclasses to create more advanced variations of this class that lazily store
the data in an arbitrary location.
Parameters:
width - -1 if unknown ideally the width/height should be known in advance
height - -1 if unknown ideally the width/height should be known in advance
Method Detail
resetCache
protected void resetCache()
A subclass might choose to load asynchroniously and reset the cache when the
image is ready.
createMulti
public static EncodedImage createMulti(int[] dpis,
byte[][] data)
Deprecated. this method is meant for internal use only, it would be very expensive to
use this method for real applications. Its here for simulators and development
purposes where screen DPI/resolution can vary significantly in runtime (something
that just doesn't happen on devices).
Creates an encoded image that acts as a multi-image, DO NOT USE THIS
METHOD. Its for internal use to improve the user experience of the simulator
Parameters:
dpis - device DPI's
data - the data matching each multi-image DPI
1811
Tries to create an encoded image from RGB which is more efficient, however if this
fails it falls back to regular RGB image. This method is slower than creating an RGB
image (not to be confused with the RGBImage class which is something ENTIRELY
different!).
Parameters:
argb - an argb array
width - the width for the image
height - the height for the image
jpeg - uses jpeg format internally which is opaque and could be faster/smaller
Returns:
an image which we hope is an encoded image
getImageData
public byte[] getImageData()
Returns the byte array data backing the image allowing the image to be stored and
discarded completely from RAM.
Returns:
byte array used to create the image, e.g. encoded PNG, JPEG etc.
create
public static EncodedImage create(byte[] data)
Creates an image from the given byte array with the variables set appropriately. This
saves LWUIT allot of resources since it doesn't need to actually traverse the pixels of
an image to find out details about it.
Parameters:
data - the data of the image
width - the width of the image
height - the height of the image
opacity - true for an opaque image
Returns:
newly created encoded image
Method Detail
1812
Creates an image from the input stream, this version of the method is somewhat
faster than the version that doesn't accept size
Parameters:
i - the input stream
size - the size of the stream
Returns:
newly created encoded image
Throws:
IOException - if thrown by the input stream
getInternal
protected Image getInternal()
Returns the actual image represented by the encoded image, this image will be
cached in a weak/soft reference internally. This method is useful to detect when the
system actually created an image instance. You shouldn't invoke this method
manually!
Returns:
drawable image instance
isLocked
public boolean isLocked()
Async lock is the equivalent of a lock operation, however it uses the given image as
the hard cache and performs the actual image loading asynchronously. On
completion this method will invoke repaint on the main form if applicable.
Overrides:
asyncLock in class Image
Parameters:
internal - the image to show while the actual image loads.
Method Detail
1813
This callback indicates that a component pointing at this image is initialized, this
allows an image to make performance sensitive considerations e.g. an encoded
image might choose to cache itself in RAM. This method may be invoked multiple
times.
Overrides:
lock in class Image
unlock
public void unlock()
This callback indicates that a component pointing at this image is now deinitilized
This method may be invoked multiple times.
Overrides:
unlock in class Image
create
public static EncodedImage create(String i)
throws IOException
Extracts a subimage from the given image allowing us to breakdown a single large
image into multiple smaller images in RAM, this actually creates a standalone version
of the image for use.
Overrides:
subImage in class Image
Parameters:
x - the x offset from the image
y - the y offset from the image
width - the width of internal images
height - the height of internal images
processAlpha - whether alpha should be processed as well as part of the
cutting
Returns:
An array of all the possible images that can be created from the source
rotate
public Image rotate(int degrees)
Returns an instance of this image rotated by the given number of degrees. By default
90 degree angle divisions are supported, anything else is implementation dependent.
This method assumes a square image. Notice that it is inefficient in the current
implementation to rotate to non-square angles,
E.g. rotating an image to 45, 90 and 135 degrees is inefficient. Use rotatate to 45, 90
and then rotate the 45 to another 90 degrees to achieve the same effect with less
memory.
Overrides:
rotate
Method Detail
in class Image
1814
Creates a new image instance with the alpha channel of opaque/translucent pixels
within the image using the new alpha value. Transparent (alpha == 0) pixels remain
transparent. All other pixels will have the new alpha value.
Overrides:
modifyAlpha in class Image
Parameters:
alpha - New value for the entire alpha channel
Returns:
Translucent/Opaque image based on the alpha value and the pixels of this
image
modifyAlpha
public Image modifyAlpha(byte alpha,
int removeColor)
Creates a new image instance with the alpha channel of opaque/translucent pixels
within the image using the new alpha value. Transparent (alpha == 0) pixels remain
transparent. All other pixels will have the new alpha value.
Overrides:
modifyAlpha in class Image
Parameters:
alpha - New value for the entire alpha channel
removeColor - pixels matching this color are made transparent (alpha channel
ignored)
Returns:
Translucent/Opaque image based on the alpha value and the pixels of this
image
getGraphics
public Graphics getGraphics()
Method Detail
1815
Callback invoked internally by Codename One to draw the image/frame onto the
display. Image subclasses can override this method to perform drawing of custom
image types.
Overrides:
drawImage in class Image
Parameters:
g - the graphics object
nativeGraphics - the underlying native graphics which might be essential for
some image types
x - the x coordinate
y - the y coordinate
drawImage
protected void drawImage(Graphics g,
Object nativeGraphics,
int x,
int y,
int w,
int h)
Callback invoked internally by Codename One to draw the image/frame onto the
display. Image subclasses can override this method to perform drawing of custom
image types.
Overrides:
drawImage in class Image
Parameters:
g - the graphics object
nativeGraphics - the underlying native graphics which might be essential for
some image types
x - the x coordinate
y - the y coordinate
w - the width to occupy
h - the height to occupy
toRGB
public void toRGB(RGBImage image,
int destX,
int destY,
int x,
int y,
int width,
int height)
Scales the image to the given width while updating the height based on the aspect
ratio of the width
Overrides:
scaledWidth in class Image
Method Detail
1816
Scales the image to the given height while updating the width based on the aspect
ratio of the height
Overrides:
scaledHeight in class Image
Parameters:
height - the given new image height
Returns:
the newly created image
scaledSmallerRatio
public Image scaledSmallerRatio(int width,
int height)
Scales the image while maintaining the aspect ratio to the smaller size image
Overrides:
scaledSmallerRatio in class Image
Parameters:
width - the given new image width
height - the given new image height
Returns:
the newly created image
scaledEncoded
public EncodedImage scaledEncoded(int width,
int height)
Returns a scaled version of this image image using the given width and height, this is
a fast algorithm that preserves translucent information. The method accepts -1 to
preserve aspect ratio in the given axis.
Overrides:
scaled in class Image
Parameters:
width - width for the scaling
height - height of the scaled image
Returns:
new image instance scaled to the given height and width
scale
public void scale(int width,
int height)
Scale the image to the given width and height, this is a fast algorithm that preserves
translucent information
Overrides:
scale in class Image
Parameters:
Method Detail
1817
image
isAnimation
public boolean isAnimation()
Method Detail
1818
Class Display
java.lang.Object
com.codename1.ui.Display
Central class for the API that manages rendering/events and is used to place top level components
(Form) on the "display".
This class handles the main thread for the toolkit referenced here on as the EDT (Event Dispatch
Thread) similar to the Swing EDT. This thread encapsulates the platform specific event delivery and
painting semantics and enables threading features such as animations etc...
The EDT should not be blocked since paint operations and events would also be blocked in much the
same way as they would be in other platforms. In order to serialize calls back into the EDT use the
methods callSerially(java.lang.Runnable) & callSeriallyAndWait(java.lang.Runnable).
Notice that all Codename One calls occur on the EDT (events, painting, animations etc...), Codename
One should normally be manipulated on the EDT as well (hence the
callSerially(java.lang.Runnable) & callSeriallyAndWait(java.lang.Runnable) methods).
Theoretically it should be possible to manipulate some Codename One features from other threads
but this can't be guaranteed to work for all use cases.
Field Summary
Modifier
and Type
static int
static int
Identical to the bar behavior, places the back command within the title bar of the
form/dialg
COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_RIGHT
static int
Places all commands on the right side of the title bar with a uniform size grid
layout
COMMAND_BEHAVIOR_DEFAULT
static int
Indicates that the Codename One implementation should decide internally the
command behavior most appropriate for this platform.
COMMAND_BEHAVIOR_ICS
static int
static int
static int
Commands are placed in the same was as they are in the ice cream sandwich
Android OS update where the back button has a theme icon the application icon
appears next to the
COMMAND_BEHAVIOR_NATIVE
Indicates that commands should try to add themselves to the native menus
COMMAND_BEHAVIOR_SIDE_NAVIGATION
static int
Indicates the classic Codename One command behavior where the commands
are placed in a list within a dialog.
COMMAND_BEHAVIOR_TOUCH_MENU
static int
Indicates the touch menu dialog rendered by Codename One where commands
are placed into a scrollable dialog
Class Display
1819
DENSITY_4K
4K level density
DENSITY_560
HD Up To 1920x1080
DENSITY_HIGH
Hi Density Up To 480x854
DENSITY_LOW
Used by openGallery
GALLERY_IMAGE
Used by openGallery
GALLERY_VIDEO
Used by openGallery
GAME_DOWN
Full QWERTY keypad keyboard type, even if a numeric keyboard also exists
KEYBOARD_TYPE_UNKNOWN
static int
static int
static int
static int
static int
static int
static int
static int
Field Summary
Unknown keyboard type is the default indicating the software should try to
detect the keyboard type if necessary
KEYBOARD_TYPE_VIRTUAL
1820
MEDIA_KEY_SKIP_FORWARD
Strings native picker type, it returns a String result and accepts a String array.
PICKER_TYPE_TIME
Time native picker type, it returns an integer with minutes since midnight.
SHOW_DURING_EDIT_ALLOW_DISCARD
Allow show to occur during edit and discard all user input at this moment
SHOW_DURING_EDIT_ALLOW_SAVE
Allow show to occur during edit and save all user input at this moment
SHOW_DURING_EDIT_EXCEPTION
If show is called while editing text in the native text box an exception is thrown
SHOW_DURING_EDIT_IGNORE
Ignore all calls to show occurring during edit, they are discarded immediately
SHOW_DURING_EDIT_SET_AS_NEXT
static int
Show will update the current form to which the OK button of the text box will
return
SMS_BOTH
static int
static int
static int
Used by getSMSSupport to indicate that SMS triggers the native SMS app
which will show a compose UI
SMS_NOT_SUPPORTED
static int
static
String
SOUND_TYPE_ALARM
static
String
SOUND_TYPE_BUTTON_PRESS
static
String
SOUND_TYPE_CONFIRMATION
static
String
SOUND_TYPE_ERROR
static
String
SOUND_TYPE_INFO
static
String
SOUND_TYPE_WARNING
Method Summary
Modifier and Type
void
boolean
Method Summary
1821
callSerially(Runnable r)
void
void
void
boolean
cancelLocalNotification(String notificationId)
Boolean
boolean
void
void
void
String
int
void
Media
String
Media
Media
Deprecated.
Object
static void
void
boolean
void
Method Summary
Deletes database
deleteContact(String id)
1822
dial(String phoneNumber)
void
void
void
boolean
void
Object
void
Image
String[]
String[]
int
CodeScanner
Deprecated.
Use the cn1-codescanner cn1lib.
getCommandBehavior()
int
Contact
Contact
getCrashReporter()
Form
String
getDatabasePath(String databaseName)
Method Summary
1823
getDefaultVirtualKeyboard()
int
int
int
float
int
int
int
ImageIO
Purchase
Purchase
static Display
Deprecated.
use the version that accepts no arguments, the phys
manual payment if applicable
getInstance()
int
int
L10NManager
LocationManager
Deprecated.
this method doesn't work properly across device and
the case of unit testing. Do not use it for anything ot
getKeyCode(GAME_*) == keyCodeFromKeyEvent,
getLocalizationManager()
int
String
String
Object
String
Deprecated.
see getAvailableRecordingMimeTypes() instead
getMsisdn()
String[]
Method Summary
1824
int
int
String[]
String
boolean
boolean
boolean
void
static void
Deprecated.
this method is invoked internally do not invoke it!
installBuiltinSound(String soundIdentifier, In
void
void
void
boolean
boolean
boolean
boolean
boolean
boolean
boolean
Method Summary
isBuiltinSoundAvailable(String soundIdentifier
1825
boolean
boolean
boolean
boolean
static boolean
boolean
boolean
boolean
boolean
Deprecated.
use getCommandBehavior() == Display.COMMAND
isNativeInputSupported()
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
Method Summary
1826
isTablet()
boolean
boolean
void
void
void
boolean
void
Object
Deprecated.
there is a new version of this method with a slightly i
Deprecated.
use scheduleLocalNotification instead
numAlphaLevels()
int
Deprecated.
this method isn't implemented in most modern devic
numColors()
int
Deprecated.
this method isn't implemented in most modern devic
onEditingComplete(Component c, String text)
void
void
void
Database
Deprecated.
see openGallery instead
void
void
void
void
void
Method Summary
1827
pointerPressed(int[] x, int[] y)
void
void
void
Deprecated.
use the version that doesn't take an id argument this
ignored!
registerVirtualKeyboard(com.codename1.impl.Vir
void
void
void
void
void
void
void
scheduleLocalNotification(LocalNotification n,
void
setAutoFoldVKBOnFormSwitch(boolean autoFoldVKB
void
void
void
void
void
void
void
void
setDefaultVirtualKeyboard(com.codename1.impl.V
setDragStartPercentage(int dragStartPercentage
void
void
setLongPointerPressInterval(int v)
Method Summary
1828
void
void
void
Deprecated.
use setCommandBehavior(Display.COMMAND_BE
setNoSleep(boolean noSleep)
void
void
void
void
void
void
void
void
void
void
void
Deprecated.
use the method share that accepts an image and m
boolean
boolean
void
void
Method Summary
1829
void
Thread
stopEditing(Component cmp)
void
void
vibrate(int duration)
void
Field Detail
SOUND_TYPE_ALARM
public static final String SOUND_TYPE_ALARM
1830
Unknown keyboard type is the default indicating the software should try to detect the
keyboard type if necessary
See Also:
Constant Field Values
KEYBOARD_TYPE_NUMERIC
public static final int KEYBOARD_TYPE_NUMERIC
Full QWERTY keypad keyboard type, even if a numeric keyboard also exists
See Also:
Constant Field Values
KEYBOARD_TYPE_VIRTUAL
public static final int KEYBOARD_TYPE_VIRTUAL
Used by getSMSSupport to indicate that SMS triggers the native SMS app which will
show a compose UI
See Also:
Constant Field Values
SMS_BOTH
public static final int SMS_BOTH
Field Detail
1831
Used by openGallery
See Also:
Constant Field Values
GALLERY_VIDEO
public static final int GALLERY_VIDEO
Used by openGallery
See Also:
Constant Field Values
GALLERY_ALL
public static final int GALLERY_ALL
Used by openGallery
See Also:
Constant Field Values
DENSITY_VERY_LOW
public static final int DENSITY_VERY_LOW
Hi Density Up To 480x854
See Also:
Constant Field Values
DENSITY_VERY_HIGH
public static final int DENSITY_VERY_HIGH
HD Up To 1920x1080
See Also:
Constant Field Values
Field Detail
1832
4K level density
See Also:
Constant Field Values
PICKER_TYPE_DATE
public static final int PICKER_TYPE_DATE
Time native picker type, it returns an integer with minutes since midnight.
See Also:
Constant Field Values
PICKER_TYPE_DATE_AND_TIME
public static final int PICKER_TYPE_DATE_AND_TIME
Strings native picker type, it returns a String result and accepts a String array.
See Also:
Constant Field Values
GAME_FIRE
public static final int GAME_FIRE
Field Detail
1833
Field Detail
1834
Ignore all calls to show occurring during edit, they are discarded immediately
See Also:
Constant Field Values
SHOW_DURING_EDIT_EXCEPTION
public static final int SHOW_DURING_EDIT_EXCEPTION
If show is called while editing text in the native text box an exception is thrown
See Also:
Constant Field Values
SHOW_DURING_EDIT_ALLOW_DISCARD
public static final int SHOW_DURING_EDIT_ALLOW_DISCARD
Allow show to occur during edit and discard all user input at this moment
See Also:
Constant Field Values
SHOW_DURING_EDIT_ALLOW_SAVE
public static final int SHOW_DURING_EDIT_ALLOW_SAVE
Allow show to occur during edit and save all user input at this moment
See Also:
Constant Field Values
SHOW_DURING_EDIT_SET_AS_NEXT
public static final int SHOW_DURING_EDIT_SET_AS_NEXT
Show will update the current form to which the OK button of the text box will return
See Also:
Constant Field Values
COMMAND_BEHAVIOR_DEFAULT
public static final int COMMAND_BEHAVIOR_DEFAULT
Indicates that the Codename One implementation should decide internally the
command behavior most appropriate for this platform.
See Also:
Constant Field Values
Field Detail
1835
Indicates the classic Codename One command behavior where the commands are
placed in a list within a dialog. This is the most customizable approach for none touch
devices.
See Also:
Constant Field Values
COMMAND_BEHAVIOR_TOUCH_MENU
public static final int COMMAND_BEHAVIOR_TOUCH_MENU
Indicates the touch menu dialog rendered by Codename One where commands are
placed into a scrollable dialog
See Also:
Constant Field Values
COMMAND_BEHAVIOR_BUTTON_BAR
public static final int COMMAND_BEHAVIOR_BUTTON_BAR
Indicates that commands should be added to an always visible bar at the bottom of
the form.
See Also:
Constant Field Values
COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_BACK
public static final int COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_BACK
Identical to the bar behavior, places the back command within the title bar of the
form/dialg
See Also:
Constant Field Values
COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_RIGHT
public static final int COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_RIGHT
Places all commands on the right side of the title bar with a uniform size grid layout
See Also:
Constant Field Values
COMMAND_BEHAVIOR_ICS
public static final int COMMAND_BEHAVIOR_ICS
Commands are placed in the same was as they are in the ice cream sandwich
Android OS update where the back button has a theme icon the application icon
appears next to the
See Also:
Constant Field Values
COMMAND_BEHAVIOR_SIDE_NAVIGATION
public static final int COMMAND_BEHAVIOR_SIDE_NAVIGATION
Indicates that commands should try to add themselves to the native menus
See Also:
Constant Field Values
Field Detail
1836
Method Detail
init
public static void init(Object m)
Closes down the EDT and Codename One, under normal conditions this method is
completely unnecessary since exiting the application will shut down Codename One.
However, if the application is minimized and the user wishes to free all resources
without exiting the application then this method can be used. Once this method is
used Codename One will no longer work and Display.init(Object) should be invoked
again for any further Codename One call! Notice that minimize (being a Codename
One method) MUST be invoked before invoking this method!
isInitialized
public static boolean isInitialized()
This method allows us to manipulate the drag started detection logic. If the pointer
was dragged for more than this percentage of the display size it is safe to assume
that a drag is in progress.
Returns:
motion percentage
setDragStartPercentage
public void setDragStartPercentage(int dragStartPercentage)
This method allows us to manipulate the drag started detection logic. If the pointer
was dragged for more than this percentage of the display size it is safe to assume
that a drag is in progress.
Parameters:
dragStartPercentage - percentage of the screen required to initiate drag
setFramerate
public void setFramerate(int rate)
Indicates the maximum frames the API will try to draw every second by default this is
set to 10. The advantage of limiting framerate is to allow the CPU to perform other
tasks besides drawing. Notice that when no change is occurring on the screen no
frame is drawn and so a high/low FPS will have no effect then. 10FPS would be very
reasonable for a business application.
Parameters:
rate - the frame rate
Method Detail
1837
Flash the backlight of the device for the given length of time
Parameters:
duration - length of time to flash the backlight
setShowDuringEditBehavior
public void setShowDuringEditBehavior(int showDuringEdit)
Invoking the show() method of a form/dialog while the user is editing text in the native
text box can have several behaviors: SHOW_DURING_EDIT_IGNORE,
SHOW_DURING_EDIT_EXCEPTION, SHOW_DURING_EDIT_ALLOW_DISCARD,
SHOW_DURING_EDIT_ALLOW_SAVE, SHOW_DURING_EDIT_SET_AS_NEXT
Parameters:
showDuringEdit - one of the following: SHOW_DURING_EDIT_IGNORE,
SHOW_DURING_EDIT_EXCEPTION,
SHOW_DURING_EDIT_ALLOW_DISCARD,
SHOW_DURING_EDIT_ALLOW_SAVE,
SHOW_DURING_EDIT_SET_AS_NEXT
getShowDuringEditBehavior
public int getShowDuringEditBehavior()
Indicates the maximum frames the API will try to draw every second
Returns:
the frame rate
isEdt
public boolean isEdt()
Returns true if we are currently in the event dispatch thread. This is useful for generic
code that can be used both with the EDT and outside of it.
Returns:
true if we are currently in the event dispatch thread; otherwise false
callSerially
public void callSerially(Runnable r)
Causes the runnable to be invoked on the event dispatch thread. This method returns
immediately and will not wait for the serial call to occur
Parameters:
r - runnable (NOT A THREAD!) that will be invoked on the EDT serial to the
paint and key handling events
Method Detail
1838
Allows executing a background task in a separate low priority thread. Tasks are
serialized so they don't overload the CPU.
Parameters:
r - the task to perform in the background
callSeriallyAndWait
public void callSeriallyAndWait(Runnable r)
Identical to callSerially with the added benefit of waiting for the Runnable method to
complete.
Parameters:
r - runnable (NOT A THREAD!) that will be invoked on the EDT serial to the
paint and key handling events
Throws:
IllegalStateException - if this method is invoked on the event dispatch
thread (e.g. during paint or event handling).
callSeriallyAndWait
public void callSeriallyAndWait(Runnable r,
int timeout)
Identical to callSerially with the added benefit of waiting for the Runnable method to
complete.
Parameters:
r - runnable (NOT A THREAD!) that will be invoked on the EDT serial to the
paint and key handling events
timeout - timeout duration, on timeout the method just returns
Throws:
IllegalStateException - if this method is invoked on the event dispatch
thread (e.g. during paint or event handling).
onEditingComplete
public void onEditingComplete(Component c,
String text)
Called by the underlying implementation to indicate that editing in the native system
has completed and changes should propagate into Codename One
Parameters:
c - edited component
text - new text for the component
invokeAndBlock
public void invokeAndBlock(Runnable r,
boolean dropEvents)
Invokes runnable and blocks the current thread, if the current thread is the edt it will
still be blocked however a separate thread would be launched to perform the duties
of the EDT while it is blocked. Once blocking is finished the EDT would be restored to
its original position. This is very similar to the "foxtrot" Swing toolkit and allows coding
"simpler" logic that requires blocking code in the middle of event sensitive areas.
Parameters:
r - runnable (NOT A THREAD!) that will be invoked synchroniously by this
method
dropEvents - indicates if the display should drop all events while this runnable
is running
invokeAndBlock
public void invokeAndBlock(Runnable r)
Invokes runnable and blocks the current thread, if the current thread is the edt it will
still be blocked however a separate thread would be launched to perform the duties
of the EDT while it is blocked. Once blocking is finished the EDT would be restored to
its original position. This is very similar to the "foxtrot" Swing toolkit and allows coding
Method Detail
1839
Indicates if this is a touch screen device that will return pen events, defaults to true if
the device has pen events but can be overriden by the developer.
Returns:
true if this device supports touch events
setTouchScreenDevice
public void setTouchScreenDevice(boolean touchScreen)
Indicates if this is a touch screen device that will return pen events, defaults to true if
the device has pen events but can be overriden by the developer.
Parameters:
touchScreen - false if this is not a touch screen device
setNoSleep
public void setNoSleep(boolean noSleep)
Calling this method with noSleep=true will cause the edt to run without sleeping.
Parameters:
noSleep - causes the edt to stop the sleeping periods between 2 cycles
setTransitionYield
public void setTransitionYield(int transitionD)
Indicates whether a delay should exist between calls to flush graphics during
transition. In some devices flushGraphics is asynchronious causing it to be very slow
with our background thread. The solution is to add a short wait allowing the
implementation time to paint the screen. This value is set automatically by default but
can be overriden for some devices.
Parameters:
transitionD - -1 for no delay otherwise delay in milliseconds
editString
public void editString(Component cmp,
int maxSize,
int constraint,
String text)
Encapsulates the editing code which is specific to the platform, some platforms would
allow "in place editing" MIDP does not.
Parameters:
cmp - the TextArea component
maxSize - the maximum size from the text area
constraint - the constraints of the text area
text - the string to edit
editString
public void editString(Component cmp,
int maxSize,
int constraint,
String text,
int initiatingKeycode)
Encapsulates the editing code which is specific to the platform, some platforms would
allow "in place editing" MIDP does not.
Parameters:
cmp - the TextArea component
maxSize - the maximum size from the text area
constraint - the constraints of the text area
text - the string to edit
initiatingKeycode - the keycode used to initiate the edit.
Method Detail
1840
Pushes a key press event with the given keycode into Codename One
Parameters:
keyCode - keycode of the key event
keyReleased
public void keyReleased(int keyCode)
Pushes a key release event with the given keycode into Codename One
Parameters:
keyCode - keycode of the key event
pointerDragged
public void pointerDragged(int[] x,
int[] y)
Pushes a pointer drag event with the given coordinates into Codename One
Parameters:
x - the x position of the pointer
y - the y position of the pointer
pointerHover
public void pointerHover(int[] x,
int[] y)
Pushes a pointer hover event with the given coordinates into Codename One
Parameters:
x - the x position of the pointer
y - the y position of the pointer
pointerHoverPressed
public void pointerHoverPressed(int[] x,
int[] y)
Pushes a pointer hover release event with the given coordinates into Codename One
Parameters:
x - the x position of the pointer
y - the y position of the pointer
Method Detail
1841
Pushes a pointer hover release event with the given coordinates into Codename One
Parameters:
x - the x position of the pointer
y - the y position of the pointer
pointerPressed
public void pointerPressed(int[] x,
int[] y)
Pushes a pointer press event with the given coordinates into Codename One
Parameters:
x - the x position of the pointer
y - the y position of the pointer
pointerReleased
public void pointerReleased(int[] x,
int[] y)
Pushes a pointer release event with the given coordinates into Codename One
Parameters:
x - the x position of the pointer
y - the y position of the pointer
sizeChanged
public void sizeChanged(int w,
int h)
Notifies Codename One of display size changes, this method is invoked by the
implementation class and is for internal use
Parameters:
w - the width of the drawing surface
h - the height of the drawing surface
hideNotify
public void hideNotify()
Broadcasts hide notify into Codename One, this method is invoked by the Codename
One implementation to notify Codename One of hideNotify events
showNotify
public void showNotify()
Broadcasts show notify into Codename One, this method is invoked by the
Codename One implementation to notify Codename One of showNotify events
hasDragOccured
public boolean hasDragOccured()
Return the form currently displayed on the screen or null if no form is currently
displayed.
Returns:
the form currently displayed on the screen or null if no form is currently
displayed
Method Detail
1842
Converts the dips count to pixels, dips are roughly 1mm in length. This is a very
rough estimate and not to be relied upon
Parameters:
dipCount - the dips that we will convert to pixels
horizontal - indicates pixels in the horizontal plane
Returns:
value in pixels
getGameAction
public int getGameAction(int keyCode)
Returns the game action code matching the given key combination
Parameters:
keyCode - key code received from the event
Returns:
game action matching this keycode
getKeyCode
public int getKeyCode(int gameAction)
Deprecated. this method doesn't work properly across device and is mocked up here
mostly for the case of unit testing. Do not use it for anything other than that! Do not
rely on getKeyCode(GAME_*) == keyCodeFromKeyEvent, this will never actually
happen!
Returns the keycode matching the given game action constant (the opposite of
getGameAction). On some devices getKeyCode returns numeric keypad values for
game actions, this breaks the code since we filter these values (to prevent navigation
on '2'). We pick unused negative values for game keys and assign them to game
keys for getKeyCode so they will work with getGameAction.
Parameters:
gameAction - game action constant from this class
Method Detail
1843
Displays the virtual keyboard on devices that support manually poping up the vitual
keyboard
Parameters:
show - toggles the virtual keyboards visibility
isVirtualKeyboardShowing
public boolean isVirtualKeyboardShowing()
Method Detail
1844
Indicates whether the device supports native in place editing in which case
lightweight input logic shouldn't be used for input.
Returns:
false by default
isMultiTouch
public boolean isMultiTouch()
Indicates whether the device supports multi-touch events, this is only relevant when
touch events are supported
Returns:
false by default
isClickTouchScreen
public boolean isClickTouchScreen()
Indicates whether the device has a double layer screen thus allowing two stages to
touch events: click and hover. This is true for devices such as the storm but can also
be true for a PC with a mouse pointer floating on top.
A click touch screen will also send pointer hover events to the underlying software
and will only send the standard pointer events on click.
Returns:
false by default
getDragSpeed
public float getDragSpeed(boolean yAxis)
This method returns the dragging speed based on the latest dragged events
Parameters:
yAxis - indicates what axis speed is required
Returns:
the dragging speed
isBidiAlgorithm
public boolean isBidiAlgorithm()
Indicates whether Codename One should consider the bidi RTL algorithm when
drawing text or navigating with the text field cursor.
Returns:
true if the bidi algorithm should be considered
setBidiAlgorithm
public void setBidiAlgorithm(boolean activate)
Indicates whether Codename One should consider the bidi RTL algorithm when
drawing text or navigating with the text field cursor.
Parameters:
activate - set to true to activate the bidi algorithm, false to disable it
convertBidiLogicalToVisual
public String convertBidiLogicalToVisual(String s)
Converts the given string from logical bidi layout to visual bidi layout so it can be
rendered properly on the screen. This method is only necessary for devices/platforms
that don't have "built in" bidi support such as Sony Ericsson devices. See this for
more on visual vs. logical ordering.
Parameters:
s - a "logical" string with RTL characters
Returns:
a "visual" renderable string
Method Detail
1845
Returns the index of the given char within the source string, the actual index isn't
necessarily the same when bidi is involved See this for more on visual vs. logical
ordering.
Parameters:
source - the string in which we are looking for the position
index - the "logical" location of the cursor
Returns:
the "visual" location of the cursor
isRTL
public boolean isRTL(char c)
An error handler will receive an action event with the source exception from the EDT
once an error handler is installed the default Codename One error dialog will no
longer appear
Parameters:
e - listener receiving the errors
removeEdtErrorHandler
public void removeEdtErrorHandler(ActionListener e)
An error handler will receive an action event with the source exception from the EDT
once an error handler is installed the default Codename One error dialog will no
longer appear
Parameters:
e - listener receiving the errors
setAllowMinimizing
public void setAllowMinimizing(boolean allowMinimizing)
Method Detail
1846
This is an internal state flag relevant only for pureTouch mode (otherwise it will
always be true). A pureTouch mode is stopped if a user switches to using the
trackball/navigation pad and this flag essentially toggles between those two modes.
Returns:
the shouldRenderSelection
shouldRenderSelection
public boolean shouldRenderSelection(Component c)
This is an internal state flag relevant only for pureTouch mode (otherwise it will
always be true). A pureTouch mode is stopped if a user switches to using the
trackball/navigation pad and this flag essentially toggles between those two modes.
Parameters:
c - the component to test against, this prevents a touch outside of the
component that triggers a repaint from painting the component selection
Returns:
the shouldRenderSelection
isPureTouch
public boolean isPureTouch()
A pure touch device has no focus showing when the user is using the touch interface.
Selection only shows when the user actually touches the screen or suddenly switches
to using a keypad/trackball. This sort of interface is common in Android devices
Returns:
the pureTouch flag
setPureTouch
public void setPureTouch(boolean pureTouch)
A pure touch device has no focus showing when the user is using the touch interface.
Selection only shows when the user actually touches the screen or suddenly switches
to using a keypad/trackball. This sort of interface is common in Android devices
Parameters:
pureTouch - the value for pureTouch
isNativeCommands
public boolean isNativeCommands()
Method Detail
1847
Normally Codename One folds the VKB when switching forms this field allows us to
block that behavior.
Returns:
the autoFoldVKBOnFormSwitch
setAutoFoldVKBOnFormSwitch
public void setAutoFoldVKBOnFormSwitch(boolean autoFoldVKBOnFormSwitch)
Normally Codename One folds the VKB when switching forms this field allows us to
block that behavior.
Parameters:
autoFoldVKBOnFormSwitch - the autoFoldVKBOnFormSwitch to set
getCommandBehavior
public int getCommandBehavior()
Indicates the way commands should be added to a form as one of the ocmmand
constants defined in this class
Returns:
the commandBehavior
setCommandBehavior
public void setCommandBehavior(int commandBehavior)
Indicates the way commands should be added to a form as one of the ocmmand
constants defined in this class
Parameters:
commandBehavior - the commandBehavior to set
getProperty
public String getProperty(String key,
String defaultValue)
Returns the property from the underlying platform deployment or the default value if
no deployment values are supported. This is equivalent to the getAppProperty from
the jad file.
The implementation should be responsible for the following keys to return reasonable
valid values for the application:
1. AppName
2. User-Agent
3. AppVersion
4. Platform - Similar to microedition.platform
5. OS - returns what is the underlying platform e.g. - J2ME, RIM, SE...
6. OSVer - OS version when available as a user readable string (not necessarily
a number e.g: 3.2.1).
Parameters:
key - the key of the property
defaultValue - a default return value
Returns:
the value of the property
Method Detail
1848
Sets a local property to the application, this method has no effect on the
implementation code and only allows the user to override the logic of getProperty for
internal application purposes.
Parameters:
key - key the key of the property
value - the value of the property
canExecute
public Boolean canExecute(String url)
Returns true if executing this URL should work, returns false if it will not and null if
this is unknown.
Parameters:
url - the url that would be executed
Returns:
true if executing this URL should work, returns false if it will not and null if this
is unknown
execute
public void execute(String url)
Executes the given URL on the native platform, this method is useful if the platform
has the ability to send an event to the app when the execution has ended, currently
this works only for Android platform to invoke other intents.
Parameters:
url - the url to execute
response - a callback from the platform when this execution returned to the
application
getDeviceDensity
public int getDeviceDensity()
Returns one of the density variables appropriate for this device, notice that density
doesn't always correspond to resolution and an implementation might decide to
change the density based on DPI constraints.
Returns:
one of the DENSITY constants of Display
playBuiltinSound
public void playBuiltinSound(String soundIdentifier)
Plays a builtin device sound matching the given identifier, implementations and
themes can offer additional identifiers to the ones that are already built in.
Parameters:
soundIdentifier - the sound identifier which can match one of the common
constants in this class or be a user/implementation defined sound
installBuiltinSound
public void installBuiltinSound(String soundIdentifier,
InputStream data)
throws IOException
Installs a replacement sound as the builtin sound responsible for the given sound
identifier (this will override the system sound if such a sound exists).
Method Detail
1849
Creates a sound in the given URI which is partially platform specific. Notice that an
audio is "auto destroyed" on completion and cannot be played twice!
Parameters:
uri - the platform specific location for the sound
onCompletion - invoked when the audio file finishes playing, may be null
Returns:
a handle that can be used to control the playback of the audio
Throws:
IOException - if the URI access fails
createMedia
public Media createMedia(InputStream stream,
String mimeType,
Runnable onCompletion)
throws IOException
Create the sound in the given stream Notice that an audio is "auto destroyed" on
completion and cannot be played twice!
Parameters:
stream - the stream containing the media data
mimeType - the type of the data in the stream
onCompletion - invoked when the audio file finishes playing, may be null
Returns:
a handle that can be used to control the playback of the audio
Throws:
IOException - if the URI access fails
createSoftWeakRef
public Object createSoftWeakRef(Object o)
Creates a soft/weak reference to an object that allows it to be collected yet caches it.
This method is in the porting layer since CLDC only includes weak references while
Method Detail
1850
Installs the native theme, this is only applicable if hasNativeTheme() returned true.
Notice that this method might replace the DefaultLookAndFeel instance and the
default transitions.
copyToClipboard
public void copyToClipboard(Object obj)
Returns true if the device allows forcing the orientation via code, feature phones do
not allow this although some include a jad property allowing for this feature
Returns:
true if lockOrientation would work
lockOrientation
public void lockOrientation(boolean portrait)
On devices that return true for canForceOrientation() this method can lock the device
orientation either to portrait or landscape mode
Parameters:
portrait - true to lock to portrait mode, false to lock to landscape mode
Method Detail
1851
This is the reverse method for lock orientation allowing orientation lock to be disabled
isTablet
public boolean isTablet()
Indicates whether the device is a tablet, notice that this is often a guess
Returns:
true if the device is assumed to be a tablet
isDesktop
public boolean isDesktop()
On most platforms it is quite fast to draw on a mutable image and then render that
image, however some platforms have much slower mutable images in comparison to
just drawing on the screen. These platforms should return false here and Codename
One will try to use less mutable image related optimizations in transitions and other
operations.
Returns:
true if mutable images are fast on this platform
getLocationManager
public LocationManager getLocationManager()
This method returns the platform Location Manager used for geofencing. This allows
tracking the user location in the background. Usage:
public class GeofenceListenerImpl implements GeofenceListener {
public void onExit(String id) {
System.out.println("Exited "+id);
}
public void onEntered(String id) {
System.out.println("Entered "+id);
}
}
Form hi = new Form("Hi World");
hi.addComponent(new Label("Hi World"));
Location loc = new Location();
loc.setLatitude(51.5033630);
loc.setLongitude(-0.1276250);
Geofence gf = new Geofence("test", loc, 100, 100000);
LocationManager.getLocationManager().addGeoFencing(GeofenceListenerImpl.class, gf);
hi.show();
public class GeofenceListenerImpl implements GeofenceListener {
public void onExit(String id) {
System.out.println("Exited "+id);
}
public void onEntered(String id) {
System.out.println("Entered "+id);
}
}
Form hi = new Form("Hi World");
Method Detail
1852
Returns:
LocationManager Object
capturePhoto
public void capturePhoto(ActionListener response)
This method tries to invoke the device native camera to capture images. The method
returns immediately and the response will be sent asynchronously to the given
ActionListener Object The image is saved as a jpeg to a file on the device. use this in
the actionPerformed to retrieve the file path String path = (String) evt.getSource(); if
evt returns null the image capture was cancelled by the user.
Parameters:
response - a callback Object to retrieve the file path
Throws:
RuntimeException - if this feature failed or unsupported on the platform
captureAudio
public void captureAudio(ActionListener response)
This method tries to invoke the device native hardware to capture audio. The method
returns immediately and the response will be sent asynchronously to the given
ActionListener Object The audio is saved to a file on the device. use this in the
actionPerformed to retrieve the file path String path = (String) evt.getSource();
Parameters:
response - a callback Object to retrieve the file path
Throws:
RuntimeException - if this feature failed or unsupported on the platform
captureVideo
public void captureVideo(ActionListener response)
This method tries to invoke the device native camera to capture video. The method
returns immediately and the response will be sent asynchronously to the given
ActionListener Object The video is saved to a file on the device. use this in the
actionPerformed to retrieve the file path String path = (String) evt.getSource();
Parameters:
response - a callback Object to retrieve the file path
Throws:
RuntimeException - if this feature failed or unsupported on the platform
openImageGallery
public void openImageGallery(ActionListener response)
Method Detail
1853
Parameters:
response - a callback Object to retrieve the file path
type - one of the following GALLERY_IMAGE, GALLERY_VIDEO, GALLERY_ALL
Throws:
RuntimeException
getPlatformName
public String getPlatformName()
Returns a 2-3 letter code representing the platform name for the platform override
Returns:
the name of the platform e.g. ios, rim, win, and, me
Method Detail
1854
Returns the suffixes for ovr files that should be used when loading a layered resource
file on this platform
Returns:
a string array with the proper order of resource override layers
sendMessage
public void sendMessage(String[] recipients,
String subject,
Message msg)
Opens the device Dialer application with the given phone number
Parameters:
phoneNumber getSMSSupport
public int getSMSSupport()
sendSMS
public void sendSMS(String phoneNumber,
String message,
boolean interactive)
throws IOException
notifyStatusBar
public void notifyStatusBar(String tickerText,
String contentTitle,
String contentBody,
boolean vibrate,
boolean flashLights)
Method Detail
1855
Indicates whether the notify status bar method will present a notification to the user
Returns:
true if the notify status bar method will present a notification to the user
notifyStatusBar
public Object notifyStatusBar(String tickerText,
String contentTitle,
String contentBody,
boolean vibrate,
boolean flashLights,
Hashtable args)
Removes the notification previously posted with the notify status bar method
Parameters:
o - the object returned from the notifyStatusBar method
isBadgingSupported
public boolean isBadgingSupported()
Returns true if the underlying OS supports numeric badges on icons. Notice this is
only available on iOS and only when push notification is enabled
Returns:
true if the underlying OS supports numeric badges
setBadgeNumber
public void setBadgeNumber(int number)
Returns true if the underlying OS supports opening the native navigation application
Returns:
true if the underlying OS supports launch of native navigation app
Method Detail
1856
withNumbers,
includesFullName,
includesPicture,
includesNumbers,
includesEmail,
includeAddress)
Notice: this method might be very slow and should be invoked on a separate thread!
It might have platform specific optimizations over getAllContacts followed by looping
over individual contacts but that isn't guaranteed. See isGetAllContactsFast for
information.
Parameters:
withNumbers - if true returns only contacts that has a number
includesFullName - if true try to fetch the full name of the Contact(not just
display name)
includesPicture - if true try to fetch the Contact Picture if exists
includesNumbers - if true try to fetch all Contact numbers
includesEmail - if true try to fetch all Contact Emails
includeAddress - if true try to fetch all Contact Addresses
Returns:
array of the contacts
isGetAllContactsFast
public boolean isGetAllContactsFast()
Indicates if the getAllContacts is platform optimized, notice that the method might still
take seconds or more to run so you should still use a separate thread!
Returns:
true if getAllContacts will perform faster that just getting each contact
getContactById
public Contact getContactById(String id)
Method Detail
1857
Some platforms allow the user to block contacts access on a per application basis
(specifically iOS).
Returns:
true if contacts access is allowed or globally available, false otherwise
createContact
public String createContact(String
String
String
String
String
String
firstName,
familyName,
officePhone,
homePhone,
cellPhone,
email)
Indicates if the native video player includes its own play/pause etc. controls so the
movie player component doesn't need to include them
Returns:
true if the movie player component doesn't need to include such controls
isNativeShareSupported
public boolean isNativeShareSupported()
Method Detail
1858
Deprecated. use the method share that accepts an image and mime type
Share the required information using the platform sharing services. a Sharing service
can be: mail, sms, facebook, twitter,... This method is implemented if
isNativeShareSupported() returned true for a specific platform.
Parameters:
toShare - String to share.
share
public void share(String text,
String image,
String mimeType)
Share the required information using the platform sharing services. a Sharing service
can be: mail, sms, facebook, twitter,... This method is implemented if
isNativeShareSupported() returned true for a specific platform.
Parameters:
text - String to share.
image - file path to the image or null
mime - type of the image or null if no image to share
share
public void share(String text,
String image,
String mimeType,
Rectangle sourceRect)
Share the required information using the platform sharing services. a Sharing service
can be: mail, sms, facebook, twitter,... This method is implemented if
isNativeShareSupported() returned true for a specific platform.
Parameters:
text - String to share.
image - file path to the image or null
mimeType - type of the image or null if no image to share
sourceRect - The source rectangle of the button that originated the share
request. This is used on some platforms to provide a hint as to where the
share dialog overlay should pop up. Particularly, on the iPad with iOS 8 and
higher.
getLocalizationManager
public L10NManager getLocalizationManager()
Deprecated. use the version that doesn't take an id argument this argument is
effectively ignored!
User register to receive push notification
Parameters:
id - the id for the user
noFallback - some devices don't support an efficient push API and will resort
to polling to provide push like functionality. If this flag is set to true no polling
will occur and the error
PushCallback.REGISTRATION_ERROR_SERVICE_NOT_AVAILABLE will
be sent to the push interface.
Method Detail
1859
Register to receive push notification, invoke this method once (ever) to receive push
notifications.
Parameters:
metaData - meta data for push, this is relevant on some platforms such as
google where a push id is necessary,
noFallback - some devices don't support an efficient push API and will resort
to polling to provide push like functionality. If this flag is set to true no polling
will occur and the error
PushCallback.REGISTRATION_ERROR_SERVICE_NOT_AVAILABLE will
be sent to the push interface.
deregisterPush
public void deregisterPush()
Deprecated.
Creates a Media recorder Object which will record from the device mic to a file in the
given path. The output format will be amr-nb if supported by the platform.
Parameters:
path - a file path to where to store the recording, if the file does not exists it
will be created.
Throws:
IOException
createMediaRecorder
public Media createMediaRecorder(String path,
String mimeType)
throws IOException
Creates a Media recorder Object which will record from the device mic to a file in the
given path.
Parameters:
path - a file path to where to store the recording, if the file does not exists it
will be created.
mimeType - the output mime type that is supported see
getAvailableRecordingMimeTypes()
Throws:
IOException
getImageIO
public ImageIO getImageIO()
Method Detail
1860
Deletes database
Parameters:
databaseName
Throws:
IOException
exists
public boolean exists(String databaseName)
Returns the file path of the Database if exists and if supported on the platform.
Returns:
the file path of the database or null if not exists
setPollingFrequency
public void setPollingFrequency(int freq)
Sets the frequency for polling the server in case of polling based push notification
Parameters:
freq - the frequency in milliseconds
startThread
public Thread startThread(Runnable r,
String name)
Start a Codename One thread that supports crash protection and similar Codename
One features.
Parameters:
r - runnable to run, NOTICE the thread MUST be explicitly started!
name - the name for the thread
Returns:
a thread instance which must be explicitly started!
isNativeTitle
public boolean isNativeTitle()
Indicates if the title of the Form is native title(in android ICS devices if the command
behavior is native the ActionBar is used to display the title and the menu)
Returns:
true if platform would like to show the Form title
Method Detail
1861
if the title is native(e.g the android action bar), notify the native title that is needs to be
refreshed
getCrashReporter
public CrashReport getCrashReporter()
Deprecated. use the version that accepts no arguments, the physical goods purchase
is always manual payment if applicable
getCodeScanner
public CodeScanner getCodeScanner()
Method Detail
1862
Indicates whether the native picker dialog is supported for the given type which can
include one of PICKER_TYPE_DATE_AND_TIME, PICKER_TYPE_TIME,
PICKER_TYPE_DATE
Parameters:
pickerType - the picker type constant
Returns:
true if the native platform supports this picker type
showNativePicker
public Object showNativePicker(int type,
Component source,
Object currentValue,
Object data)
Shows a native modal dialog allowing us to perform the picking for the given type
which can include one of PICKER_TYPE_DATE_AND_TIME, PICKER_TYPE_TIME,
PICKER_TYPE_DATE
Parameters:
type - the picker type constant
source - the source component (optional) the native dialog will be placed in
relation to this component if applicable
currentValue - the currently selected value
data - additional meta data specific to the picker type when applicable
Returns:
the value from the picker or null if the operation was canceled.
isMultiKeyMode
public boolean isMultiKeyMode()
When set to true Codename One allows multiple hardware keys to be pressed at
once, this isn't on by default since it can trigger some complexities with UI navigation
to/from native code
Returns:
the multiKeyMode
setMultiKeyMode
public void setMultiKeyMode(boolean multiKeyMode)
When set to true Codename One allows multiple hardware keys to be pressed at
once, this isn't on by default since it can trigger some complexities with UI navigation
to/from native code
Parameters:
multiKeyMode - the multiKeyMode to set
Method Detail
1863
Long pointer press is invoked after the given interval, this allows making long press
events shorter/longer
Parameters:
v - time in milliseconds
getLongPointerPressInterval
public int getLongPointerPressInterval()
Long pointer press is invoked after the given interval, this allows making long press
events shorter/longer
Returns:
time in milliseconds
scheduleLocalNotification
public void scheduleLocalNotification(LocalNotification n,
long firstTime,
int repeat)
isSimulator
public boolean isSimulator()
Allows detecting development mode so debugging code and special cases can be
used to simplify flow
Returns:
true if we are running in the simulator, false otherwise
createBackgroundMedia
public Media createBackgroundMedia(String uri)
throws IOException
Create a blur image from the given image. The algorithm is gaussian blur https://en.wikipedia.org/wiki/Gaussian_blur
Parameters:
Method Detail
1864
in the algorithm
isGaussianBlurSupported
public boolean isGaussianBlurSupported()
Method Detail
1865
Class Dialog
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.Form
com.codename1.ui.Dialog
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
Direct Known Subclasses:
Progress, VirtualKeyboard
public class
extends Form
A dialog is a form that occupies a part of the screen and appears as a modal entity to the developer.
Dialogs allow us to prompt users for information and rely on the information being available on the
next line after the show method.
Modality indicates that a dialog will block the calling thread even if the calling thread is the EDT.
Notice that a dialog will not release the block until dispose is called even if show() from another form
is called! Events are still performed thanks to the Display.invokeAndBlock(java.lang.Runnable)
capability of the Display class.
To determine the size of the dialog use the show method that accepts 4 integer values, notice that
these values accept margin from the four sides rather than x, y, width and height values!
It's important to style a Dialog using getDialogStyle() or setDialogUIID(java.lang.String)
methods rather than styling the dialog object directly.
The Dialog class also includes support for popup dialog which is a dialog type that is positioned next
to a component or screen area and points an arrow at that location.
Typical dialog usage looks like this:
final Button show = new Button("Show Dialog");
final Button showPopup = new Button("Show Popup");
cnt.add(show).add(showPopup);
show.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Dialog.show("Dialog Title", "This is the dialog body, it can contain anything...", "OK", "Cancel");
}
});
showPopup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Dialog d = new Dialog("Popup Title");
TextArea popupBody = new TextArea("This is the body of the popup", 3, 10);
popupBody.setUIID("PopupBody");
popupBody.setEditable(false);
d.setLayout(new BorderLayout());
d.add(BorderLayout.CENTER, popupBody);
d.showPopupDialog(showPopup);
}
});
See this sample for showing a dialog at the bottom of the screen:
Dialog dlg = new Dialog("At Bottom");
dlg.setLayout(new BorderLayout());
// span label accepts the text and the UIID for the dialog body
dlg.add(new SpanLabel("Dialog Body text", "DialogBody"));
int h = Display.getInstance().getDisplayHeight();
dlg.setDisposeWhenPointerOutOfBounds(true);
dlg.show(h /8 * 7, 0, 0, 0);
Class Dialog
1866
See Also:
Display.invokeAndBlock(java.lang.Runnable)
Field Summary
Modifier and
Type
static int
Constant indicating the type of alert to indicate the sound to play or icon if
none are explicitly set
TYPE_CONFIRMATION
static int
Constant indicating the type of alert to indicate the sound to play or icon if
none are explicitly set
TYPE_ERROR
static int
Constant indicating the type of alert to indicate the sound to play or icon if
none are explicitly set
TYPE_INFO
static int
Constant indicating the type of alert to indicate the sound to play or icon if
none are explicitly set
TYPE_NONE
static int
Constant indicating the type of alert to indicate the sound to play or icon if
none are explicitly set
TYPE_WARNING
static int
Constant indicating the type of alert to indicate the sound to play or icon if
none are explicitly set
Field Summary
1867
Constructor Summary
Constructor and Description
Dialog()
Method Summary
Modifier
and Type
protected
void
void
void
void
void
boolean
Invoked to allow subclasses of form to handle a command from one point rather
than implementing many command instances
addComponent(Component cmp)
Closes the current form and returns to the previous form, releasing the EDT in
the process
getBlurBackgroundRadius()
float
Container
static
float
Dialog background can be blurred using a Gaussian blur effect, this sets the
radius of the Gaussian blur.
getContentPane()
Dialog background can be blurred using a Gaussian blur effect, this sets the
radius of the Gaussian blur.
static
String
getDefaultDialogPosition()
static
int
getDefaultDialogType()
Container
String
Dimension
Style
Returns the preferred size of the dialog, this allows developers to position a
dialog manually in arbitrary positions.
getDialogStyle()
int
String
getDialogUIID()
1868
getLayout()
isAutoAdjustDialogSize()
boolean
static
boolean
Places commands as buttons at the bottom of the standard static dialogs rather
than as softbuttons.
isDisableStaticDialogScrolling()
static
boolean
Allows a developer to indicate his interest that the dialog should no longer scroll
on its own but rather rely on the scrolling properties of internal scrollable
containers.
isDisposeWhenPointerOutOfBounds()
boolean
void
protected
void
This flag indicates if the dialog should be disposed if a pointer released event
occurred out of the dialog content.
keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
onShow()
Allows subclasses to bind functionality that occurs when a specific form or dialog
appears on the screen
placeButtonCommands(Command[] cmds)
void
void
void
void
void
static
void
Deprecated.
this method shouldn't be invoked externally, it should have been private
pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method
pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method
removeAll()
void
void
static
void
Method Summary
Dialog background can be blurred using a Gaussian blur effect, this sets the
radius of the Gaussian blur.
setCommandsAsButtons(boolean c)
Places commands as buttons at the bottom of the standard static dialogs rather
than as softbuttons.
1869
setDefaultBlurBackgroundRadius(float aDefaultBlurBackgroundRadius)
Dialog background can be blurred using a Gaussian blur effect, this sets the
radius of the Gaussian blur.
static
void
setDefaultDialogPosition(String p)
static
void
setDefaultDialogType(int d)
void
void
void
void
static
void
Allows a developer to indicate his interest that the dialog should no longer scroll
on its own but rather rely on the scrolling properties of internal scrollable
containers.
setDisposeWhenPointerOutOfBounds(boolean disposeWhenPointerOutOfBounds)
void
void
void
void
This flag indicates if the dialog should be disposed if a pointer released event
occurred out of the dialog content.
setLayout(Layout layout)
void
void
Indicates the time (in milliseconds) afterwhich the dialog will be disposed
implicitly
setTitle(String title)
void
Allows replacing the title with a different title component, thus allowing
developers to create more elaborate title objects.
setTitleComponent(Label title, Transition t)
void
Allows replacing the title with a different title component, thus allowing
developers to create more elaborate title objects.
show()
void
The default version of show modal shows the dialog occupying the center portion
of the screen.
show(int top, int bottom, int left, int right)
Command
This method shows the form as a modal alert allowing us to produce a behavior
of an alert/dialog box.
show(int top, int bottom, int left, int right, boolean includeTitle)
Command
Command
static
Command
static
Command
Method Summary
Deprecated.
use the version that doesn't accept the include title, the includeTitle feature is no
longer supported
show(int top, int bottom, int left, int right, boolean includeTitle,
boolean modal)
Deprecated.
use showAtPosition, the includeTitle flag is no longer supported
show(String title, Component body, Command... cmds)
Shows a modal dialog with the given component as its "body" placed in the
center.
show(String title, Component body, Command[] cmds, int type,
Image icon)
1870
static
Command
static
Command
static
Command
static
Command
static
Command
static
Command
static
boolean
static
boolean
static
boolean
Shows a modal dialog with the given component as its "body" placed in the
center.
show(String title, Component body, Command[] cmds, int type,
Image icon, long timeout, Transition transition)
Shows a modal dialog with the given component as its "body" placed in the
center.
show(String title, Component body, Command defaultCommand,
Command[] cmds, int type, Image icon, long timeout,
Transition transition)
Shows a modal dialog with the given component as its "body" placed in the
center.
show(String title, String text, Command[] cmds, int type, Image icon,
long timeout)
Shows a modal prompt dialog with the given title and text.
show(String title, String text, Command[] cmds, int type, Image icon,
long timeout, Transition transition)
Shows a modal prompt dialog with the given title and text.
show(String title, String text, Command defaultCommand, Command[] cmds,
int type, Image icon, long timeout)
Shows a modal prompt dialog with the given title and text.
show(String title, String text, Command defaultCommand, Command[] cmds,
int type, Image icon, long timeout, Transition transition)
Shows a modal prompt dialog with the given title and text.
show(String title, String text, int type, Image icon, String okText,
String cancelText)
Shows a modal prompt dialog with the given title and text.
show(String title, String text, int type, Image icon, String okText,
String cancelText, long timeout)
Shows a modal prompt dialog with the given title and text.
show(String title, String text, String okText, String cancelText)
Shows a modal prompt dialog with the given title and text.
showAtPosition(int top, int bottom, int left, int right, boolean modal)
Command
This method shows the form as a modal alert allowing us to produce a behavior
of an alert/dialog box.
showBack()
void
Command
Displays the current form on the screen, this version of the method is useful for
"back" navigation since it reverses the direction of the transition.
showDialog()
Shows a modal dialog and returns the command pressed within the modal dialog
showModeless()
void
Command
Shows a modeless dialog which is useful for some simpler use cases such as
progress indication etc...
showPacked(String position, boolean modal)
Command
A popup dialog is shown with the context of a component and its selection, it is
disposed seamlessly if the back button is pressed or if the user touches outside
its bounds.
showPopupDialog(Rectangle rect)
Command
A popup dialog is shown with the context of a component and its selection, it is
disposed seamlessly if the back button is pressed or if the user touches outside
its bounds.
showStetched(String position, boolean modal)
Command
Command
Method Summary
Deprecated.
due to typo use showStretched instead
showStretched(String position, boolean modal)
1871
boolean
Returns true if a dialog that was disposed did it because of a pointer out of
bounds
wasDisposedDueToRotation()
Returns true if the dialog was disposed automatically due to device rotation
1872
Field Detail
TYPE_NONE
public static final int TYPE_NONE
Constant indicating the type of alert to indicate the sound to play or icon if none are
explicitly set
See Also:
Constant Field Values
TYPE_ALARM
public static final int TYPE_ALARM
Constant indicating the type of alert to indicate the sound to play or icon if none are
explicitly set
See Also:
Constant Field Values
TYPE_CONFIRMATION
public static final int TYPE_CONFIRMATION
Constant indicating the type of alert to indicate the sound to play or icon if none are
explicitly set
See Also:
Constant Field Values
TYPE_ERROR
public static final int TYPE_ERROR
Constant indicating the type of alert to indicate the sound to play or icon if none are
explicitly set
See Also:
Constant Field Values
1873
Constant indicating the type of alert to indicate the sound to play or icon if none are
explicitly set
See Also:
Constant Field Values
TYPE_WARNING
public static final int TYPE_WARNING
Constant indicating the type of alert to indicate the sound to play or icon if none are
explicitly set
See Also:
Constant Field Values
Constructor Detail
Dialog
public Dialog(String title)
Method Detail
getContentPane
public Container getContentPane()
Field Detail
1874
Method Detail
1875
Allows modifying the title attributes beyond style (e.g. setting icon/alignment etc.)
Overrides:
getTitleComponent in class Form
Returns:
the component representing the title for the form
getTitleStyle
public Style getTitleStyle()
Allows replacing the title with a different title component, thus allowing developers to
create more elaborate title objects.
Overrides:
setTitleComponent in class Form
Parameters:
title - new title component
getDialogComponent
public Container getDialogComponent()
Returns the container that actually implements the dialog positioning. This container
is normally not accessible via the Codename One API.
Returns:
internal dialog container useful for various calculations.
setTitleComponent
public void setTitleComponent(Label title,
Transition t)
Allows replacing the title with a different title component, thus allowing developers to
create more elaborate title objects. This version of the method allows special effects
for title replacement such as transitions for title entering
Overrides:
setTitleComponent in class Form
Parameters:
title - new title component
t - transition for title replacement
Method Detail
1876
Initialize the default transition for the dialogs overriding the forms transition
Overrides:
initLaf in class Form
Parameters:
laf - the default transition for the dialog
show
public Command show(int top,
int bottom,
int left,
int right,
boolean includeTitle)
Deprecated. use the version that doesn't accept the include title, the includeTitle
feature is no longer supported
This method shows the form as a modal alert allowing us to produce a behavior of an
alert/dialog box. This method will block the calling thread even if the calling thread is
the EDT. Notice that this method will not release the block until dispose is called even
if show() from another form is called!
Modal dialogs Allow the forms "content" to "hang in mid air" this is especially useful
for dialogs where you would want the underlying form to "peek" from behind the form.
Parameters:
top - space in pixels between the top of the screen and the form
bottom - space in pixels between the bottom of the screen and the form
left - space in pixels between the left of the screen and the form
right - space in pixels between the right of the screen and the form
includeTitle - whether the title should hang in the top of the screen or be
glued onto the content pane
Returns:
the last command pressed by the user if such a command exists
Method Detail
1877
top,
bottom,
left,
right)
This method shows the form as a modal alert allowing us to produce a behavior of an
alert/dialog box. This method will block the calling thread even if the calling thread is
the EDT. Notice that this method will not release the block until dispose is called even
if show() from another form is called!
Modal dialogs Allow the forms "content" to "hang in mid air" this is especially useful
for dialogs where you would want the underlying form to "peek" from behind the form.
See this sample for showing a dialog at the bottom of the screen:
Dialog dlg = new Dialog("At Bottom");
dlg.setLayout(new BorderLayout());
// span label accepts the text and the UIID for the dialog body
dlg.add(new SpanLabel("Dialog Body text", "DialogBody"));
int h = Display.getInstance().getDisplayHeight();
dlg.setDisposeWhenPointerOutOfBounds(true);
dlg.show(h /8 * 7, 0, 0, 0);
Parameters:
top - space in pixels between the top of the screen and the form
bottom - space in pixels between the bottom of the screen and the form
left - space in pixels between the left of the screen and the form
right - space in pixels between the right of the screen and the form
Returns:
the last command pressed by the user if such a command exists
show
public Command show(int top,
int bottom,
int left,
int right,
boolean includeTitle,
boolean modal)
Method Detail
1878
Indicates the time (in milliseconds) afterwhich the dialog will be disposed implicitly
Parameters:
time - a milliseconds time used to dispose the dialog
show
public static boolean show(String title,
String text,
int type,
Image icon,
String okText,
String cancelText)
Shows a modal prompt dialog with the given title and text.
Parameters:
title - The title for the dialog optionally null;
text - the text displayed in the dialog
type - the type of the alert one of TYPE_WARNING, TYPE_INFO,
TYPE_ERROR, TYPE_CONFIRMATION or TYPE_ALARM
icon - the icon for the dialog, can be null
okText - the text to appear in the command dismissing the dialog
cancelText - optionally null for a text to appear in the cancel command for
canceling the dialog
Returns:
true if the ok command was pressed or if cancelText is null. False otherwise.
autoAdjust
protected void autoAdjust(int w,
int h)
Auto adjust size of the dialog. This method is triggered from a sizeChanged event.
Parameters:
w - width of the screen
h - height of the screen
show
public static boolean show(String title,
String text,
int type,
Image icon,
String okText,
String cancelText,
long timeout)
Shows a modal prompt dialog with the given title and text.
Parameters:
title - The title for the dialog optionally null;
text - the text displayed in the dialog
Method Detail
1879
Shows a modal prompt dialog with the given title and text.
Parameters:
title - The title for the dialog optionally null;
text - the text displayed in the dialog
cmds - commands that are added to the form any click on any command will
dispose the form
type - the type of the alert one of TYPE_WARNING, TYPE_INFO,
TYPE_ERROR, TYPE_CONFIRMATION or TYPE_ALARM
icon - the icon for the dialog, can be null
timeout - a timeout after which null would be returned if timeout is 0 inifinite
time is used
Returns:
the command pressed by the user
show
public static Command show(String title,
String text,
Command defaultCommand,
Command[] cmds,
int type,
Image icon,
long timeout)
Shows a modal prompt dialog with the given title and text.
Parameters:
title - The title for the dialog optionally null;
text - the text displayed in the dialog
defaultCommand - command to be assigned as the default command or null
cmds - commands that are added to the form any click on any command will
dispose the form
type - the type of the alert one of TYPE_WARNING, TYPE_INFO,
TYPE_ERROR, TYPE_CONFIRMATION or TYPE_ALARM
icon - the icon for the dialog, can be null
timeout - a timeout after which null would be returned if timeout is 0 inifinite
time is used
Returns:
the command pressed by the user
show
public static Command show(String title,
String text,
Command[] cmds,
int type,
Image icon,
long timeout,
Transition transition)
Shows a modal prompt dialog with the given title and text.
Parameters:
title - The title for the dialog optionally null;
Method Detail
1880
Shows a modal prompt dialog with the given title and text.
Parameters:
title - The title for the dialog optionally null;
text - the text displayed in the dialog
defaultCommand - command to be assigned as the default command or null
cmds - commands that are added to the form any click on any command will
dispose the form
type - the type of the alert one of TYPE_WARNING, TYPE_INFO,
TYPE_ERROR, TYPE_CONFIRMATION or TYPE_ALARM
icon - the icon for the dialog, can be null
timeout - a timeout after which null would be returned if timeout is 0 inifinite
time is used
transition - the transition installed when the dialog enters/leaves
Returns:
the command pressed by the user
show
public static boolean show(String
String
String
String
title,
text,
okText,
cancelText)
Shows a modal prompt dialog with the given title and text.
Parameters:
title - The title for the dialog optionally null;
text - the text displayed in the dialog
okText - the text to appear in the command dismissing the dialog
cancelText - optionally null for a text to appear in the cancel command for
canceling the dialog
Returns:
true if the ok command was pressed or if cancelText is null. False otherwise.
show
public static Command show(String title,
Component body,
Command... cmds)
Shows a modal dialog with the given component as its "body" placed in the center.
Parameters:
title - title for the dialog
body - component placed in the center of the dialog
cmds - commands that are added to the form any click on any command will
dispose the form
Returns:
the command pressed by the user
Method Detail
1881
Shows a modal dialog with the given component as its "body" placed in the center.
Parameters:
title - title for the dialog
body - component placed in the center of the dialog
cmds - commands that are added to the form any click on any command will
dispose the form
type - the type of the alert one of TYPE_WARNING, TYPE_INFO,
TYPE_ERROR, TYPE_CONFIRMATION or TYPE_ALARM
icon - the icon for the dialog, can be null
Returns:
the command pressed by the user
show
public static Command show(String title,
Component body,
Command[] cmds,
int type,
Image icon,
long timeout)
Shows a modal dialog with the given component as its "body" placed in the center.
Parameters:
title - title for the dialog
body - component placed in the center of the dialog
cmds - commands that are added to the form any click on any command will
dispose the form
type - the type of the alert one of TYPE_WARNING, TYPE_INFO,
TYPE_ERROR, TYPE_CONFIRMATION or TYPE_ALARM
icon - the icon for the dialog, can be null
timeout - a timeout after which null would be returned if timeout is 0 inifinite
time is used
Returns:
the command pressed by the user
show
public static Command show(String title,
Component body,
Command[] cmds,
int type,
Image icon,
long timeout,
Transition transition)
Shows a modal dialog with the given component as its "body" placed in the center.
Parameters:
title - title for the dialog
body - component placed in the center of the dialog
cmds - commands that are added to the form any click on any command will
dispose the form
type - the type of the alert one of TYPE_WARNING, TYPE_INFO,
TYPE_ERROR, TYPE_CONFIRMATION or TYPE_ALARM
icon - the icon for the dialog, can be null
timeout - a timeout after which null would be returned if timeout is 0 infinite
time is used
transition - the transition installed when the dialog enters/leaves
Returns:
the command pressed by the user
Method Detail
1882
Deprecated. this method shouldn't be invoked externally, it should have been private
Places the given commands in the dialog command area, this is very useful for touch
devices.
Parameters:
cmds - the commands to place
keyReleased
public void keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Form
Parameters:
keyCode - the key code value to indicate a physical key.
show
public static Command show(String title,
Component body,
Command defaultCommand,
Command[] cmds,
int type,
Image icon,
long timeout,
Transition transition)
Shows a modal dialog with the given component as its "body" placed in the center.
Parameters:
title - title for the dialog
body - component placed in the center of the dialog
defaultCommand - command to be assigned as the default command or null
cmds - commands that are added to the form any click on any command will
dispose the form
type - the type of the alert one of TYPE_WARNING, TYPE_INFO,
TYPE_ERROR, TYPE_CONFIRMATION or TYPE_ALARM
icon - the icon for the dialog, can be null
timeout - a timeout after which null would be returned if timeout is 0 inifinite
time is used
transition - the transition installed when the dialog enters/leaves
Returns:
the command pressed by the user
onShow
protected void onShow()
Allows subclasses to bind functionality that occurs when a specific form or dialog
appears on the screen
Overrides:
onShow in class Form
showBack
public void showBack()
Displays the current form on the screen, this version of the method is useful for
"back" navigation since it reverses the direction of the transition.
Overrides:
showBack in class Form
setScrollable
public void setScrollable(boolean scrollable)
Method Detail
1883
show
public void show()
The default version of show modal shows the dialog occupying the center portion of
the screen.
Overrides:
show in class Form
showModeless
public void showModeless()
Shows a modeless dialog which is useful for some simpler use cases such as
progress indication etc...
showPopupDialog
public Command showPopupDialog(Component c)
A popup dialog is shown with the context of a component and its selection, it is
disposed seamlessly if the back button is pressed or if the user touches outside its
bounds. It can optionally provide an arrow in the theme to point at the context
component. The popup dialog has the PopupDialog style by default.
Parameters:
c - the context component which is used to position the dialog and can also
be pointed at
Returns:
the command that might have been triggered by the user within the dialog if
commands are placed in the dialog
showPopupDialog
public Command showPopupDialog(Rectangle rect)
A popup dialog is shown with the context of a component and its selection, it is
disposed seamlessly if the back button is pressed or if the user touches outside its
bounds. It can optionally provide an arrow in the theme to point at the context
component. The popup dialog has the PopupDialog style by default.
Parameters:
rect - the screen rectangle to which the popup should point
Returns:
the command that might have been triggered by the user within the dialog if
commands are placed in the dialog
showPacked
public Command showPacked(String position,
boolean modal)
Method Detail
1884
Returns the preferred size of the dialog, this allows developers to position a dialog
manually in arbitrary positions.
Returns:
the preferred size of this dialog
dispose
public void dispose()
Closes the current form and returns to the previous form, releasing the EDT in the
process
showDialog
public Command showDialog()
Shows a modal dialog and returns the command pressed within the modal dialog
Returns:
last command pressed in the modal dialog
actionCommand
protected void actionCommand(Command cmd)
Invoked to allow subclasses of form to handle a command from one point rather than
implementing many command instances
Overrides:
actionCommand in class Form
Parameters:
cmd - the action command
animate
public boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Form
Returns:
true if a repaint is desired or false if no repaint is necessary
isAutoDispose
public boolean isAutoDispose()
Method Detail
1885
Default screen orientation position for the upcoming dialog. By default the dialog will
be shown at hardcoded coordinates, this method allows us to pack the dialog
appropriately in one of the border layout based locations see BorderLayout for futher
details.
Parameters:
p - for dialogs on the sceen using BorderLayout orientation tags
getDefaultDialogPosition
public static String getDefaultDialogPosition()
Default screen orientation position for the upcoming dialog. By default the dialog will
be shown at hardcoded coordinates, this method allows us to pack the dialog
appropriately in one of the border layout based locations see BorderLayout for futher
details.
Returns:
position for dialogs on the sceen using BorderLayout orientation tags
getDialogType
public int getDialogType()
Indicates whether Codename One should try to automatically adjust a showing dialog
size when a screen size change event occurs
Parameters:
Method Detail
1886
Indicates whether Codename One should try to automatically adjust a showing dialog
size when a screen size change event occurs
Returns:
true to indicate that Codename One should make a "best effort" to resize the
dialog
setDisableStaticDialogScrolling
public static void setDisableStaticDialogScrolling(boolean d)
Allows a developer to indicate his interest that the dialog should no longer scroll on its
own but rather rely on the scrolling properties of internal scrollable containers. This
flag only affects the static show methods within this class.
Parameters:
d - indicates whether scrolling should be active or not
isDisableStaticDialogScrolling
public static boolean isDisableStaticDialogScrolling()
Allows a developer to indicate his interest that the dialog should no longer scroll on its
own but rather rely on the scrolling properties of internal scrollable containers. This
flag only affects the static show methods within this class.
Returns:
true if scrolling should be activated, false otherwise
setCommandsAsButtons
public static void setCommandsAsButtons(boolean c)
Places commands as buttons at the bottom of the standard static dialogs rather than
as softbuttons. This is especially appropriate for devices such as touch devices and
devices without the common softbuttons (e.g. blackberries). The default value is false
Parameters:
c - true to place commands as buttons and not as softbutton keys
isCommandsAsButtons
public static boolean isCommandsAsButtons()
Places commands as buttons at the bottom of the standard static dialogs rather than
as softbuttons. This is especially appropriate for devices such as touch devices and
devices without the common softbuttons (e.g. blackberries). The default value is false
Returns:
true if commands are placed as buttons and not as softbutton keys
setDisposeWhenPointerOutOfBounds
public void setDisposeWhenPointerOutOfBounds(boolean disposeWhenPointerOutOfBounds)
This flag indicates if the dialog should be disposed if a pointer released event
occurred out of the dialog content.
Parameters:
disposeWhenPointerOutOfBounds isDisposeWhenPointerOutOfBounds
public boolean isDisposeWhenPointerOutOfBounds()
This flag indicates if the dialog should be disposed if a pointer released event
occurred out of the dialog content.
Returns:
true if the dialog should dispose
Method Detail
1887
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Form
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerPressed
public void pointerPressed(int x,
int y)
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Form
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
wasDisposedDueToOutOfBoundsTouch
public boolean wasDisposedDueToOutOfBoundsTouch()
Returns true if a dialog that was disposed did it because of a pointer out of bounds
Returns:
true when a dialog was disposed due to pointer out of bounds.
getDialogPosition
public String getDialogPosition()
Screen orientation position for the upcoming dialog. By default the dialog will be
shown at hardcoded coordinates, this method allows us to pack the dialog
appropriately in one of the border layout based locations see BorderLayout for futher
details.
Returns:
the dialogPosition
setDialogPosition
public void setDialogPosition(String dialogPosition)
Screen orientation position for the upcoming dialog. By default the dialog will be
shown at hardcoded coordinates, this method allows us to pack the dialog
appropriately in one of the border layout based locations see BorderLayout for futher
details.
Parameters:
dialogPosition - the dialogPosition to set
growOrShrink
public void growOrShrink()
Indicates if we want to enforce directional bias for the popup dialog. If null this field is
ignored but if its set to a value it biases the system towards a fixed direction for the
popup dialog.
Returns:
the popupDirectionBiasPortrait
Method Detail
1888
Indicates if we want to enforce directional bias for the popup dialog. If null this field is
ignored but if its set to a value it biases the system towards a fixed direction for the
popup dialog.
Parameters:
popupDirectionBiasPortrait - the popupDirectionBiasPortrait to set
wasDisposedDueToRotation
public boolean wasDisposedDueToRotation()
Returns true if the dialog was disposed automatically due to device rotation
Returns:
the disposedDueToRotation value
getBlurBackgroundRadius
public float getBlurBackgroundRadius()
Dialog background can be blurred using a Gaussian blur effect, this sets the radius of
the Gaussian blur. -1 is a special case value that indicates that no blurring should
take effect and the default tint mode only should be used
Returns:
the blurBackgroundRadius
setBlurBackgroundRadius
public void setBlurBackgroundRadius(float blurBackgroundRadius)
Dialog background can be blurred using a Gaussian blur effect, this sets the radius of
the Gaussian blur. -1 is a special case value that indicates that no blurring should
take effect and the default tint mode only should be used. Notice that this value can
be set using the theme constant: dialogBlurRadiusInt
Parameters:
blurBackgroundRadius - the blurBackgroundRadius to set
getDefaultBlurBackgroundRadius
public static float getDefaultBlurBackgroundRadius()
Dialog background can be blurred using a Gaussian blur effect, this sets the radius of
the Gaussian blur. -1 is a special case value that indicates that no blurring should
take effect and the default tint mode only should be used
Returns:
the defaultBlurBackgroundRadius
setDefaultBlurBackgroundRadius
Dialog background can be blurred using a Gaussian blur effect, this sets the radius of
the Gaussian blur. -1 is a special case value that indicates that no blurring should
take effect and the default tint mode only should be used. Notice that this value can
be set using the theme constant: dialogBlurRadiusInt
Parameters:
aDefaultBlurBackgroundRadius - the defaultBlurBackgroundRadius to set
Method Detail
1889
Class Container
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
Direct Known Subclasses:
Ads, BaseSpinner, BrowserComponent, Calendar, ComponentGroup, ContainerList,
EmbeddedContainer, FloatingHint, Form, HTMLComponent, InfiniteContainer,
InteractionDialog, MapComponent, MediaPlayer, MenuBar, MultiButton, OnOffSwitch,
SpanButton, SpanLabel, SwipeableContainer, Table, Tabs, Toolbar, Tree, WebBrowser
public class
extends Component
implements Iterable<Component>
A composite pattern with Component, allows nesting and arranging multiple components using a
pluggable layout manager architecture. Containers can be nested one within the other to form
elaborate UI's. By default Containers use FlowLayout which isn't ideal for most use cases.
Many components within Codename One (e.g. Tree, Table, MultiButton etc.) derive from Container
instead of Component. This allows such components to provide very rich functionality by building on
top of the existing functionality. Container also provides the lead component functionality that allows
Class Container
1890
Field Summary
Constructor Summary
Constructor and Description
Container()
Method Summary
Modifier and Type
Container
Container
Container
Container
Container
Container
void
void
void
void
void
Field Summary
1891
void
void
void
void
void
void
void
void
void
protected Dimension
protected void
void
remove this component and it's children from the painting queue
clearClientProperties()
boolean
protected Motion
protected void
Invoked on the focus component to let it know that drag has started
on the parent container for the case of a component that doesn't
support scrolling
drop(Component dragged, int x, int y)
void
static Container
static Container
Component
Method Summary
1892
void
Deprecated.
this method is no longer used in the new animation framework
forceRevalidate()
void
int
A more powerful form of revalidate that recursively lays out the full
hierarchy
getBottomGap()
Returns the gap to be left for the bottom scrollbar on the X axis.
getClosestComponentTo(int x, int y)
Component
Component
Very useful for touch events or drop events that need approximation
more than accuracy
getComponentAt(int index)
Component
int
int
protected int
protected int
Layout
int
Returns the height for layout manager purposes, this takes scrolling
into consideration unlike the getWidth method.
getLayoutWidth()
int
Returns the width for layout manager purposes, this takes scrolling
into consideration unlike the getWidth method.
getLeadComponent()
Component
Container
int
int
Returns the lead container thats handling the leading, this is useful
for a container hierarchy where the parent container might not be the
leader
getScrollIncrement()
Returns the gap to be left for the side scrollbar on the Y axis.
getUIManager()
UIManager
protected void
void
boolean
isEnabled()
Method Summary
1893
isScrollableX()
protected boolean
Iterator<Component>
void
If this Component is focused, the key pressed event will call this
method
keyReleased(int k)
void
void
void
void
If this Component is focused, the key released event will call this
method
layoutContainer()
void
void
protected void
protected String
void
Invoked for devices where the pointer can hover without actually
clicking the display.
pointerPressed(int x, int y)
void
If this Component is focused, the pointer pressed event will call this
method
refreshTheme(boolean merge)
void
void
void
Method Summary
1894
void
void
void
void
void
void
scrollComponentToVisible(Component c)
void
setCellRenderer(boolean cellRenderer)
void
setEnabled(boolean enabled)
void
setLayout(Layout layout)
void
Sets the lead component for this container, a lead component takes
over the entire component hierarchy and receives all the events for
the container hierarchy.
void
setScrollable(boolean scrollable)
void
void
void
void
void
protected void
setShouldLayout(boolean layout)
void
1895
Constructor Detail
Container
public Container(Layout layout)
Method Detail
1896
This method should be used by the Component to retrieve the correct UIManager to
work with
Overrides:
getUIManager in class Component
Returns:
a UIManager instance
add
public Container add(Component cmp)
Simpler version of addComponent that allows chaining the calls for shorter syntax
Parameters:
cmp - the component to add
Returns:
this for call chaining
add
public Container add(Object constraint,
Component cmp)
Simpler version of addComponent that allows chaining the calls for shorter syntax
Parameters:
constraint - the layout constraint if applicable
cmp - the component to add
Returns:
this for call chaining
add
public Container add(String label)
Simpler version of addComponent that allows chaining the calls for shorter syntax
Parameters:
Method Detail
1897
Simpler version of addComponent that allows chaining the calls for shorter syntax
Parameters:
img - an image that will be wrapped as a label, this is equivalent to calling
add(new Label(l))
Returns:
this for call chaining
add
public Container add(Object constraint,
String label)
Simpler version of addComponent that allows chaining the calls for shorter syntax
Parameters:
constraint - the layout constraint if applicable
label - a component that will be wrapped as a label, this is equivalent to
calling add(new Label(l))
Returns:
this for call chaining
add
public Container add(Object constraint,
Image img)
Simpler version of addComponent that allows chaining the calls for shorter syntax
Parameters:
constraint - the layout constraint if applicable
img - an image that will be wrapped as a label, this is equivalent to calling
add(new Label(l))
Returns:
this for call chaining
setUIManager
public void setUIManager(UIManager uiManager)
Allows replacing the UIManager in a component hierarchy to update the look and feel
only to a specific hierarchy
Parameters:
uiManager - UIManager instance
setLeadComponent
public void setLeadComponent(Component lead)
Sets the lead component for this container, a lead component takes over the entire
component hierarchy and receives all the events for the container hierarchy.
Parameters:
lead - component that takes over the hierarchy
getLeadComponent
public Component getLeadComponent()
Returns the lead component for this hierarchy if such a component is defined
Returns:
the lead component
getLeadParent
public Container getLeadParent()
Returns the lead container thats handling the leading, this is useful for a container
hierarchy where the parent container might not be the leader
Method Detail
1898
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class Component
Parameters:
k - the key code value to indicate a physical key.
keyReleased
public void keyReleased(int k)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Component
Parameters:
k - the key code value to indicate a physical key.
getLayout
public Layout getLayout()
Indicates the values within the component have changed and preferred size should
be recalculated
Overrides:
setShouldCalcPreferredSize in class Component
Parameters:
shouldCalcPreferredSize - indicate whether this component need to
recalculate his preferred size
getLayoutWidth
public int getLayoutWidth()
Returns the width for layout manager purposes, this takes scrolling into consideration
unlike the getWidth method.
Returns:
the layout width
Method Detail
1899
Returns the height for layout manager purposes, this takes scrolling into
consideration unlike the getWidth method.
Returns:
the layout height
applyRTL
public void applyRTL(boolean rtl)
addComponent
public void addComponent(Component cmp)
This method adds the Component at a specific index location in the Container
Components array.
Parameters:
index - location to insert the Component
cmp - the Component to add
Throws:
ArrayIndexOutOfBoundsException - if index is out of bounds
IllegalArgumentException - if Component is already contained or the cmp is
a Form Component
replaceAndWait
public void replaceAndWait(Component current,
Component next,
Transition t)
Method Detail
1900
This method replaces the current Component with the next Component. Current
Component must be contained in this Container. This method returns when transition
has finished.
Parameters:
current - a Component to remove from the Container
next - a Component that replaces the current Component
t - a Transition between the add and removal of the Components a Transition
can be null
layoutAnimationSpeed - the speed of the layout animation after replace is
completed
replace
public void replace(Component current,
Component next,
Transition t,
Runnable onFinish,
int growSpeed)
This method replaces the current Component with the next Component
Parameters:
current - a Component to remove from the Container
next - a Component that replaces the current Component
t - a Transition between the add and removal of the Components a Transition
can be null
onFinish - invoked when the replace operation is completed, may be null
growSpeed - after replace is completed the component can gradually
grow/shrink to fill up available room, set this to 0 for immediate growth or any
larger number for gradual animation. -1 indicates a special case where no
validation occurs
replaceAndWait
public void replaceAndWait(Component current,
Component next,
Transition t,
boolean dropEvents)
This method replaces the current Component with the next Component. Current
Component must be contained in this Container. This method returns when transition
has finished.
Parameters:
current - a Component to remove from the Container
next - a Component that replaces the current Component
t - a Transition between the add and removal of the Components a Transition
can be null
dropEvents - indicates if the display should drop all events while this
Component replacing is happening
replace
public void replace(Component current,
Component next,
Transition t)
Method Detail
1901
removes a Component from the Container, notice that removed component might still
have a pending repaint in the queue that won't be removed. Calling form.repaint() will
workaround such an issue.
Parameters:
cmp - the removed component
cancelRepaints
protected void cancelRepaints()
remove this component and it's children from the painting queue
Overrides:
cancelRepaints in class Component
flushReplace
public void flushReplace()
remove all Components from container, notice that removed component might still
have a pending repaint in the queue that won't be removed. Calling form.repaint() will
workaround such an issue.
revalidate
public void revalidate()
Re-layout the container, this is useful when we modify the container hierarchy and
need to redo the layout
forceRevalidate
public void forceRevalidate()
A more powerful form of revalidate that recursively lays out the full hierarchy
clearClientProperties
public void clearClientProperties()
Method Detail
1902
This method can be overriden by a component to draw on top of itself or its children
after the component or the children finished drawing in a similar way to the glass
pane but more refined per component
Parameters:
g - the graphics context
layoutContainer
public void layoutContainer()
Returns true if the given component is within the hierarchy of this container
Parameters:
cmp - a Component to check
Returns:
true if this Component contains in this Container
Method Detail
1903
Makes sure the component is visible in the scroll if this container is scrollable
Parameters:
c - the component that will be scrolling for visibility
getClosestComponentTo
public Component getClosestComponentTo(int x,
int y)
Very useful for touch events or drop events that need approximation more than
accuracy
Parameters:
x - location in container relative coordinates
y - location in container relative coordinates
Returns:
the closest component in the container or null if no component is in the
container
getComponentAt
public Component getComponentAt(int x,
int y)
pointerHover
public void pointerHover(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHover in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerPressed
public void pointerPressed(int x,
int y)
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Component
Returns:
the calculated preferred size based on component content
Method Detail
1904
Returns a string representing the state of this component. This method is intended to
be used only for debugging purposes, and the content and format of the returned
string may vary between implementations. The returned string may be empty but may
not be null.
Overrides:
paramString in class Component
Returns:
a string representation of this component's state
refreshTheme
public void refreshTheme(boolean merge)
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Component
Parameters:
merge - indicates if the current styles should be merged with the new styles
isScrollableX
public boolean isScrollableX()
Returns the gap to be left for the side scrollbar on the Y axis. This method is used by
layout managers to determine the room they should leave for the scrollbar. (note:
side scrollbar rather than left scrollbar is used for a future version that would support
bidi).
Overrides:
getSideGap in class Component
Returns:
the gap to be left for the side scrollbar on the Y axis
getBottomGap
public int getBottomGap()
Returns the gap to be left for the bottom scrollbar on the X axis. This method is used
by layout managers to determine the room they should leave for the scrollbar
Overrides:
getBottomGap in class Component
Returns:
the gap to be left for the bottom scrollbar on the X axis
setScrollableX
public void setScrollableX(boolean scrollableX)
Method Detail
1905
setScrollableY
public void setScrollableY(boolean scrollableY)
Used as an optimization to mark that this component is currently being used as a cell
renderer
Overrides:
setCellRenderer in class Component
Parameters:
cellRenderer - indicate whether this component is currently being used as a
cell renderer
setScrollIncrement
public void setScrollIncrement(int scrollIncrement)
Determines the scroll increment size of this Container. This value is in use when the
current foucs element within this Container is larger than this Container size.
Parameters:
scrollIncrement - the size in pixels.
getScrollIncrement
public int getScrollIncrement()
Invoked on the focus component to let it know that drag has started on the parent
container for the case of a component that doesn't support scrolling
Overrides:
dragInitiated in class Component
fireClicked
protected void fireClicked()
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly. When overriding this
method you should also override isSelectableInteraction to indicate that a command
is placed appropriately on top of the fire key for 3 soft button phones.
Overrides:
fireClicked in class Component
Method Detail
1906
This method will recursively set all the Container chidrens to be enabled/disabled. If
the Container is disabled and a child Component changed it's state to be enabled, the
child Component will be treated as an enabled Component.
Overrides:
setEnabled in class Component
Parameters:
enabled getGridPosY
protected int getGridPosY()
Paints the background of the component, invoked with the clipping region and
appropriate scroll translation.
Parameters:
g - the component graphics
getGridPosX
protected int getGridPosX()
Method Detail
1907
Animates a pending layout into place, this effectively replaces revalidate with a more
visual form of animation. This method waits until the operation is completed before
returning
Parameters:
duration - the duration in milliseconds for the animation
startingOpacity - the initial opacity to give to the animated components
animateLayoutFade
public void animateLayoutFade(int duration,
int startingOpacity)
Animates a pending layout into place, this effectively replaces revalidate with a more
visual form of animation
Parameters:
duration - the duration in milliseconds for the animation
startingOpacity - the initial opacity to give to the animated components
animateLayoutAndWait
public void animateLayoutAndWait(int duration)
Animates a pending layout into place, this effectively replaces revalidate with a more
visual form of animation. This method waits until the operation is completed before
returning
Parameters:
duration - the duration in milliseconds for the animation
animateLayout
public void animateLayout(int duration)
Animates a pending layout into place, this effectively replaces revalidate with a more
visual form of animation
See:
Form hi = new Form("Layout Animations", new BoxLayout(BoxLayout.Y_AXIS));
Button fall = new Button("Fall");
fall.addActionListener((e) -> {
for(int iter = 0 ; iter < 10 ; iter++) {
Label b = new Label ("Label " + iter);
b.setWidth(fall.getWidth());
b.setHeight(fall.getHeight());
b.setY(-fall.getHeight());
hi.add(b);
}
Method Detail
1908
Parameters:
duration
drop
public void drop(Component dragged,
int x,
int y)
Performs a drop operation of the component at the given X/Y location in coordinate
space, this method should be overriden by subclasses to perform all of the logic
related to moving a component, by default this method does nothing and so dragging
a component and dropping it has no effect
Overrides:
drop in class Component
Parameters:
dragged - the component being dropped
x - the x coordinate of the drop
y - the y coordinate of the drop
createAnimateMotion
protected Motion createAnimateMotion(int start,
int destination,
int duration)
Creates a motion object for animation, allows subclasses to replace the motion type
used in animations (currently defaults to ease-in).
Parameters:
start - start value
destination - destination value
duration - duration of animation
Returns:
motion object
morph
public void morph(Component source,
Component destination,
int duration,
Runnable onCompletion)
Method Detail
1909
This method is the exact reverse of animateLayout, when completed it leaves the
container in an invalid state. It is useful to invoke this in order to remove a
component, transition to a different form or provide some other interaction. E.g.:
Parameters:
duration - the duration of the animation
opacity - the opacity to which the layout
components
iterator
public Iterator<Component> iterator()
Method Detail
1910
Class ComponentGroup
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.ComponentGroup
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
A component group is a container that applies the given UIID to a set of components within it and
gives the same UIID with "First"/"Last" prepended to the first and last components. E.g. by default the
GroupElement UIID is applied so the first and last elements would have the
GroupElementFirst/GroupElementLast UIID's applied to them. If a group has only one element the
word "Only" is appended to the element UIID as in GroupElementOnly.
Important!!! A component group does nothing by default unless explicitly activated by the theme by
enabling the ComponentGroupBool constant (by default, this can be customized via the groupFlag
property). This allows logical grouping without changing the UI for themes that don't need grouping.
This container uses box X/Y layout (defaults to Y), other layout managers shouldn't be used since this
container relies on the specific behavior of the box layout.
Check out this sample code:
hi.add("Three Labels").
add(ComponentGroup.enclose(new
add("One Label").
add(ComponentGroup.enclose(new
add("Three Buttons").
add(ComponentGroup.enclose(new
add("One Button").
add(ComponentGroup.enclose(new
Class ComponentGroup
1911
Field Summary
Constructor Summary
Constructor and Description
ComponentGroup()
Default constructor
Method Summary
Modifier and Type
Field Summary
1912
enclose(Component... cmp)
String
The group flag allows changing the flag that activates this group, from
ComponentGroupBool to any arbitrary flag.
String
getPropertyNames()
String[]
Class[]
Matches the property names method (see that method for further
details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by
the GUI builder
Object
isForceGroup()
boolean
boolean
Makes sure the component is up to date with the current theme, ONLY
INVOKE THIS METHOD IF YOU CHANGED THE THEME!
void
setElementUIID(String elementUIID)
void
void
setGroupFlag(String groupFlag)
The group flag allows changing the flag that activates this group, from
ComponentGroupBool to any arbitrary flag.
void
setHorizontal(boolean horizontal)
void
Method Summary
1913
Constructor Detail
ComponentGroup
public ComponentGroup()
Default constructor
1914
Method Detail
refreshTheme
public void refreshTheme(boolean merge)
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Container
Parameters:
merge - indicates if the current styles should be merged with the new styles
isHorizontal
public boolean isHorizontal()
Indicates that the component group should be horizontal by using the BoxLayout Y
Returns:
the horizontal
setHorizontal
public void setHorizontal(boolean horizontal)
Indicates that the component group should be horizontal by using the BoxLayout Y
Parameters:
horizontal - the horizontal to set
getElementUIID
public String getElementUIID()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
Method Detail
1915
in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
getGroupFlag
public String getGroupFlag()
The group flag allows changing the flag that activates this group, from
ComponentGroupBool to any arbitrary flag. This allows a developer/designer to
enable grouping for a specific type of components (e.g. for horizontal Toggle Buttons)
yet disable it for vertical lists of components.
Returns:
the groupFlag
setGroupFlag
public void setGroupFlag(String groupFlag)
The group flag allows changing the flag that activates this group, from
ComponentGroupBool to any arbitrary flag. This allows a developer/designer to
enable grouping for a specific type of components (e.g. for horizontal Toggle Buttons)
yet disable it for vertical lists of components.
Parameters:
groupFlag - the groupFlag to set
isForceGroup
public boolean isForceGroup()
Component grouping can be an element from the theme but can be forced manually
for a specific group
Returns:
the forceGroup
setForceGroup
public void setForceGroup(boolean forceGroup)
Component grouping can be an element from the theme but can be forced manually
for a specific group
Parameters:
forceGroup - the forceGroup to set
enclose
public static ComponentGroup enclose(Component... cmp)
Shorthand method for wrapping the given components in a vertical component group
Parameters:
cmp - the components to add into a newly created group
Returns:
the newly created group
Method Detail
1916
encloseHorizontal
public static ComponentGroup encloseHorizontal(Component... cmp)
Method Detail
1917
Class Component
java.lang.Object
com.codename1.ui.Component
All Implemented Interfaces:
Animation, StyleListener
Direct Known Subclasses:
ChartComponent, Container, ImageViewer, InfiniteProgress, Label, List, PeerComponent,
TextArea
public class
extends Object
implements Animation, StyleListener
The component class is the basis of all UI widgets in Codename One, to arrange multiple components
together we use the Container class which itself "IS A" Component subclass. The Container is a
Component that contains Components effectively allowing us to nest Containers infinitely to build any
type of visual hierarchy we want by nesting Containers.
See Also:
Container
Field Summary
Modifier and Type
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
Class Component
1918
static int
static int
Constructor Summary
Modifier
protected
Method Summary
Modifier and Type
void
void
Binds an action listener to drop events which are invoked when this component i
addFocusListener(FocusListener l)
void
void
void
void
Registers interest in receiving callbacks for focus gained events, a focus event is
accepts the focus.
addPointerDraggedListener(ActionListener l)
void
This method adds a refresh task to the Component, the task will be executed if t
beyond a certain height.
addScrollListener(ScrollListener l)
void
boolean
void
protected
Dimension
protected
Dimension
protected void
void
boolean
Registers interest in receiving callbacks for scroll gained events, a scroll event is
is scrolled.
animate()
Method that can be overriden to represent the actual size of the component whe
size for the viewport
cancelRepaints()
ComponentAnimation
Creates an animation that will transform the current component to the styling of t
completed.
deinitialize()
protected void
protected void
Field Summary
Invoked to indicate that the component initialization is being reversed since the c
the container hierarchy.
deinitializeCustomStyle(Style s)
Allows components to create a style of their own, this method cleans up state for
1919
dragEnter(Component dragged)
This callback method indicates that a component drag has just entered this com
dragExit(Component dragged)
protected void
protected void
This callback method provides an indication for a drop target that a drag operatio
component and it should clear all relevant state if such state exists.
dragFinished(int x, int y)
Callback indicating that the drag has finished either via drop or by releasing the c
draggingOver(Component dragged, int x, int y)
protected boolean
This method allows a component to indicate if it is a drop target for the given com
location (in component coordiate space).
dragInitiated()
protected void
Invoked on the focus component to let it know that drag has started on the paren
component that doesn't support scrolling
drawDraggedImage(Graphics g, Image img, int x, int y)
protected void
Draws the given image at x/y, this method can be overriden to draw additional in
negative drop indication
drop(Component dragged, int x, int y)
void
Performs a drop operation of the component at the given X/Y location in coordin
be overriden by subclasses to perform all of the logic related to moving a compo
does nothing and so dragging a component and dropping it has no effect
fireClicked()
protected void
protected void
protected void
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this m
devices to work properly.
focusGained()
int
Returns the absolute X location based on the component hierarchy, this method
screen for the component rather than a relative location as returned by getX()
getAbsoluteY()
int
Returns the absolute Y location based on the component hierarchy, this method
screen for the component rather than a relative location as returned by getX()
getAllStyles()
Style
AnimationManager
Returns a "meta style" that allows setting styles once to all the different Style obj
will be meaningless and will return 0 values.
getAnimationManager()
Returns the animation manager of the parent form or null if this component isn't
getBaseline(int width, int height)
int
int
The baseline for the component text according to which it should be aligned with
visual look.
getBaselineResizeBehavior()
Returns a constant indicating how the baseline varies with the size of the compo
getBindablePropertyNames()
String[]
Class[]
Returns the names of the properties within this component that can be bound for
names mean that the first one will be the first bound
getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
getBorder()
protected Border
int
Object
Returns the gap to be left for the bottom scrollbar on the X axis.
getBoundPropertyValue(String prop)
protected
Rectangle
getBounds()
Object
getClientProperty(String key)
Method Summary
Returns the component bounds which is sometimes more convenient than invok
1920
Client properties allow the association of meta-data with a component, this is use
construct GUI's on the fly and need to track the connection between the UI and t
String
String
Form
Object
getCloudBoundProperty()
Indicates the property within this component that should be bound to the cloud o
getCloudDestinationProperty()
Returns the Component Form or null if this Component is not added yet to a form
getComponentState()
Some components may optionally generate a state which can then be restored u
getDirtyRegion()
Rectangle
gets the Component dirty region, this method is for internal use only and SHOUL
code.
getDisabledStyle()
Style
int
int
Returns the Component Style for the disabled state allowing us to manipulate th
its disabled
getDraggedx()
Gets the current dragged x values when the Component is being dragged
getDraggedy()
Gets the current dragged y values when the Component is being dragged
getDragImage()
protected Image
protected int
protected float
Indicates if the section within the X/Y area is a "drag region" where we expect pe
case we can instantly start dragging making perceived performance faster.
getDragSpeed(boolean vertical)
This method returns the dragging speed based on the latest dragged events
getGridPosX()
protected int
protected int
int
Label
String
Component
Component
Component
Component
Container
int
Dimension
int
Style
Method Summary
Allows us to indicate the label associated with this component thus providing vis
component e.g.
getName()
Allows us to determine which component will receive focus next when traversing
getNextFocusLeft()
Allows us to determine which component will receive focus next when traversing
getNextFocusRight()
Allows us to determine which component will receive focus next when traversing
getNextFocusUp()
Allows us to determine which component will receive focus next when traversing
getParent()
1921
Returns the Component Style for the pressed state allowing us to manipulate the
is pressed
getPropertyNames()
String[]
String[]
Class[]
Object
Component[]
Component[]
Component
This method is here to workaround an XMLVM array type bug where property ty
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Obje
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI b
getSameHeight()
int
Dimension
int
int
Returns the Components dimension in scrolling, this is very similar to the preferr
represents actual scrolling limits.
getScrollOpacity()
This method is used internally by the look and feel to implement the fading scroll
getScrollOpacityChangeSpeed()
int
Indicates the X position of the scrolling, this number is relative to the component
would indicate the x position of the component.
getScrollY()
int
String
Indicates the Y position of the scrolling, this number is relative to the component
would indicate the x position of the component.
getSelectCommandText()
Allows determining the text for the select command used in the 3rd softbutton m
getSelectedRect()
Rectangle
Returns the component bounds with absolute screen coordinates, for componen
selection behavior and are not containers (currently only List) this method allows
selection itself which is useful for things such as the popup dialog and similar UI'
position of the selection externally
getSelectedStyle()
Style
int
Returns the Component Style for the selected state allowing us to manipulate th
owns focus
getSideGap()
Returns the gap to be left for the side scrollbar on the Y axis.
getStyle()
Style
int
String
UIManager
Style
Method Summary
Returns the current Component Style allowing code to draw the current compon
getUnselected/Pressed/DisabledStyle() and not this method since it will return di
component state.
getTensileLength()
This method should be used by the Component to retrieve the correct UIManage
getUnselectedStyle()
Returns the Component Style for the unselected mode allowing us to manipulate
1922
getVisibleBounds()
Returns the component bounds for scrolling which might differ from the getBoun
getWidth()
void
boolean
boolean
protected void
Grows or shrinks this component to its new preferred size, this method essential
preferred size has changed and creates a "growing" effect that lasts for the dura
handlesInput()
Allows subclasses to bind functionality that relies on fully initialized and "ready fo
initCustomStyle(Style s)
protected void
protected void
protected void
Allows components to create a style of their own, this method binds the listener t
painter
initLaf(UIManager uim)
Allows subclasses to create their own custom style types and install the backgro
isAlwaysTensile()
boolean
boolean
Enable the tensile drag to work even when a component doesn't have a scroll sh
needs to be set to true)
isCellRenderer()
protected boolean
Indicates whether we are in the middle of a drag operation, this method allows d
released events to know when this is a drag operation.
isDragAndDropOperation(int x, int y)
protected boolean
boolean
Indicates whether this component can be dragged in a drag and drop operation r
isDragRegion(int x, int y)
protected boolean
Deprecated.
replaced with getDragRegionStatus
isDropTarget()
boolean
Indicates whether this component can receive dropped components into it, notic
component or container the parents will be checked recursively to find a valid dro
isEnabled()
boolean
boolean
boolean
boolean
boolean
boolean
protected boolean
Method Summary
This property is useful for blocking in z-order touch events, sometimes we might
specific component without making it focusable.
isHidden()
Indicates that this component and all its children should be hidden when the dev
isInClippingRegion(Graphics g)
1923
boolean
protected boolean
boolean
boolean
boolean
protected boolean
boolean
boolean
protected boolean
boolean
protected boolean
Indicates whether the component should "trigger" tactile touch when pressed by
isTactileTouch(int x, int y)
Elaborate components might not provide tactile feedback for all their areas (e.g.
isTensileDragEnabled()
boolean
boolean
void
void
void
protected void
protected void
Indicates whether tensile drag (dragging beyond the boundry of the component a
for this component.
isVisible()
If this Component is focused, the key pressed event will call this method
keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
keyRepeated(int keyCode)
If this Component is focused, the key repeat event will call this method.
laidOut()
This is a callback method to inform the Component when it's been laidout on the
longKeyPress(int keyCode)
If this Component is focused this method is invoked when the user presses and
longPointerPress(int x, int y)
void
If this Component is focused this method is invoked when the user presses and
Component
onScrollX(int scrollX)
protected void
This method can be overriden to receive scroll events, unlike overriding setScrol
scrolling.
onScrollY(int scrollY)
protected void
This method can be overriden to receive scroll events, unlike overriding setScrol
scrolling.
paint(Graphics g)
void
This method paints the Component on the screen, it should be overriden by subc
drawing or invoke the UI API's to let the PLAF perform the rendering.
paintBackground(Graphics g)
protected void
void
Method Summary
1924
paintBorder(Graphics g)
void
Paints this component as a root by going to all the parent components and settin
based on coordinates and scroll status.
paintComponent(Graphics g, boolean background)
void
Paints this component as a root by going to all the parent components and settin
based on coordinates and scroll status.
paintLock(boolean hardLock)
Image
void
protected void
This method locks the component so it will always paint the given image instead
logic.
paintLockRelease()
Releases the paint lock image to allow paint to work as usual, see paintLock(boo
paintScrollbars(Graphics g)
Paints the UI for the scrollbars on the component, this will be invoked only for sc
paintScrollbarX(Graphics g)
protected void
Paints the UI for the scrollbar on the X axis, this method allows component subc
a scrollbar
paintScrollbarY(Graphics g)
protected void
protected String
Paints the UI for the scrollbar on the Y axis, this method allows component subc
a scrollbar
paramString()
protected boolean
void
void
void
void
void
void
void
void
void
If this Component is focused, the pointer dragged event will call this method
pointerDragged(int x, int y)
If this Component is focused, the pointer dragged event will call this method
pointerHover(int[] x, int[] y)
Invoked for devices where the pointer can hover without actually clicking the disp
pointerHoverPressed(int[] x, int[] y)
Invoked for devices where the pointer can hover without actually clicking the disp
pointerHoverReleased(int[] x, int[] y)
Invoked for devices where the pointer can hover without actually clicking the disp
pointerPressed(int[] x, int[] y)
If this Component is focused, the pointer pressed event will call this method
pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method
pointerReleased(int[] x, int[] y)
If this Component is focused, the pointer released event will call this method
pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method
putClientProperty(String key, Object value)
void
Client properties allow the association of meta-data with a component, this is use
construct GUI's on the fly and need to track the connection between the UI and t
refreshTheme()
void
Makes sure the component is up to date with the current theme, ONLY INVOKE
CHANGED THE THEME!
refreshTheme(boolean merge)
void
protected void
void
Method Summary
Makes sure the component is up to date with the current theme, ONLY INVOKE
CHANGED THE THEME!
refreshTheme(String id, boolean merge)
1925
removeDropListener(ActionListener l)
Removes an action listener to drop events which are invoked when this compon
removeFocusListener(FocusListener l)
Repaint this Component, the repaint call causes a callback of the paint method o
repaint(int x, int y, int w, int h)
void
protected void
void
protected void
Changes the current component to the focused component, will work only for a c
parent form.
resetFocusable()
Makes sure the component is visible in the scroll if this container is scrollable
scrollRectToVisible(Rectangle rect, Component coordinateSpace)
Makes sure the component is visible in the scroll if this container is scrollable
setAlwaysTensile(boolean alwaysTensile)
void
Enable the tensile drag to work even when a component doesn't have a scroll sh
needs to be set to true)
setBoundPropertyValue(String prop, Object value)
void
void
void
void
void
Sets the value of a bound property within this component, notice that this method
change event when invoked to prevent recursion!
setCellRenderer(boolean cellRenderer)
Indicates the property within this component that should be bound to the cloud o
setCloudDestinationProperty(String cloudDestinationProperty)
If getComponentState returned a value the setter can update the value and resto
setDirtyRegion(Rectangle dirty)
void
void
void
sets the Component dirty region, this method is for internal use only and SHOUL
code.
setDisabledStyle(Style style)
Changes the Component disalbed Style by replacing the Component Style with t
setDraggable(boolean draggable)
Indicates whether this component can be dragged in a drag and drop operation r
setDropTarget(boolean dropTarget)
void
Indicates whether this component can receive dropped components into it, notic
component or container the parents will be checked recursively to find a valid dro
setEnabled(boolean enabled)
void
void
void
Method Summary
Deprecated.
this method shouldn't be invoked by user code, use requestFocus() instead
1926
setFocusable(boolean focusable)
void
void
This property is useful for blocking in z-order touch events, sometimes we might
specific component without making it focusable.
setHandlesInput(boolean handlesInput)
void
void
void
void
Sets the Component height, this method is exposed for the purpose of external l
be invoked directly.
If a user wishes to effect the component size setPreferredSize should be used.
setHidden(boolean b)
Makes the components preferred size equal 0 when hidden and restores it to the
setHidden(boolean b, boolean changeMargin)
Makes the components preferred size equal 0 when hidden and restores it to the
setHideInPortrait(boolean hideInPortrait)
Indicates that this component and all its children should be hidden when the dev
setInitialized(boolean initialized)
protected void
void
Deprecated.
replaced by setScrollVisible to match the JavaBeans spec
setLabelForComponent(Label componentLabel)
void
void
void
Allows us to indicate the label associated with this component thus providing vis
component e.g.
setName(String name)
Allows us to determine which component will receive focus next when traversing
setNextFocusLeft(Component nextFocusLeft)
void
void
Allows us to determine which component will receive focus next when traversing
doesn't affect the general focus behavior.
setNextFocusRight(Component nextFocusRight)
Allows us to determine which component will receive focus next when traversing
setNextFocusUp(Component nextFocusUp)
void
Allows us to determine which component will receive focus next when traversing
doesn't affect the general focus behavior.
setPreferredH(int preferredH)
void
Deprecated.
this method shouldn't be used, use sameWidth/Height, padding, margin or overr
similar functionality
setPreferredSize(Dimension d)
void
Deprecated.
this method shouldn't be used, use sameWidth/Height, padding, margin or overr
similar functionality
setPreferredW(int preferredW)
void
Deprecated.
this method shouldn't be used, use sameWidth/Height, padding, margin or overr
similar functionality
setPressedStyle(Style style)
void
String
void
Sets the Component Style for the pressed state allowing us to manipulate the loo
pressed
setPropertyValue(String name, Object value)
Sets a new value to the given property, returns an error message if failed and nu
setRTL(boolean rtl)
static void
Method Summary
Places all of these components in the same height group, to remove a compone
method with that component only.
1927
Places all of these components in the same width group, to remove a componen
method with that component only.
setScrollAnimationSpeed(int animationSpeed)
void
void
void
void
protected void
Indicates the X position of the scrolling, this number is relative to the component
would indicate the x position of the component.
setScrollY(int scrollY)
protected void
void
void
void
Indicates the X position of the scrolling, this number is relative to the component
would indicate the x position of the component.
setSelectCommandText(String selectText)
Allows determining the text for the select command used in the 3rd softbutton m
setSelectedStyle(Style style)
Changes the Component selected Style by replacing the Component Style with t
setShouldCalcPreferredSize(boolean shouldCalcPreferredSize)
Indicates the values within the component have changed and preferred size sho
setSize(Dimension d)
void
void
void
void
Sets the Component size, this method is exposed for the purpose of external lay
be invoked directly.
If a user wishes to effect the component size setPreferredSize should be used.
setSmoothScrolling(boolean smoothScrolling)
Indicates whether the component should "trigger" tactile touch when pressed by
setTensileDragEnabled(boolean tensileDragEnabled)
void
void
void
void
void
Indicates whether tensile drag (dragging beyond the boundry of the component a
for this component.
setTensileLength(int tensileLength)
Changes the Component Style by replacing the Component Style with the given
setVisible(boolean visible)
void
Sets the Component width, this method is exposed for the purpose of external la
be invoked directly.
If a user wishes to effect the component size setPreferredSize should be used.
setX(int x)
void
Sets the Component x location relative to the parent container, this method is ex
external layout managers and should not be invoked directly.
setY(int y)
void
Sets the Component y location relative to the parent container, this method is ex
external layout managers and should not be invoked directly.
shouldBlockSideSwipe()
protected boolean
A component that might need side swipe such as the slider could block it from be
purpose when on top of said component.
void
Method Summary
1928
String
void
Field Detail
DRAG_REGION_NOT_DRAGGABLE
public static final int DRAG_REGION_NOT_DRAGGABLE
1929
Field Detail
1930
Constructor Detail
Component
protected Component()
Method Detail
setSameWidth
public static void setSameWidth(Component... c)
Places all of these components in the same width group, to remove a component
from the group invoke this method with that component only.
Parameters:
c - the components to group together, this will override all previous width
grouping
getAllStyles
public Style getAllStyles()
Returns a "meta style" that allows setting styles once to all the different Style objects,
the getters for this style will be meaningless and will return 0 values. Usage:
Painter p = new Painter(cmp) {
public void paint(Graphics g, Rectangle rect) {
boolean antiAliased = g.isAntiAliased();
g.setAntiAliased(true);
int r = Math.min(rect.getWidth(), rect.getHeight())/2;
int x = rect.getX() + rect.getWidth()/2 - r;
int y = rect.getY() + rect.getHeight()/2 - r;
switch (style) {
case CircleButtonStrokedDark:
case CircleButtonStrokedLight: {
if (cmp.getStyle().getBgTransparency() != 0) {
int alpha = cmp.getStyle().getBgTransparency();
if (alpha <0) {
alpha = 0xff;
}
g.setColor(cmp.getStyle().getBgColor());
g.setAlpha(alpha);
g.fillArc(x, y, 2*r-1, 2*r-1, 0, 360);
g.setAlpha(0xff);
}
g.setColor(cmp.getStyle().getFgColor());
g.drawArc(x, y, 2*r-1, 2*r-1, 0, 360);
break;
}
case CircleButtonFilledDark:
case CircleButtonFilledLight:
case CircleButtonTransparentDark:
case CircleButtonTransparentLight: {
int alpha = cmp.getStyle().getBgTransparency();
if (alpha < 0) {
alpha = 0xff;
}
g.setAlpha(alpha);
Field Detail
1931
Returns:
a unified style object for the purpose of setting on object object instances
getSameWidth
public Component[] getSameWidth()
Places all of these components in the same height group, to remove a component
from the group invoke this method with that component only.
Parameters:
c - the components to group together, this will override all previous height
grouping
getSameHeight
public Component[] getSameHeight()
This method should be used by the Component to retrieve the correct UIManager to
work with
Returns:
a UIManager instance
getX
public int getX()
Method Detail
1932
Client properties allow the association of meta-data with a component, this is useful
for some applications that construct GUI's on the fly and need to track the connection
between the UI and the data.
Parameters:
key - the key used for putClientProperty
Returns:
the value set to putClientProperty or null if no value is set to the property
clearClientProperties
public void clearClientProperties()
Client properties allow the association of meta-data with a component, this is useful
for some applications that construct GUI's on the fly and need to track the connection
between the UI and the data. Setting the value to null will remove the client property
from the component.
Parameters:
key - arbitrary key for the property
value - the value assigned to the given client property
getDirtyRegion
public final Rectangle getDirtyRegion()
gets the Component dirty region, this method is for internal use only and SHOULD
NOT be invoked by user code. Use repaint(int,int,int,int)
Returns:
returns the region that needs repainting or null for the whole component
setDirtyRegion
public final void setDirtyRegion(Rectangle dirty)
sets the Component dirty region, this method is for internal use only and SHOULD
NOT be invoked by user code. Use repaint(int,int,int,int)
Parameters:
dirty - the region that needs repainting or null for the whole component
setVisible
public void setVisible(boolean visible)
Method Detail
1933
Sets the Component x location relative to the parent container, this method is
exposed for the purpose of external layout managers and should not be invoked
directly.
Parameters:
x - the current x coordinate of the components origin
setY
public void setY(int y)
Sets the Component y location relative to the parent container, this method is
exposed for the purpose of external layout managers and should not be invoked
directly.
Parameters:
y - the current y coordinate of the components origin
isDragRegion
protected boolean isDragRegion(int x,
int y)
Indicates if the section within the X/Y area is a "drag region" where we expect people
to drag or press in which case we can instantly start dragging making perceived
performance faster. This is invoked by the implementation code to optimize drag start
behavior
Parameters:
x - x location for the touch
y - y location for the touch
Returns:
one of the DRAG_REGION_* values
getBaseline
public int getBaseline(int width,
int height)
The baseline for the component text according to which it should be aligned with
other components for best visual look.
Parameters:
width - the component width
height - the component height
Returns:
baseline value from the top of the component
getBaselineResizeBehavior
public int getBaselineResizeBehavior()
Returns a constant indicating how the baseline varies with the size of the component.
Returns:
one of BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT,
BRB_CENTER_OFFSET or BRB_OTHER
Method Detail
1934
Returns the Component Preferred Size, there is no guarantee the Component will be
sized at its Preferred Size. The final size of the component may be smaller than its
preferred size or even larger than the size.
The Layout manager can take this value into consideration, but there is no guarantee
or requirement.
Returns:
the component preferred size
getScrollDimension
public Dimension getScrollDimension()
Returns the Components dimension in scrolling, this is very similar to the preferred
size aspect only it represents actual scrolling limits.
Returns:
the component actual size with all scrolling
calcScrollSize
protected Dimension calcScrollSize()
Method that can be overriden to represent the actual size of the component when it
differs from the desireable size for the viewport
Returns:
scroll size, by default this is the same as the preferred size
setScrollSize
public void setScrollSize(Dimension d)
setPreferredH
public void setPreferredH(int preferredH)
Method Detail
1935
getPreferredW
public int getPreferredW()
getPreferredH
public int getPreferredH()
setWidth
public void setWidth(int width)
Sets the Component width, this method is exposed for the purpose of external layout
managers and should not be invoked directly.
If a user wishes to effect the component size setPreferredSize should be used.
Parameters:
width - the width of the component
See Also:
setPreferredSize(com.codename1.ui.geom.Dimension)
setHeight
public void setHeight(int height)
Sets the Component height, this method is exposed for the purpose of external layout
managers and should not be invoked directly.
If a user wishes to effect the component size setPreferredSize should be used.
Parameters:
height - the height of the component
See Also:
setPreferredSize(com.codename1.ui.geom.Dimension)
setSize
public void setSize(Dimension d)
Sets the Component size, this method is exposed for the purpose of external layout
managers and should not be invoked directly.
If a user wishes to effect the component size setPreferredSize should be used.
Parameters:
d - the component dimension
See Also:
setPreferredSize(com.codename1.ui.geom.Dimension)
getUIID
public String getUIID()
This method sets the Component the Unique identifier. This method should be used
before a component has been initialized
Parameters:
id - UIID unique identifier for component type
Method Detail
1936
Registers interest in receiving callbacks for focus gained events, a focus event is
invoked when the component accepts the focus. A special case exists for the Form
which sends a focus even for every selection within the form.
Parameters:
l - listener interface implementing the observable pattern
removeFocusListener
public void removeFocusListener(FocusListener l)
Registers interest in receiving callbacks for scroll gained events, a scroll event is
invoked when the component is scrolled.
Parameters:
l - listener interface implementing the observable pattern
removeScrollListener
public void removeScrollListener(ScrollListener l)
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly. When overriding this
method you should also override isSelectableInteraction to indicate that a command
is placed appropriately on top of the fire key for 3 soft button phones.
isSelectableInteraction
protected boolean isSelectableInteraction()
Allows determining the text for the select command used in the 3rd softbutton mode.
Parameters:
selectText - text for the interaction with the softkey
getSelectCommandText
public String getSelectCommandText()
Allows determining the text for the select command used in the 3rd softbutton mode.
Returns:
Method Detail
1937
Allows us to indicate the label associated with this component thus providing visual
feedback related for this component e.g. starting the ticker when the component
receives focus.
Parameters:
componentLabel - a label associated with this component
getLabelForComponent
public Label getLabelForComponent()
Allows us to indicate the label associated with this component thus providing visual
feedback related for this component e.g. starting the ticker when the component
receives focus.
Returns:
the label associated with this component
focusGained
protected void focusGained()
Returns the absolute X location based on the component hierarchy, this method
calculates a location on the screen for the component rather than a relative location
as returned by getX()
Returns:
the absolute x location of the component
See Also:
getX()
getAbsoluteY
public int getAbsoluteY()
Returns the absolute Y location based on the component hierarchy, this method
calculates a location on the screen for the component rather than a relative location
as returned by getX()
Returns:
the absolute y location of the component
See Also:
getY()
isInClippingRegion
protected boolean isInClippingRegion(Graphics g)
paintScrollbars
protected void paintScrollbars(Graphics g)
Paints the UI for the scrollbars on the component, this will be invoked only for
scrollable components. This method invokes the appropriate X/Y versions to do all
Method Detail
1938
Paints the UI for the scrollbar on the X axis, this method allows component
subclasses to customize the look of a scrollbar
Parameters:
g - the component graphics
getScrollOpacity
public int getScrollOpacity()
This method is used internally by the look and feel to implement the fading scrollbar
behavior.
Returns:
the opacity of the scrollbar
getSelectedRect
public Rectangle getSelectedRect()
Returns the component bounds with absolute screen coordinates, for components
that include an internal selection behavior and are not containers (currently only List)
this method allows returning the position of the selection itself which is useful for
things such as the popup dialog and similar UI's that need to reference the position of
the selection externally
Returns:
the bounds of the component with absolute screen coordinates
paintScrollbarY
protected void paintScrollbarY(Graphics g)
Paints the UI for the scrollbar on the Y axis, this method allows component
subclasses to customize the look of a scrollbar
Parameters:
g - the component graphics
paintComponent
public final void paintComponent(Graphics g)
Paints this component as a root by going to all the parent components and setting the
absolute translation based on coordinates and scroll status. Restores translation
when the painting is finished.
One of the uses of this method is to create a "screenshot" as is demonstrated in the
code below that creates an image for sharing on social media
Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);
Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");
Parameters:
g - the graphics to paint this Component on
Method Detail
1939
Paints this component as a root by going to all the parent components and setting the
absolute translation based on coordinates and scroll status. Restores translation
when the painting is finished.
One of the uses of this method is to create a "screenshot" as is demonstrated in the
code below that creates an image for sharing on social media
Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);
Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");
Parameters:
g - the graphics to paint this Component on
background - if true paints all parents background
getBorder
protected Border getBorder()
Method Detail
1940
Indicates the X position of the scrolling, this number is relative to the component
position and so a position of 0 would indicate the x position of the component.
Returns:
the X position of the scrolling
getScrollY
public int getScrollY()
Indicates the Y position of the scrolling, this number is relative to the component
position and so a position of 0 would indicate the x position of the component.
Returns:
the Y position of the scrolling
onScrollX
protected void onScrollX(int scrollX)
This method can be overriden to receive scroll events, unlike overriding setScrollX it
will receive all calls for scrolling. Normally you should not override this method and try
to find a more creative solution since scrolling is very specific to platform behavior.
Parameters:
scrollX - the X position of the scrolling
onScrollY
protected void onScrollY(int scrollY)
This method can be overriden to receive scroll events, unlike overriding setScrollY it
will receive all calls for scrolling. Normally you should not override this method and try
to find a more creative solution since scrolling is very specific to platform behavior.
Parameters:
scrollY - the Y position of the scrolling
setScrollX
protected void setScrollX(int scrollX)
Indicates the X position of the scrolling, this number is relative to the component
position and so a position of 0 would indicate the x position of the component.
Parameters:
scrollX - the X position of the scrolling
setScrollY
protected void setScrollY(int scrollY)
Indicates the X position of the scrolling, this number is relative to the component
position and so a position of 0 would indicate the x position of the component.
Parameters:
scrollY - the Y position of the scrolling
Method Detail
1941
Gets the current dragged x values when the Component is being dragged
Returns:
dragged x value
getDraggedy
public int getDraggedy()
Gets the current dragged y values when the Component is being dragged
Returns:
dragged y value
getBottomGap
public int getBottomGap()
Returns the gap to be left for the bottom scrollbar on the X axis. This method is used
by layout managers to determine the room they should leave for the scrollbar
Returns:
the gap to be left for the bottom scrollbar on the X axis
getSideGap
public int getSideGap()
Returns the gap to be left for the side scrollbar on the Y axis. This method is used by
layout managers to determine the room they should leave for the scrollbar. (note:
side scrollbar rather than left scrollbar is used for a future version that would support
bidi).
Returns:
the gap to be left for the side scrollbar on the Y axis
contains
public boolean contains(int x,
int y)
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Returns:
the calculated preferred size based on component content
getBounds
protected Rectangle getBounds()
Returns the component bounds which is sometimes more convenient than invoking
getX/Y/Width/Height. Bounds are relative to parent container.
Changing values within the bounds can lead to unpredicted behavior.
Returns:
the component bounds
See Also:
getX(), getY()
Method Detail
1942
Returns the component bounds for scrolling which might differ from the getBounds for
large components e.g. list.
Returns:
the component bounds
See Also:
getX(), getY()
isFocusable
public boolean isFocusable()
Indicates the values within the component have changed and preferred size should
be recalculated
Parameters:
shouldCalcPreferredSize - indicate whether this component need to
recalculate his preferred size
handlesInput
public boolean handlesInput()
Prevents key events from being grabbed for focus traversal. E.g. a list component
might use the arrow keys for internal navigation so it will switch this flag to true in
order to prevent the focus manager from moving to the next component.
Returns:
true if key events are being used for focus traversal ; otherwise false
setHandlesInput
public void setHandlesInput(boolean handlesInput)
Prevents key events from being grabbed for focus traversal. E.g. a list component
might use the arrow keys for internal navigation so it will switch this flag to true in
order to prevent the focus manager from moving to the next component.
Parameters:
handlesInput - indicates whether key events can be grabbed for focus
traversal
hasFocus
public boolean hasFocus()
Method Detail
1943
getComponentForm
public Form getComponentForm()
Returns the Component Form or null if this Component is not added yet to a form
Returns:
the Component Form
repaint
public void repaint()
Repaint this Component, the repaint call causes a callback of the paint method on the
event dispatch thread.
See Also:
Display
repaint
public void repaint(int
int
int
int
x,
y,
w,
h)
If this Component is focused this method is invoked when the user presses and holds
the key
Parameters:
keyCode - the key code value to indicate a physical key.
keyPressed
public void keyPressed(int keyCode)
If this Component is focused, the key pressed event will call this method
Parameters:
keyCode - the key code value to indicate a physical key.
keyReleased
public void keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
Parameters:
keyCode - the key code value to indicate a physical key.
Method Detail
1944
If this Component is focused, the key repeat event will call this method.
Parameters:
keyCode - the key code value to indicate a physical key.
getAnimationManager
public AnimationManager getAnimationManager()
Returns the animation manager of the parent form or null if this component isn't
currently associated with a form
Returns:
the animation manager instance
getScrollAnimationSpeed
public int getScrollAnimationSpeed()
Creates an animation that will transform the current component to the styling of the
destination UIID when completed. Notice that fonts will only animate within the
truetype and native familiy and we recommend that you don't shift
weight/typeface/style as this might diminish the effect.
Important: Only unselected styles are animated but once the animation completes all
styles are applied.
Parameters:
destUIID - the UIID to which this component will gradually shift
duration - the duration of the animation or the number of steps
Returns:
an animation component that can either be stepped or played
setScrollAnimationSpeed
public void setScrollAnimationSpeed(int animationSpeed)
Method Detail
1945
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerHoverPressed
public void pointerHoverPressed(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pinch
protected boolean pinch(float scale)
If this Component is focused, the pointer dragged event will call this method
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
getDragImage
protected Image getDragImage()
Invoked on the focus component to let it know that drag has started on the parent
container for the case of a component that doesn't support scrolling
Method Detail
1946
Draws the given image at x/y, this method can be overriden to draw additional
information such as positive or negative drop indication
Parameters:
g - the graphics context
img - the image
x - x position
y - y position
draggingOver
protected boolean draggingOver(Component dragged,
int x,
int y)
This method allows a component to indicate if it is a drop target for the given
component at the given x/y location (in component coordiate space). This method
can also update the drop tagets appearance to indicate the drop location.
Parameters:
dragged - the component being dragged
x - the x location over the component
y - the y location over the component
Returns:
true if a drop at this location will be successful
dragEnter
protected void dragEnter(Component dragged)
This callback method indicates that a component drag has just entered this
component
Parameters:
dragged - the component being dragged
dragExit
protected void dragExit(Component dragged)
This callback method provides an indication for a drop target that a drag operation is
exiting the bounds of this component and it should clear all relevant state if such state
exists. E.g. if a component provides drop indication visuaization in draggingOver this
visualization should be cleared..
Parameters:
dragged - the component being dragged
drop
public void drop(Component dragged,
int x,
int y)
Performs a drop operation of the component at the given X/Y location in coordinate
space, this method should be overriden by subclasses to perform all of the logic
related to moving a component, by default this method does nothing and so dragging
a component and dropping it has no effect
Parameters:
dragged - the component being dropped
x - the x coordinate of the drop
y - the y coordinate of the drop
addPullToRefresh
public void addPullToRefresh(Runnable task)
This method adds a refresh task to the Component, the task will be executed if the
user has pulled the scroll beyond a certain height.
Parameters:
Method Detail
1947
If this Component is focused, the pointer dragged event will call this method
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
isStickyDrag
protected boolean isStickyDrag()
If this Component is focused, the pointer pressed event will call this method
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
isDragAndDropOperation
protected boolean isDragAndDropOperation(int x,
int y)
If this Component is focused, the pointer pressed event will call this method
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerReleased
public void pointerReleased(int[] x,
int[] y)
If this Component is focused, the pointer released event will call this method
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
longPointerPress
public void longPointerPress(int x,
int y)
If this Component is focused this method is invoked when the user presses and holds
the pointer on the Component
Method Detail
1948
If this Component is focused, the pointer released event will call this method
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
setTensileDragEnabled
public void setTensileDragEnabled(boolean tensileDragEnabled)
Indicates whether tensile drag (dragging beyond the boundry of the component and
snapping back) is enabled for this component.
Parameters:
tensileDragEnabled - true to enable tensile drag
isTensileDragEnabled
public boolean isTensileDragEnabled()
Indicates whether tensile drag (dragging beyond the boundry of the component and
snapping back) is enabled for this component.
Returns:
true when tensile drag is enabled
addDropListener
public void addDropListener(ActionListener l)
Binds an action listener to drop events which are invoked when this component is
dropped on a target
Parameters:
l - the callback
removeDropListener
public void removeDropListener(ActionListener l)
Removes an action listener to drop events which are invoked when this component is
dropped on a target
Parameters:
l - the callback
addDragOverListener
public void addDragOverListener(ActionListener l)
Callback indicating that the drag has finished either via drop or by releasing the
component
Parameters:
x - the x location
y - the y location
Method Detail
1949
This method returns the dragging speed based on the latest dragged events
Parameters:
vertical - indicates what axis speed is required
Returns:
the dragging speed
getStyle
public Style getStyle()
Returns the current Component Style allowing code to draw the current component,
you should normally use getUnselected/Pressed/DisabledStyle() and not this method
since it will return different values based on component state.
Returns:
the component Style object
getPressedStyle
public Style getPressedStyle()
Returns the Component Style for the pressed state allowing us to manipulate the look
of the component when it is pressed
Returns:
Method Detail
1950
Sets the Component Style for the pressed state allowing us to manipulate the look of
the component when it is pressed
Parameters:
style - the component Style object
getUnselectedStyle
public Style getUnselectedStyle()
Returns the Component Style for the unselected mode allowing us to manipulate the
look of the component
Returns:
the component Style object
getSelectedStyle
public Style getSelectedStyle()
Returns the Component Style for the selected state allowing us to manipulate the
look of the component when it owns focus
Returns:
the component Style object
getDisabledStyle
public Style getDisabledStyle()
Returns the Component Style for the disabled state allowing us to manipulate the
look of the component when its disabled
Returns:
the component Style object
setUnselectedStyle
public void setUnselectedStyle(Style style)
Changes the Component Style by replacing the Component Style with the given Style
Parameters:
style - the component Style object
setSelectedStyle
public void setSelectedStyle(Style style)
Changes the Component selected Style by replacing the Component Style with the
given Style
Parameters:
style - the component Style object
setDisabledStyle
public void setDisabledStyle(Style style)
Changes the Component disalbed Style by replacing the Component Style with the
given Style
Parameters:
style - the component Style object
installDefaultPainter
protected void installDefaultPainter(Style s)
Allows subclasses to create their own custom style types and install the background
painter into them
Parameters:
s - the custom style
Method Detail
1951
Changes the current component to the focused component, will work only for a
component that belongs to a parent form.
toString
public String toString()
Returns a string representing the state of this component. This method is intended to
be used only for debugging purposes, and the content and format of the returned
string may vary between implementations. The returned string may be empty but may
not be null.
Returns:
a string representation of this component's state
refreshTheme
public void refreshTheme()
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
refreshTheme
public void refreshTheme(boolean merge)
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Parameters:
merge - indicates if the current styles should be merged with the new styles
refreshTheme
protected void refreshTheme(String id,
boolean merge)
Indicates whether we are in the middle of a drag operation, this method allows
developers overriding the pointer released events to know when this is a drag
operation.
Returns:
true if we are in the middle of a drag; otherwise false
getGridPosY
protected int getGridPosY()
Method Detail
1952
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Returns:
true if a repaint is desired or false if no repaint is necessary
scrollRectToVisible
protected void scrollRectToVisible(Rectangle rect,
Component coordinateSpace)
Makes sure the component is visible in the scroll if this container is scrollable
Parameters:
rect - the rectangle that need to be visible
coordinateSpace - the component according to whose coordinates rect is
defined. Rect's x/y are relative to that component (they are not absolute).
scrollRectToVisible
public void scrollRectToVisible(int x,
int y,
int width,
int height,
Component coordinateSpace)
Makes sure the component is visible in the scroll if this container is scrollable
Parameters:
xywidth height coordinateSpace - the component according to whose coordinates rect is
defined. Rect's x/y are relative to that component (they are not absolute).
paintBorder
protected void paintBorder(Graphics g)
Draws the component border if such a border exists. The border unlike the content of
the component will not be affected by scrolling for a scrollable component.
Parameters:
g - graphics context on which the border is painted
paintBorderBackground
protected void paintBorderBackground(Graphics g)
Used as an optimization to mark that this component is currently being used as a cell
renderer
Parameters:
Method Detail
1953
cell renderer
isCellRenderer
public boolean isCellRenderer()
Used as an optimization to mark that this component is currently being used as a cell
renderer
Returns:
true is this component is currently being used as a cell renderer
isScrollVisible
public boolean isScrollVisible()
This is a callback method to inform the Component when it's been laidout on the
parent Container
deinitialize
protected void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
initComponent
protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
isInitialized
protected boolean isInitialized()
Method Detail
1954
Allows us to determine which component will receive focus next when traversing with
the down key
Returns:
the next focus component
setNextFocusDown
public void setNextFocusDown(Component nextFocusDown)
Allows us to determine which component will receive focus next when traversing with
the down key
Parameters:
nextFocusDown - the next focus component
getNextFocusUp
public Component getNextFocusUp()
Allows us to determine which component will receive focus next when traversing with
the up key.
Returns:
the nxt focus component
setNextFocusUp
public void setNextFocusUp(Component nextFocusUp)
Allows us to determine which component will receive focus next when traversing with
the up key, this method doesn't affect the general focus behavior.
Parameters:
nextFocusUp - next focus component
getNextFocusLeft
public Component getNextFocusLeft()
Allows us to determine which component will receive focus next when traversing with
the left key.
Returns:
the next focus component
setNextFocusLeft
public void setNextFocusLeft(Component nextFocusLeft)
Allows us to determine which component will receive focus next when traversing with
the left key, this method doesn't affect the general focus behavior.
Parameters:
nextFocusLeft - the next focus component
getNextFocusRight
public Component getNextFocusRight()
Method Detail
1955
Allows us to determine which component will receive focus next when traversing with
the right key
Parameters:
nextFocusRight - the next focus component
isEnabled
public boolean isEnabled()
A component name allows us to easily identify the component within a dynamic UI.
Returns:
name of the component
setName
public void setName(String name)
A component name allows us to easily identify the component within a dynamic UI.
Parameters:
name - a name for the component
initCustomStyle
protected void initCustomStyle(Style s)
Allows components to create a style of their own, this method binds the listener to the
style and installs a bg painter
Parameters:
s - style to initialize
deinitializeCustomStyle
protected void deinitializeCustomStyle(Style s)
Allows components to create a style of their own, this method cleans up state for the
given style
Parameters:
s - style no longer used
isRTL
public boolean isRTL()
Method Detail
1956
Elaborate components might not provide tactile feedback for all their areas (e.g. Lists)
this method defaults to returning the value of isTactileTouch
Parameters:
x - the x position
y - the y position
Returns:
True if the device should vibrate
isTactileTouch
public boolean isTactileTouch()
Indicates whether the component should "trigger" tactile touch when pressed by the
user in a touch screen UI.
Returns:
the tactileTouch
setTactileTouch
public void setTactileTouch(boolean tactileTouch)
Indicates whether the component should "trigger" tactile touch when pressed by the
user in a touch screen UI.
Parameters:
tactileTouch - true to trigger vibration when the component is pressed
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Parameters:
Method Detail
1957
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
paintLockRelease
public void paintLockRelease()
Releases the paint lock image to allow paint to work as usual, see
paintLock(boolean) for details
paintLock
public Image paintLock(boolean hardLock)
This method locks the component so it will always paint the given image instead of
running through its paint logic. This is useful when running transitions that might be
quite expensive on the device. A lock should be released using paintLockRelease(), it
is implicitly released when a component is deinitialized although a component doesn't
need to be initialized to be locked!
If the component is not opaque null is always returned!
Duplicate calls to this method won't produce duplicate locks, in case of a soft lock the
return value will always be null.
Parameters:
- indicates whether the lock uses a hard or a soft reference to the
image
Returns:
the image in case of a hard lock
isSnapToGrid
hardLock
Indicates whether scrolling this component should jump to a specific location in a grid
Returns:
the snapToGrid
setSnapToGrid
public void setSnapToGrid(boolean snapToGrid)
Indicates whether scrolling this component should jump to a specific location in a grid
Parameters:
snapToGrid - the snapToGrid to set
shouldBlockSideSwipe
protected boolean shouldBlockSideSwipe()
A component that might need side swipe such as the slider could block it from being
used for some other purpose when on top of said component.
isFlatten
public boolean isFlatten()
Makes the component effectively opaque by blending the backgrounds into an image
in memory so the layer of underlying components is only drawn once when this
Method Detail
1958
Makes the component effectively opaque by blending the backgrounds into an image
in memory so the layer of underlying components is only drawn once when this
component is repainted. This does have a significant memory overhead.
Parameters:
flatten - the flatten value
getTensileLength
public int getTensileLength()
This property is useful for blocking in z-order touch events, sometimes we might want
to grab touch events in a specific component without making it focusable.
Returns:
the grabsPointerEvents
setGrabsPointerEvents
public void setGrabsPointerEvents(boolean grabsPointerEvents)
This property is useful for blocking in z-order touch events, sometimes we might want
to grab touch events in a specific component without making it focusable.
Parameters:
grabsPointerEvents - the grabsPointerEvents to set
getScrollOpacityChangeSpeed
public int getScrollOpacityChangeSpeed()
Grows or shrinks this component to its new preferred size, this method essentially
takes a component whose preferred size has changed and creates a "growing" effect
that lasts for the duration. Notice that some components (such as text areas) don't
report proper preferred size untill they are laid out once. Hence the first time around a
text area (or container containing a text area) will not produce the expected effect.
This can be solved by invoking revalidate before the call to this method only the first
time around!
Method Detail
1959
isAlwaysTensile
public boolean isAlwaysTensile()
Enable the tensile drag to work even when a component doesn't have a scroll
showable (scrollable flag still needs to be set to true)
Returns:
the alwaysTensile
setAlwaysTensile
public void setAlwaysTensile(boolean alwaysTensile)
Enable the tensile drag to work even when a component doesn't have a scroll
showable (scrollable flag still needs to be set to true)
Parameters:
alwaysTensile - the alwaysTensile to set
isDraggable
public boolean isDraggable()
Indicates whether this component can be dragged in a drag and drop operation rather
than scroll the parent
Returns:
the draggable state
setDraggable
public void setDraggable(boolean draggable)
Indicates whether this component can be dragged in a drag and drop operation rather
than scroll the parent
Parameters:
draggable - the draggable to set
isDropTarget
public boolean isDropTarget()
Indicates whether this component can receive dropped components into it, notice that
when dropping on a component or container the parents will be checked recursively
to find a valid drop target
Returns:
the dropTarget state
setDropTarget
public void setDropTarget(boolean dropTarget)
Indicates whether this component can receive dropped components into it, notice that
when dropping on a component or container the parents will be checked recursively
to find a valid drop target
Parameters:
dropTarget - the dropTarget to set
isHideInPortrait
public boolean isHideInPortrait()
Indicates that this component and all its children should be hidden when the device is
switched to portrait mode
Returns:
the hideInPortrait
setHideInPortrait
public void setHideInPortrait(boolean hideInPortrait)
Indicates that this component and all its children should be hidden when the device is
switched to portrait mode
Parameters:
Method Detail
1960
cancelRepaints
protected void cancelRepaints()
Returns the names of the properties within this component that can be bound for
persistence, the order of these names mean that the first one will be the first bound
Returns:
a string array of property names or null
getBindablePropertyTypes
public Class[] getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
Returns:
the class for binding
bindProperty
public void bindProperty(String prop,
BindTarget target)
Sets the value of a bound property within this component, notice that this method
MUST NOT fire the property change event when invoked to prevent recursion!
Parameters:
prop - the property whose value should be set
value - the value
getCloudBoundProperty
public String getCloudBoundProperty()
Indicates the property within this component that should be bound to the cloud object
Returns:
the cloudBoundProperty
Method Detail
1961
Indicates the property within this component that should be bound to the cloud object
Parameters:
cloudBoundProperty - the cloudBoundProperty to set
getCloudDestinationProperty
public String getCloudDestinationProperty()
Some components may optionally generate a state which can then be restored using
setCompnentState(). This method is used by the UIBuilder.
Returns:
the component state or null for undefined state.
setHidden
public void setHidden(boolean b,
boolean changeMargin)
Makes the components preferred size equal 0 when hidden and restores it to the
default size when not. This method also optionally sets the margin to 0 so the
component will be truly hidden
Parameters:
b - true to hide the component and false to show it
changeMargin - indicates margin should be set to 0
setHidden
public void setHidden(boolean b)
Makes the components preferred size equal 0 when hidden and restores it to the
default size when not. Also toggles the UIID to "Container" and back to allow
padding/margin to be removed. Since the visible flag just hides the component
without "removing" the space it occupies this is the flag that can be used to truly hide
a component within the UI.
Parameters:
b - true to hide the component and false to show it
isHidden
public boolean isHidden()
If getComponentState returned a value the setter can update the value and restore
the prior state.
Parameters:
state - the non-null state
Method Detail
1962
Class Command
java.lang.Object
com.codename1.ui.Command
All Implemented Interfaces:
ActionListener
Direct Known Subclasses:
NavigationCommand, ShareService
public class
extends Object
implements ActionListener
The Command class provides a useful extension to the ActionListener interface in cases where the
same functionality may be accessed by several controls.
Constructor Summary
Constructor and Description
Command(String command)
Method Summary
Modifier
and Type
void
static
Command
boolean
Creates a new command instance that encapsulates the action listener and
details, the main value of this approach is in our ability to write commands using
the shorthand lambda syntax of Java 8.
equals(Object obj)
Object
String
The client properties are a useful way to associate meta-data with a command
without subclassing
getCommandName()
Image
Image
int
Image
Class Command
Indicates the icon that is displayed on the button when the button is in the
disabled state
getIcon()
1963
Indicates the icon that is displayed on the button when the button is in rolled
over state
Image
hashCode()
int
boolean
boolean
Indicates whether this command causes the dialog to dispose implicitly, defaults
to true
isEnabled()
The client properties are a useful way to associate meta-data with a command
without sub classing
void
setCommandName(String command)
void
Indicates the icon that is displayed on the button when the button is in the
disabled state
void
setDisposesDialog(boolean disposesDialog)
Indicates whether this command causes the dialog to dispose implicitly, defaults
to true
void
setEnabled(boolean enabled)
void
void
Indicates the icon that is displayed on the button when the button is in pressed
state
void
setRolloverIcon(Image rolloverIcon)
Indicates the icon that is displayed on the button when the button is in rolled
over state
void
String
toString()
Constructor Detail
Command
public Command(String command)
Method Summary
1964
Method Detail
getId
public int getId()
Constructor Detail
1965
Indicates the icon that is displayed on the button when the button is in pressed state
Returns:
icon used
getDisabledIcon
public Image getDisabledIcon()
Indicates the icon that is displayed on the button when the button is in the disabled
state
Returns:
icon used
getRolloverIcon
public Image getRolloverIcon()
Indicates the icon that is displayed on the button when the button is in rolled over
state
Returns:
icon used
setRolloverIcon
public void setRolloverIcon(Image rolloverIcon)
Indicates the icon that is displayed on the button when the button is in rolled over
state
Parameters:
rolloverIcon - icon to use
setPressedIcon
public void setPressedIcon(Image pressedIcon)
Indicates the icon that is displayed on the button when the button is in pressed state
Parameters:
pressedIcon - icon used
setDisabledIcon
public void setDisabledIcon(Image disabledIcon)
Indicates the icon that is displayed on the button when the button is in the disabled
state
Parameters:
disabledIcon - icon used
equals
public boolean equals(Object obj)
Method Detail
1966
Indicates whether this command causes the dialog to dispose implicitly, defaults to
true
isDisposesDialog
public boolean isDisposesDialog()
Indicates whether this command causes the dialog to dispose implicitly, defaults to
true
isEnabled
public boolean isEnabled()
The client properties are a useful way to associate meta-data with a command
without subclassing
Parameters:
key - an arbitrary user key
Returns:
an arbitrary user object
putClientProperty
public void putClientProperty(String key,
Object value)
The client properties are a useful way to associate meta-data with a command
without sub classing
Parameters:
key - an arbitrary user key
value - an arbitrary user object, null to remove
create
public static Command create(String name,
Image icon,
ActionListener ev)
Creates a new command instance that encapsulates the action listener and details,
the main value of this approach is in our ability to write commands using the
shorthand lambda syntax of Java 8.
Parameters:
Method Detail
1967
Returns:
a newly created Command instance
Method Detail
1968
Class ComboBox<T>
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.List<T>
com.codename1.ui.ComboBox<T>
All Implemented Interfaces:
Animation, StyleListener
public class
extends List<T>
A ComboBox is a list that allows only one selection at a time, when a user clicks the ComboBox a popup
button with the full list of elements allows the selection of a single element. The ComboBox is driven by
the list model and allows all the renderer features of the List as well.
The ComboBox is notoriously hard to style properly as it relies on a complex dynamic of popup renderer
and instantly visible renderer. The UIID for the ComboBox is "ComboBox" however if you set it to
something else all the other UIID's will also change their prefix. E.g. the "ComboBoxPopup" UIID will
become "MyNewUIIDPopup".
The combo box defines the following UIID's by default:
ComboBox
ComboBoxItem
ComboBoxFocus
PopupContentPane
PopupItem
PopupFocus
This class also defines theme constants that allow some native themes to manipulate its behavior
e.g.:
popupTitleBool - shows the "label for" value as the title of the popup dialog
popupCancelBodyBool - Adds a cancel button into the popup dialog
centeredPopupBool - shows the popup dialog in the center of the screen instead of under the
popup
otherPopupRendererBool - Uses a different list cell render for the popup than the one used
for the ComboBox itself. When this is false PopupItem & PopupFocus become irrelevant. Notice
that the Android native theme defines this to true.
iOS doesn't use combo boxes as part of its UI paradigm. Its available there mostly in web
applications and feels unnatural in iOS which is why we recommend using the Picker class.
The sample code below uses the GenericListCellRenderer to create a richer ComboBox UI.
public void showComboForm() {
Form hi = new Form("ComboBox", new BoxLayout(BoxLayout.Y_AXIS));
ComboBox<Map<String, Object>> combo = new ComboBox<> (
createListEntry("A Game of Thrones", "1996"),
createListEntry("A Clash Of Kings", "1998"),
createListEntry("A Storm Of Swords", "2000"),
createListEntry("A Feast For Crows", "2005"),
createListEntry("A Dance With Dragons", "2011"),
createListEntry("The Winds of Winter", "2016 (please, please, please)"),
createListEntry("A Dream of Spring", "Ugh"));
combo.setRenderer(new GenericListCellRenderer<>(new MultiButton(), new MultiButton()));
hi.show();
}
private Map<String, Object> createListEntry(String name, String date) {
Map<String, Object> entry = new HashMap<>();
entry.put("Line1", name);
entry.put("Line2", date);
return entry;
}
Class ComboBox<T>
1969
See Also:
List
Field Summary
Constructor Summary
Constructor and Description
ComboBox()
Method Summary
Modifier
and Type
Field Summary
protected
Dimension
calcPreferredSize()
protected
Dialog
createPopupDialog(List<T> l)
protected
List<T>
createPopupList()
protected
void
fireClicked()
1970
int
The baseline for the component text according to which it should be aligned
with other components for best visual look.
getOrientation()
Rectangle
protected
Rectangle
Returns the component bounds for scrolling which might differ from the
getBounds for large components e.g.
isActAsSpinnerDialog()
boolean
When this flag is active the combo box acts as a button that opens a dialog that
looks like a spinner this allows creating user interfaces for touch devices where
a spinner UI approach is more common than a combo box paradigm.
isDefaultActAsSpinnerDialog()
static
boolean
static
boolean
When this flag is active the combo box acts as a button that opens a dialog that
looks like a spinner this allows creating user interfaces for touch devices where
a spinner UI approach is more common than a combo box paradigm.
isDefaultIncludeSelectCancel()
Indicates whethe the soft buttons for select/cancel should appear for the combo
box by default
isIncludeSelectCancel()
boolean
void
protected
void
Indicates whethe the soft buttons for select/cancel should appear for the combo
box
keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
laidOut()
This is a callback method to inform the Component when it's been laidout on
the parent Container
paint(Graphics g)
void
void
If this Component is focused, the pointer dragged event will call this method
pointerHover(int[] x, int[] y)
void
Invoked for devices where the pointer can hover without actually clicking the
display.
pointerHoverReleased(int[] x, int[] y)
void
void
void
Invoked for devices where the pointer can hover without actually clicking the
display.
pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method
pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method
setActAsSpinnerDialog(boolean actAsSpinnerDialog)
void
When this flag is active the combo box acts as a button that opens a dialog that
looks like a spinner this allows creating user interfaces for touch devices where
a spinner UI approach is more common than a combo box paradigm.
setDefaultActAsSpinnerDialog(boolean aDefaultActAsSpinnerDialog)
static
void
When this flag is active the combo box acts as a button that opens a dialog that
looks like a spinner this allows creating user interfaces for touch devices where
a spinner UI approach is more common than a combo box paradigm.
setDefaultIncludeSelectCancel(boolean aDefaultIncludeSelectCancel)
Method Summary
1971
static
void
setIncludeSelectCancel(boolean includeSelectCancel)
Indicates whethe the soft buttons for select/cancel should appear for the combo
box
void
setSelectedIndex(int selection)
Sets the current selected offset in the list, by default this implementation will
scroll the list to the selection if the selection is outside of the screen
void
void
void
protected
Command
Shows the popup dialog for the combo box and returns the resulting command.
1972
Constructor Detail
ComboBox
public ComboBox(Vector<T> items)
Method Detail
isDefaultActAsSpinnerDialog
public static boolean isDefaultActAsSpinnerDialog()
When this flag is active the combo box acts as a button that opens a dialog that looks
like a spinner this allows creating user interfaces for touch devices where a spinner
UI approach is more common than a combo box paradigm.
Returns:
the defaultActAsSpinnerDialog
1973
When this flag is active the combo box acts as a button that opens a dialog that looks
like a spinner this allows creating user interfaces for touch devices where a spinner
UI approach is more common than a combo box paradigm.
Parameters:
aDefaultActAsSpinnerDialog - the defaultActAsSpinnerDialog to set
setUIID
public void setUIID(String uiid)
This method sets the Component the Unique identifier. This method should be used
before a component has been initialized
Overrides:
setUIID in class Component
Parameters:
uiid - UIID unique identifier for component type
getBaseline
public int getBaseline(int width,
int height)
The baseline for the component text according to which it should be aligned with
other components for best visual look.
Overrides:
getBaseline in class Component
Parameters:
width - the component width
height - the component height
Returns:
baseline value from the top of the component
laidOut
protected void laidOut()
This is a callback method to inform the Component when it's been laidout on the
parent Container
Overrides:
laidOut in class List<T>
getSelectedRect
public Rectangle getSelectedRect()
Returns the component bounds with absolute screen coordinates, for components
that include an internal selection behavior and are not containers (currently only List)
this method allows returning the position of the selection itself which is useful for
things such as the popup dialog and similar UI's that need to reference the position of
the selection externally
Overrides:
getSelectedRect in class List<T>
Returns:
the bounds of the component with absolute screen coordinates
getVisibleBounds
protected Rectangle getVisibleBounds()
Returns the component bounds for scrolling which might differ from the getBounds for
large components e.g. list.
Overrides:
getVisibleBounds in class List<T>
Returns:
the component bounds
See Also:
Component.getX(), Component.getY()
Method Detail
1974
Sets the current selected offset in the list, by default this implementation will scroll the
list to the selection if the selection is outside of the screen
Overrides:
setSelectedIndex in class List<T>
Parameters:
selection - the current selected offset in the list
setSelectedIndex
public void setSelectedIndex(int selection,
boolean scroll)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHover in class List<T>
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerHoverReleased
public void pointerHoverReleased(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHoverReleased in class List<T>
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
createPopupDialog
protected Dialog createPopupDialog(List<T> l)
Subclasses can override this method to change the creation of the dialog
Parameters:
l - the list of the popup
Returns:
a dialog instance
showPopupDialog
protected Command showPopupDialog(Dialog popupDialog,
List l)
Shows the popup dialog for the combo box and returns the resulting command. This
method can be overriden by subclasses to modify the behavior of the class.
Parameters:
popupDialog - the popup dialog
l - the list within
Returns:
the selected command
Method Detail
1975
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly. When overriding this
method you should also override isSelectableInteraction to indicate that a command
is placed appropriately on top of the fire key for 3 soft button phones.
Overrides:
fireClicked in class List<T>
createPopupList
protected List<T> createPopupList()
Creates the list object used within the popup dialog. This method allows subclasses
to customize the list creation for the popup dialog shown when the combo box is
pressed.
Returns:
a newly created list object used when the user presses the combo box.
keyReleased
public void keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class List<T>
Parameters:
keyCode - the key code value to indicate a physical key.
pointerPressed
public void pointerPressed(int x,
int y)
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class List<T>
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerDragged
public void pointerDragged(int x,
int y)
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class List<T>
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class List<T>
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
paint
public void paint(Graphics g)
Method Detail
1976
in interface Animation
Overrides:
paint in class List<T>
Parameters:
g - the component graphics
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class List<T>
Returns:
the calculated preferred size based on component content
getOrientation
public int getOrientation()
Indicates whethe the soft buttons for select/cancel should appear for the combo box
Returns:
true if the soft buttons for select/cancel should appear for the combo box
setIncludeSelectCancel
public void setIncludeSelectCancel(boolean includeSelectCancel)
Indicates whethe the soft buttons for select/cancel should appear for the combo box
Parameters:
includeSelectCancel - the new value
isDefaultIncludeSelectCancel
public static boolean isDefaultIncludeSelectCancel()
Indicates whethe the soft buttons for select/cancel should appear for the combo box
by default
Returns:
true if the soft buttons for select/cancel should appear for the combo box
setDefaultIncludeSelectCancel
Indicates whethe the soft buttons for select/cancel should appear for the combo box
by default
Parameters:
aDefaultIncludeSelectCancel - the new value
isActAsSpinnerDialog
public boolean isActAsSpinnerDialog()
When this flag is active the combo box acts as a button that opens a dialog that looks
like a spinner this allows creating user interfaces for touch devices where a spinner
UI approach is more common than a combo box paradigm.
Returns:
the actAsSpinnerDialog
Method Detail
1977
When this flag is active the combo box acts as a button that opens a dialog that looks
like a spinner this allows creating user interfaces for touch devices where a spinner
UI approach is more common than a combo box paradigm.
Parameters:
actAsSpinnerDialog - the actAsSpinnerDialog to set
Method Detail
1978
Class CheckBox
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.Button
com.codename1.ui.CheckBox
All Implemented Interfaces:
Animation, StyleListener
public class
extends Button
CheckBox is a button that can be selected or deselected and displays its state to the user. Check out
RadioButton for a more exclusive selection approach. Both components support a toggle button mode
using the Button.setToggle(boolean) API.
CheckBox cb1 = new CheckBox("CheckBox No Icon");
cb1.setSelected(true);
CheckBox cb2 = new CheckBox("CheckBox With Icon", icon);
CheckBox cb3 = new CheckBox("CheckBox Opposite True", icon);
CheckBox cb4 = new CheckBox("CheckBox Opposite False", icon);
cb3.setOppositeSide(true);
cb4.setOppositeSide(false);
RadioButton rb1 = new RadioButton("Radio 1");
RadioButton rb2 = new RadioButton("Radio 2");
RadioButton rb3 = new RadioButton("Radio 3", icon);
new ButtonGroup(rb1, rb2, rb3);
rb2.setSelected(true);
hi.add(cb1).add(cb2).add(cb3).add(cb4).add(rb1).add(rb2).add(rb3);
Field Summary
Class CheckBox
1979
Constructor Summary
Constructor and Description
CheckBox()
Method Summary
Modifier and
Type
void
protected
Dimension
static
CheckBox
static
CheckBox
static
CheckBox
Shorthand for creating the check box setting the icon/text and making it into a
toggle button
createToggle(String text)
Shorthand for creating the check box setting the icon/text and making it into a
toggle button
createToggle(String text, Image icon)
Shorthand for creating the check box setting the icon/text and making it into a
toggle button
getBindablePropertyNames()
String[]
Class[]
Object
boolean
boolean
Returns the names of the properties within this component that can be bound
for persistence, the order of these names mean that the first one will be the
first bound
getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
getBoundPropertyValue(String prop)
Places the check box on the opposite side at the far end
isSelected()
void
protected
String
1980
Makes sure the component is up to date with the current theme, ONLY
INVOKE THIS METHOD IF YOU CHANGED THE THEME!
void
released(int x, int y)
void
Sets the value of a bound property within this component, notice that this
method MUST NOT fire the property change event when invoked to prevent
recursion!
void
setOppositeSide(boolean oppositeSide)
void
Places the check box on the opposite side at the far end
setSelected(boolean selected)
void
void
Method Summary
1981
Constructor Detail
CheckBox
public CheckBox(String text)
Method Detail
isSelected
public boolean isSelected()
1982
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Button
Returns:
the calculated preferred size based on component content
paramString
protected String paramString()
Returns a string representing the state of this component. This method is intended to
be used only for debugging purposes, and the content and format of the returned
string may vary between implementations. The returned string may be empty but may
not be null.
Overrides:
paramString in class Label
Returns:
a string representation of this component's state
refreshTheme
public void refreshTheme(boolean merge)
Makes sure the component is up to date with the current theme, ONLY INVOKE THIS
METHOD IF YOU CHANGED THE THEME!
Overrides:
refreshTheme in class Component
Parameters:
merge - indicates if the current styles should be merged with the new styles
Method Detail
1983
Places the check box on the opposite side at the far end
Overrides:
isOppositeSide in class Button
Returns:
the oppositeSide
setOppositeSide
public void setOppositeSide(boolean oppositeSide)
Places the check box on the opposite side at the far end
Parameters:
oppositeSide - the oppositeSide to set
getBindablePropertyNames
public String[] getBindablePropertyNames()
Returns the names of the properties within this component that can be bound for
persistence, the order of these names mean that the first one will be the first bound
Overrides:
getBindablePropertyNames in class Label
Returns:
a string array of property names or null
getBindablePropertyTypes
public Class[] getBindablePropertyTypes()
Returns the types of the properties that are bindable within this component
Overrides:
getBindablePropertyTypes in class Label
Returns:
the class for binding
bindProperty
public void bindProperty(String prop,
BindTarget target)
Method Detail
1984
Sets the value of a bound property within this component, notice that this method
MUST NOT fire the property change event when invoked to prevent recursion!
Overrides:
setBoundPropertyValue in class Label
Parameters:
prop - the property whose value should be set
value - the value
createToggle
public static CheckBox createToggle(String text,
Image icon)
Shorthand for creating the check box setting the icon/text and making it into a toggle
button
Parameters:
text - the text for the button
icon - the icon for the button
Returns:
a check box
createToggle
public static CheckBox createToggle(String text)
Shorthand for creating the check box setting the icon/text and making it into a toggle
button
Parameters:
text - the text for the button
Returns:
a check box
createToggle
public static CheckBox createToggle(Image icon)
Shorthand for creating the check box setting the icon/text and making it into a toggle
button
Parameters:
icon - the icon for the button
Returns:
a check box
Method Detail
1985
Class Calendar
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.Calendar
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
Field Summary
Class Calendar
1986
Constructor Summary
Constructor and Description
Calendar()
Creates a new instance of Calendar set to the given date based on time since epoch (the
java.util.Date convention)
Calendar(long time, TimeZone tmz)
Creates a new instance of Calendar set to the given date based on time since epoch (the
java.util.Date convention)
Method Summary
Modifier
and Type
void
void
protected
Button
createDay()
protected
Label
createDayTitle(int day)
Date
Date
Style
Style
long
TimeZone
This method creates the Day Button Component for the Month View
This method creates the Day title Component for the Month View
getCurrentDate()
Returns the currently viewed date (as opposed to the selected date)
getDate()
Gets the selected style of the month view component within the calendar
getMonthViewUnSelectedStyle()
Gets the un selected style of the month view component within the calendar
getSelectedDay()
boolean
void
void
void
void
void
void
void
Sets the Calendar view on the given date, only the the month and year are
being considered.
setDate(Date d)
Sets the current date in the view and the selected date to be the same.
setMonthViewSelectedStyle(Style s)
Sets the selected style of the month view component within the calendar
setMonthViewUnSelectedStyle(Style s)
Sets the un selected style of the month view component within the calendar
1987
void
Sets the Calendar timezone, if not specified Calendar will use the default
timezone
void
void
protected
void
protected
void
Method Summary
1988
Constructor Detail
Calendar
public Calendar(long time)
Creates a new instance of Calendar set to the given date based on time since epoch
(the java.util.Date convention)
Parameters:
time - time since epoch
Calendar
public Calendar()
Creates a new instance of Calendar set to the given date based on time since epoch
(the java.util.Date convention)
Parameters:
time - time since epoch
tmz - a reference timezone
Method Detail
getSelectedDay
public long getSelectedDay()
1989
Sets the current date in the view and the selected date to be the same.
Parameters:
d - new date
setYearRange
public void setYearRange(int minYear,
int maxYear)
Sets the Calendar view on the given date, only the the month and year are being
considered.
Parameters:
d - the date to set the calendar view on.
getCurrentDate
public Date getCurrentDate()
Returns the currently viewed date (as opposed to the selected date)
Returns:
the currently viewed date
setTimeZone
public void setTimeZone(TimeZone tmz)
Sets the Calendar timezone, if not specified Calendar will use the default timezone
Parameters:
tmz - the timezone
getTimeZone
public TimeZone getTimeZone()
Sets the selected style of the month view component within the calendar
Parameters:
s - style for the month view
setMonthViewUnSelectedStyle
public void setMonthViewUnSelectedStyle(Style s)
Sets the un selected style of the month view component within the calendar
Parameters:
s - style for the month view
Method Detail
1990
Gets the selected style of the month view component within the calendar
Returns:
the style of the month view
getMonthViewUnSelectedStyle
public Style getMonthViewUnSelectedStyle()
Gets the un selected style of the month view component within the calendar
Returns:
the style of the month view
addActionListener
public void addActionListener(ActionListener l)
This flag determines if selected date can be changed by selecting an alternative date
Parameters:
changesSelectedDateEnabled - if true pressing on a date will cause the
selected date to be changed to the pressed one
isChangesSelectedDateEnabled
public boolean isChangesSelectedDateEnabled()
This flag determines if selected date can be changed by selecting an alternative date
Returns:
true if enabled
createDay
protected Button createDay()
This method creates the Day Button Component for the Month View
Returns:
a Button that corresponds to the Days Components
Method Detail
1991
This method creates the Day title Component for the Month View
Parameters:
day - the relevant day values are 0-6 where 0 is sunday.
Returns:
a Label that corresponds to the relevant Day
updateButtonDayDate
protected void updateButtonDayDate(Button dayButton,
int year,
int currentMonth,
int day)
Method Detail
1992
Class ButtonGroup
java.lang.Object
com.codename1.ui.ButtonGroup
public class
extends Object
This class is used to create a multiple-exclusion scope for RadioButton. Creating a set of RadioButton
components with the same ButtonGroup object means that only one RadioButton can be selected
among those within the specific ButtonGroup.
CheckBox cb1 = new CheckBox("CheckBox No Icon");
cb1.setSelected(true);
CheckBox cb2 = new CheckBox("CheckBox With Icon", icon);
CheckBox cb3 = new CheckBox("CheckBox Opposite True", icon);
CheckBox cb4 = new CheckBox("CheckBox Opposite False", icon);
cb3.setOppositeSide(true);
cb4.setOppositeSide(false);
RadioButton rb1 = new RadioButton("Radio 1");
RadioButton rb2 = new RadioButton("Radio 2");
RadioButton rb3 = new RadioButton("Radio 3", icon);
new ButtonGroup(rb1, rb2, rb3);
rb2.setSelected(true);
hi.add(cb1).add(cb2).add(cb3).add(cb4).add(rb1).add(rb2).add(rb3);
Constructor Summary
Constructor and Description
ButtonGroup()
Class ButtonGroup
1993
Summary
Modifier and
Type
void
void
Clears the selection such that none of the buttons in the ButtonGroup are
selected.
void
getButtonCount()
int
RadioButton
getRadioButton(int index)
int
boolean
isSelected()
void
void
void
Constructor Detail
ButtonGroup
public ButtonGroup()
Method Detail
addAll
public void addAll(RadioButton... rb)
Method Summary
1994
Clears the selection such that none of the buttons in the ButtonGroup are selected.
getButtonCount
public int getButtonCount()
Method Detail
1995
Class Button
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.Button
All Implemented Interfaces:
Animation, StyleListener
Direct Known Subclasses:
CheckBox, LikeButton, Picker, RadioButton, ScaleImageButton, ShareButton
public class
extends Label
Button is the base class for several UI widgets allowing clickability. It has 3 states: rollover, pressed
and the default state. Button can also have an ActionListener that react when the Button is clicked
or handle actions via a Command.
Button has the "Button" UIID by default.
Here is trivial usage of the Button API:
Form hi = new Form("Button");
Button b = new Button("My Button");
hi.add(b);
b.addActionListener((e) -> Log.p("Clicked"));
This code shows a common use case of making a button look like a hyperlink
Form hi = new Form("Button");
Button b = new Button("Link Button");
b.getAllStyles().setBorder(Border.createEmpty());
b.getAllStyles().setTextDecoration(Style.TEXT_DECORATION_UNDERLINE);
hi.add(b);
b.addActionListener((e) -> Log.p("Clicked"));
Class Button
1996
Summary
Modifier and
Type
static int
STATE_PRESSED
static int
static int
Constructor Summary
Constructor and Description
Button()
Method Summary
Modifier and
Type
void
boolean
protected
Dimension
protected
void
protected
void
Adds a listener to the button which will cause an event to dispatch on click
animate()
Invoked on the focus component to let it know that drag has started on the
parent container for the case of a component that doesn't support scrolling
fireClicked()
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly.
getActionListeners()
Vector
protected
Border
Field Summary
Deprecated.
use getListeners instead
getBorder()
1997
getCommand()
Image
Image
Collection
Indicates the icon that is displayed on the button when the button is in the
disabled state
getIconFromState()
Returns the icon for the button based on its current state
getListeners()
Image
int
Indicates the icon that is displayed on the button when the button is in
pressed state
getReleaseRadius()
Image
Indicates the icon that is displayed on the button when the button is in rolled
over state
getRolloverPressedIcon()
Image
int
boolean
boolean
Indicates the icon that is displayed on the button when the button is in
pressed state and is selected.
getState()
Places the check box or radio button on the opposite side at the far end
isSelectableInteraction()
protected
boolean
boolean
boolean
void
void
void
void
If this Component is focused, the key pressed event will call this method
keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
keyRepeated(int keyCode)
If this Component is focused, the key repeat event will call this method.
pointerDragged(int x, int y)
If this Component is focused, the pointer dragged event will call this method
pointerHover(int[] x, int[] y)
void
Invoked for devices where the pointer can hover without actually clicking the
display.
pointerHoverReleased(int[] x, int[] y)
void
void
void
void
void
void
Method Summary
Invoked for devices where the pointer can hover without actually clicking the
display.
pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method
pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method
pressed()
1998
void
protected
void
resetFocusable()
Deprecated.
use the Style alignment instead
void
setAutoRelease(boolean autoRelease)
Sets the auto released mode of this button, by default it's not an auto
released Button
void
setCommand(Command cmd)
void
Indicates the icon that is displayed on the button when the button is in the
disabled state
void
setPressedIcon(Image pressedIcon)
Indicates the icon that is displayed on the button when the button is in
pressed state
void
setReleaseRadius(int releaseRadius)
void
Indicates the icon that is displayed on the button when the button is in rolled
over state
void
setRolloverPressedIcon(Image rolloverPressedIcon)
Indicates the icon that is displayed on the button when the button is in
pressed state and is selected.
void
setToggle(boolean toggle)
void
1999
Field Detail
STATE_ROLLOVER
public static final int STATE_ROLLOVER
Indicates the rollover state of a button which is equivalent to focused for most uses
See Also:
Constant Field Values
STATE_PRESSED
public static final int STATE_PRESSED
Indicates the default state of a button which is neither pressed nor focused
See Also:
Constant Field Values
Constructor Detail
Button
public Button()
2000
Method Detail
setCommand
public void setCommand(Command cmd)
Indicates the icon that is displayed on the button when the button is in pressed state
Returns:
icon used
See Also:
STATE_PRESSED
Constructor Detail
2001
Indicates the icon that is displayed on the button when the button is in pressed state
and is selected. This is ONLY applicable to toggle buttons
Returns:
icon used
setRolloverPressedIcon
public void setRolloverPressedIcon(Image rolloverPressedIcon)
Indicates the icon that is displayed on the button when the button is in pressed state
and is selected. This is ONLY applicable to toggle buttons
Parameters:
rolloverPressedIcon - icon used
getDisabledIcon
public Image getDisabledIcon()
Indicates the icon that is displayed on the button when the button is in the disabled
state
Returns:
icon used
getRolloverIcon
public Image getRolloverIcon()
Indicates the icon that is displayed on the button when the button is in rolled over
state
Returns:
icon used
See Also:
STATE_ROLLOVER
setRolloverIcon
public void setRolloverIcon(Image rolloverIcon)
Indicates the icon that is displayed on the button when the button is in rolled over
state
Parameters:
rolloverIcon - icon to use
See Also:
STATE_ROLLOVER
setPressedIcon
public void setPressedIcon(Image pressedIcon)
Indicates the icon that is displayed on the button when the button is in pressed state
Parameters:
pressedIcon - icon used
See Also:
STATE_PRESSED
setDisabledIcon
public void setDisabledIcon(Image disabledIcon)
Indicates the icon that is displayed on the button when the button is in the disabled
state
Parameters:
disabledIcon - icon used
addActionListener
public void addActionListener(ActionListener l)
Adds a listener to the button which will cause an event to dispatch on click
Parameters:
Method Detail
2002
Returns the icon for the button based on its current state
Returns:
the button icon based on its current state
pressed
public void pressed()
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
keyReleased
public void keyReleased(int keyCode)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
Method Detail
2003
If this Component is focused, the key repeat event will call this method.
Overrides:
keyRepeated in class Component
Parameters:
keyCode - the key code value to indicate a physical key.
fireClicked
protected void fireClicked()
When working in 3 softbutton mode "fire" key (center softbutton) is sent to this
method in order to allow 3 button devices to work properly. When overriding this
method you should also override isSelectableInteraction to indicate that a command
is placed appropriately on top of the fire key for 3 soft button phones.
Overrides:
fireClicked in class Component
isSelectableInteraction
protected boolean isSelectableInteraction()
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHover in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerHoverReleased
public void pointerHoverReleased(int[] x,
int[] y)
Invoked for devices where the pointer can hover without actually clicking the display.
This is true for PC mouse pointer as well as some devices such as the BB storm.
Overrides:
pointerHoverReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerPressed
public void pointerPressed(int x,
int y)
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
Method Detail
2004
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
dragInitiated
protected void dragInitiated()
Invoked on the focus component to let it know that drag has started on the parent
container for the case of a component that doesn't support scrolling
Overrides:
dragInitiated in class Component
pointerDragged
public void pointerDragged(int x,
int y)
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Label
Returns:
the calculated preferred size based on component content
getBorder
protected Border getBorder()
Method Detail
2005
Toggle button mode is only relevant for checkboxes/radio buttons. When pressed a
toggle button stays pressed and when pressed again it moves to releleased state.
Returns:
the toggle
setToggle
public void setToggle(boolean toggle)
Toggle button mode is only relevant for checkboxes/radio buttons. When pressed a
toggle button stays pressed and when pressed again it moves to releleased state.
Setting toggle implicitly changes the UIID to "ToggleButton"
Parameters:
toggle - the toggle to set
animate
public boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Label
Returns:
true if a repaint is desired or false if no repaint is necessary
isOppositeSide
public boolean isOppositeSide()
Places the check box or radio button on the opposite side at the far end
Returns:
the oppositeSide
getReleaseRadius
public int getReleaseRadius()
Indicates a radius in which a pointer release will still have effect. Notice that this only
applies to pointer release events and not to pointer press events
Returns:
the releaseRadius
setReleaseRadius
public void setReleaseRadius(int releaseRadius)
Indicates a radius in which a pointer release will still have effect. Notice that this only
applies to pointer release events and not to pointer press events
Parameters:
releaseRadius - the releaseRadius to set
Method Detail
2006
Returns if this is an auto released Button. Auto released Buttons will are been
disarmed when a drag is happening within the Button.
Returns:
true if it's an auto released Button.
setAutoRelease
public void setAutoRelease(boolean autoRelease)
Sets the auto released mode of this button, by default it's not an auto released Button
Method Detail
2007
Class BrowserComponent
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.BrowserComponent
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
The browser component is an interface to an embeddable native platform browser on platforms that
support embedding the native browser in place, if you need wide compatibility and flexibility you
should check out the HTMLComponent which provides a lightweight 100% cross platform web
component.
This component will only work on platforms that support embedding a native browser which exclude
earlier versions of Blackberry devices and J2ME devices.
Its recommended that you place this component in a fixed position (none scrollable) on the screen
without other focusable components to prevent confusion between focus authority and allow the
component to scroll itself rather than CodenameOne making that decision for it.
On Android this component might show a native progress indicator dialog. You can disable that
functionality using the call.
The following code shows the basic usage of the BrowserComponent:
Form hi = new Form("Browser", new BorderLayout());
BrowserComponent browser = new BrowserComponent();
browser.setURL("https://www.codenameone.com/");
hi.add(BorderLayout.CENTER, browser);
Class BrowserComponent
2008
Field Summary
Field Summary
2009
Summary
Constructor and Description
BrowserComponent()
This constructor will work as expected when a browser component is supported, see
isNativeBrowserSupported()
Method Summary
Modifier and Type
void
void
void
void
void
Adds a listener to the given event type name, event type names are
platform specific but some must be fired for all platforms and will invoke
the action listener when the appropriate event loads
back()
String
Executes the given JavaScript and returns a result string from the
underlying platform where applicable
exposeInJavaScript(Object o, String name)
void
Deprecated.
this doesn't work in most platforms see issue 459 for details, use the
setBrowserNavigationCallback method instead
fireWebEvent(String type, ActionEvent ev)
void
void
BrowserNavigationCallback
String
String
boolean
boolean
static boolean
boolean
boolean
void
Constructor Summary
2010
void
setBrowserNavigationCallback(BrowserNavigationCallback callback)
Set the browser navigation callback which allows handling a case where
a URL invocation can be delegated to Java code.
void
setNativeScrollingEnabled(boolean b)
This flag allows disabling the native browser scrolling on platforms that
support it
void
void
void
void
setURL(String url)
void
Sets the page URL, jar: URL's must be supported by the implementation
setURLHierarchy(String url)
void
Sets the page URL while respecting the hierarchy of the html
stop()
void
Method Summary
2011
Constructor Detail
BrowserComponent
public BrowserComponent()
This constructor will work as expected when a browser component is supported, see
isNativeBrowserSupported()
Method Detail
setBrowserNavigationCallback
public void setBrowserNavigationCallback(BrowserNavigationCallback callback)
Set the browser navigation callback which allows handling a case where a URL
invocation can be delegated to Java code. This allows binding Java side functionality
to JavaScript functionality in the same way PhoneGap/Cordova work
Parameters:
callback - the callback interface
getBrowserNavigationCallback
public BrowserNavigationCallback getBrowserNavigationCallback()
The browser navigation callback interface allows handling a case where a URL
invocation can be delegated to Java code. This allows binding Java side functionality
to JavaScript functionality in the same way PhoneGap/Cordova work
Returns:
the callback interface
isNativeBrowserSupported
public static boolean isNativeBrowserSupported()
2012
This method allows customizing the properties of a web view in various ways
including platform specific settings. When a property isn't supported by a specific
platform it is just ignored.
Parameters:
key - see the documentation with the CodenameOne Implementation for
further details
value - see the documentation with the CodenameOne Implementation for
further details
getTitle
public String getTitle()
Sets the page URL, jar: URL's must be supported by the implementation
Parameters:
url - the URL
setURLHierarchy
public void setURLHierarchy(String url)
throws IOException
Sets the page URL while respecting the hierarchy of the html
Parameters:
url - the URL
Throws:
IOException
reload
public void reload()
Method Detail
2013
Some platforms require that you enable pinch to zoom explicitly. This method has no
effect if pinch to zoom isn't supported by the platform
Parameters:
e - true to enable pinch to zoom, false to disable it
isPinchToZoomEnabled
public boolean isPinchToZoomEnabled()
This flag allows disabling the native browser scrolling on platforms that support it
Parameters:
b - true to enable native scrolling, notice that non-native scrolling might be
problematic
isNativeScrollingEnabled
public boolean isNativeScrollingEnabled()
Adds a listener to the given event type name, event type names are platform specific
but some must be fired for all platforms and will invoke the action listener when the
appropriate event loads
Parameters:
type - platform specific but must support: onStart, onLoad, onError
Method Detail
2014
Used internally by the implementation to fire an event from the native browser widget
Parameters:
type - the type of the event
ev - the event
execute
public void execute(String javaScript)
Executes the given JavaScript and returns a result string from the underlying platform
where applicable
Parameters:
javaScript - the JavaScript code to execute
Returns:
the string returned from the Javascript call
exposeInJavaScript
public void exposeInJavaScript(Object o,
String name)
Deprecated. this doesn't work in most platforms see issue 459 for details, use the
setBrowserNavigationCallback method instead
Allows exposing the given object to JavaScript code so the JavaScript code can
invoke methods and access fields on the given object. Notice that on RIM devices
which don't support reflection this object must implement the propriatery Scriptable
interface
http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/script/Scriptable.html
Parameters:
o - the object to invoke, notice all public fields and methods would be
exposed to JavaScript
name - the name to expose within JavaScript
Method Detail
2015
Class AutoCompleteTextField
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.TextArea
com.codename1.ui.TextField
com.codename1.ui.AutoCompleteTextField
All Implemented Interfaces:
Animation, StyleListener
public class
extends TextField
An editable TextField with completion suggestions that show up in a drop down menu while the user
types in text.
This class uses the "TextField" UIID by default as well as "AutoCompletePopup" & "AutoCompleteList"
for the popup list details.
The sample below shows the more trivial use case for this widget:
Form hi = new Form("Auto Complete", new BoxLayout(BoxLayout.Y_AXIS));
AutoCompleteTextField ac = new AutoCompleteTextField("Short", "Shock", "Sholder", "Shrek");
ac.setMinimumElementsShownInPopup(5);
hi.add(ac);
Field Summary
Class AutoCompleteTextField
2016
Constructor Summary
Constructor and Description
AutoCompleteTextField()
The default constructor is useful for cases of filter subclasses overriding the
getSuggestionModel value as well as for the GUI builder
AutoCompleteTextField(ListModel<String> listModel)
Method Summary
Modifier and Type
void
Adds an action listener that fires an event when an entry in the auto-complete li
deinitialize()
protected void
protected boolean
String[]
int
Invoked to indicate that the component initialization is being reversed since the
the container hierarchy.
filter(String text)
Subclasses can override this method to perform more elaborate filter operations
getCompletion()
int
Indicates the minimum length of text in the field in order for a popup to show the
shown immediately for all text length if the number is 2 a popup will only appear
or more.
getPropertyNames()
String[]
String[]
Class[]
Object
protected
ListModel<String>
protected void
boolean
This method is here to workaround an XMLVM array type bug where property ty
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Obj
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
getSuggestionModel()
Allows subclasses to bind functionality that relies on fully initialized and "ready f
isStartsWithMode()
When enabled this makes the filter check that the string starts with rather than w
2017
void
If this Component is focused, the key pressed event will call this method
keyReleased(int k)
void
If this Component is focused, the key released event will call this method
removeListListener(ActionListener a)
void
Removes an action listener that fires an event when an entry in the auto-comple
setCompletion(String... completion)
void
void
void
Indicates the minimum length of text in the field in order for a popup to show the
shown immediately for all text length if the number is 2 a popup will only appear
or more.
void
String
Sets a new value to the given property, returns an error message if failed and n
setStartsWithMode(boolean startsWithMode)
void
When enabled this makes the filter check that the string starts with rather than w
setText(String text)
void
protected void
updateFilterList()
Method Summary
2018
Constructor Detail
AutoCompleteTextField
public AutoCompleteTextField(String... completion)
2019
The default constructor is useful for cases of filter subclasses overriding the
getSuggestionModel value as well as for the GUI builder
Method Detail
initComponent
protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
deinitialize
protected void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class TextField
setText
public void setText(String text)
Subclasses can override this method to perform more elaborate filter operations
Parameters:
text - the text to filter
Returns:
true if the filter has changed the list, false if it hasn't or is working
asynchronously
getSuggestionModel
protected ListModel<String> getSuggestionModel()
Constructor Detail
2020
keyPressed
public void keyPressed(int k)
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class TextField
Parameters:
k - the key code value to indicate a physical key.
keyReleased
public void keyReleased(int k)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class TextField
Parameters:
k - the key code value to indicate a physical key.
addListListener
public void addListListener(ActionListener a)
Adds an action listener that fires an event when an entry in the auto-complete list is
selected. Notice that this method will only take effect when the popup is reshown, if it
is invoked when a popup is already showing it will have no effect.
Parameters:
a - the listener
removeListListener
public void removeListListener(ActionListener a)
Removes an action listener that fires an event when an entry in the auto-complete list
is selected. Notice that this method will only take effect when the popup is reshown, if
it is invoked when a popup is already showing it will have no effect.
Parameters:
a - the listener
getMinimumLength
public int getMinimumLength()
Indicates the minimum length of text in the field in order for a popup to show the
default is 0 where a popup is shown immediately for all text length if the number is 2
a popup will only appear when there are two characters or more.
Returns:
the minimumLength
setMinimumLength
public void setMinimumLength(int minimumLength)
Indicates the minimum length of text in the field in order for a popup to show the
default is 0 where a popup is shown immediately for all text length if the number is 2
a popup will only appear when there are two characters or more.
Parameters:
minimumLength - the minimumLength to set
getMinimumElementsShownInPopup
public int getMinimumElementsShownInPopup()
Method Detail
2021
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setCompletion
public void setCompletion(String... completion)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Method Detail
2022
in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
isStartsWithMode
public boolean isStartsWithMode()
When enabled this makes the filter check that the string starts with rather than within
the index
Returns:
the startsWithMode
setStartsWithMode
public void setStartsWithMode(boolean startsWithMode)
When enabled this makes the filter check that the string starts with rather than within
the index
Parameters:
startsWithMode - the startsWithMode to set
Method Detail
2023
Class AnimationManager
java.lang.Object
com.codename1.ui.AnimationManager
Animation manager concentrates all of the animations for a given form into a single place that allows
us to manage all mutations to a Form in a way the prevents collisions between mutations. The one
type of animation that isn't handled by this class is the form level transition, replace transitions are
handled by this class.
Method Summary
Modifier
and Type
void
void
Adds the animation to the end of the animation queue and blocks the current
thread until the animation completes
void
flushAnimation(Runnable r)
void
boolean
isAnimating()
void
Performs a step animation as the user scrolls down/up the page e.g.
Method Detail
isAnimating
public boolean isAnimating()
Class AnimationManager
2024
Adds the animation to the end of the animation queue and blocks the current thread
until the animation completes
Parameters:
an - the animation to perform
addAnimation
public void addAnimation(ComponentAnimation an,
Runnable callback)
Performs a step animation as the user scrolls down/up the page e.g. slowly
converting a title UIID from a big visual representation to a smaller title for easier
navigation then back again when scrolling up
Parameters:
cna - the animation to bind to the scroll event
flushAnimation
public void flushAnimation(Runnable r)
Method Detail
2025
Interface UnitTest
All Known Implementing Classes:
AbstractTest
public interface
A Codename One unit test interface, you would normally like to derive from AbstractTest which is less
verbose and contains many helper methods.
Method Summary
Modifier and
Type
void
int
prepare()
void
boolean
boolean
runTest()
Returns true to indicate that the test expects to be executed on the EDT
Method Detail
runTest
boolean runTest()
throws Exception
Runs a unit test, if it returns true it passed. If it threw an exception or returned false it
failed.
Returns:
whether it passed
Throws:
Exception - thrown if it failed
prepare
void prepare()
Returns the time in milliseconds after which the test should be automatically failed.
Returns:
time in milliseconds
Interface UnitTest
2026
Returns true to indicate that the test expects to be executed on the EDT
Returns:
whether the test should execute on the EDT or the testing thread
Method Detail
2027
Class TestUtils
java.lang.Object
com.codename1.testing.TestUtils
public class
extends Object
Method Summary
Modifier and
Type
static void
static void
static void
static void
static void
static void
Class TestUtils
assertBool(boolean b)
2028
static void
static void
static void
Asserts that the given objects are equal using the first object's .equal()
method
assertEqual(Object expected, Object actual, String errorMessage)
static void
static void
static void
static void
static void
Asserts that the given objects are equal using the first object's .equal()
method
assertEqual(short expected, short actual)
static void
assertFalse(boolean value)
Asserts that we have a label with the given text baring the given name
assertLabel(String text)
Asserts that we have a label with the given text baring the given name
assertLabel(String name, String text)
Asserts that we have a label with the given text baring the given name
assertNoException(Runnable expression)
Method Summary
2029
static void
Asserts that the given objects are not equal using the first object's .equal()
method
assertNotEqual(Object expected, Object actual, String errorMessage)
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
static void
Method Summary
Asserts that the given objects are not equal using the first object's .equal()
method
assertNotEqual(short expected, short actual)
Asserts that the given parameters do not reference the same object
assertNotSame(Object expected, Object actual, String errorMessage)
Asserts that the given parameters do not reference the same object
assertNull(Object object)
Asserts that we have a label with the given text baring the given name
assertTextArea(String text)
Asserts that we have a label with the given text baring the given name
assertTextArea(String name, String text)
Asserts that we have a label with the given text baring the given name
assertTitle(String title)
2030
ensureVisible(int[] path)
Finds a component with the given name, works even with UI's that weren't
created with the GUI builder
findLabelText(String text)
Finds a component with the given name, works even with UI's that weren't
created with the GUI builder
findTextAreaText(String text)
Finds a component with the given name, works even with UI's that weren't
created with the GUI builder
gameKeyPress(int gameKey)
Gets the component from the current form based on its path.
goBack()
static void
static void
static void
static void
static void
Executes the back command for the current form, similarly to pressing the
back button
keyPress(int keyCode)
static void
static void
static void
static void
static void
static void
static
boolean
Method Summary
2031
static void
Waits for the given number of milliseconds even if the waiting is on the EDT
thread
waitForFormName(String name)
static void
Waits for a form change and if no form change occurred after a given timeout
then fail the test
waitForFormTitle(String title)
static void
Waits for a form change and if no form change occurred after a given timeout
then fail the test
Method Detail
setVerboseMode
public static void setVerboseMode(boolean v)
Waits for the given number of milliseconds even if the waiting is on the EDT thread
Parameters:
millis - the number of milliseconds to wait
findByName
public static Component findByName(String componentName)
Finds a component with the given name, works even with UI's that weren't created
with the GUI builder
Parameters:
componentName - the name of the component to find
Returns:
the component with the given name within the tree
selectInList
public static void selectInList(String listName,
int offset)
2032
Finds a component with the given name, works even with UI's that weren't created
with the GUI builder
Parameters:
text - the text of the label/button
Returns:
the component with the given label text within the tree
clickButtonByLabel
public static void clickButtonByLabel(String text)
Executes the back command for the current form, similarly to pressing the back
button
clickMenuItem
public static void clickMenuItem(String name)
Method Detail
2033
Waits for a form change and if no form change occurred after a given timeout then fail
the test
Parameters:
title - the title of the form to wait for
waitForFormName
public static void waitForFormName(String name)
Waits for a form change and if no form change occurred after a given timeout then fail
the test
Parameters:
name - the name of the form to wait for
screenshotTest
public static boolean screenshotTest(String screenshotName)
The screenshot test takes a screenshot of the screen and compares it to a prior
screenshot, if both are 100% identical the test passes. If not the test fails.
If this is the first time the test is run then the screenshot is taken and saved under the
given name in the devices storage. The test passes for this case but a warning is
printed to the console. The name will have .png appended to it so it will be identified.
This test will only work on devices that support the ImageIO API with PNG file format.
Parameters:
screenshotName - the name to use for the storage, must be unique!
Returns:
true if the screenshots are identical or no prior screenshot exists or if the test
can't be run on this device. False if a screenshot exists and it isn't 100%
identical.
log
public static void log(String t)
Method Detail
2034
A component press on a given named component at x/y where x and y are NOT
pixels but rather a number between 0 to 1 representing the percentage within the
component where the event took place. E.g. For a 100x100 component a press within
10,5 would be 0.1f, 0.05f.
Parameters:
x - the offset within the component as a number between 0 and 1
y - the offset within the component as a number between 0 and 1
componentName - the name of the component
pointerRelease
public static void pointerRelease(float x,
float y,
String componentName)
A component release on a given named component at x/y where x and y are NOT
pixels but rather a number between 0 to 1 representing the percentage within the
component where the event took place. E.g. For a 100x100 component a press within
10,5 would be 0.1f, 0.05f.
Parameters:
x - the offset within the component as a number between 0 and 1
y - the offset within the component as a number between 0 and 1
componentName - the name of the component
pointerDrag
public static void pointerDrag(float x,
float y,
String componentName)
A component drag on a given named component at x/y where x and y are NOT
pixels but rather a number between 0 to 1 representing the percentage within the
component where the event took place. E.g. For a 100x100 component a press within
10,5 would be 0.1f, 0.05f.
Parameters:
x - the offset within the component as a number between 0 and 1
y - the offset within the component as a number between 0 and 1
componentName - the name of the component
pointerPress
public static void pointerPress(float x,
float y,
int[] path)
A component press on a given named component at x/y where x and y are NOT
pixels but rather a number between 0 to 1 representing the percentage within the
component where the event took place. E.g. For a 100x100 component a press within
10,5 would be 0.1f, 0.05f.
Parameters:
x - the offset within the component as a number between 0 and 1
Method Detail
2035
pointerRelease
public static void pointerRelease(float x,
float y,
int[] path)
A component release on a given named component at x/y where x and y are NOT
pixels but rather a number between 0 to 1 representing the percentage within the
component where the event took place. E.g. For a 100x100 component a press within
10,5 would be 0.1f, 0.05f.
Parameters:
x - the offset within the component as a number between 0 and 1
y - the offset within the component as a number between 0 and 1
path - the path to the component
pointerDrag
public static void pointerDrag(float x,
float y,
int[] path)
A component drag on a given named component at x/y where x and y are NOT
pixels but rather a number between 0 to 1 representing the percentage within the
component where the event took place. E.g. For a 100x100 component a press within
10,5 would be 0.1f, 0.05f.
Parameters:
x - the offset within the component as a number between 0 and 1
y - the offset within the component as a number between 0 and 1
path - the path to the component
getComponentByPath
public static Component getComponentByPath(int[] path)
Gets the component from the current form based on its path. A path is a set of offsets
starting from the content pane and moving inwards so a path of { 0, 3 } would mean
that the first component within the Content pane (by index) is a Container whose 3rd
component (again by index) is the component we want.
Parameters:
path - an array
Returns:
a component
setText
public static void setText(String name,
String text)
Method Detail
2036
Method Detail
2037
Asserts that the given parameters do not reference the same object
assertNotSame
public static void assertNotSame(Object expected,
Object actual,
String errorMessage)
Asserts that the given parameters do not reference the same object
Parameters:
errorMessage - is a string describing the failure
assertEqual
public static void assertEqual(byte expected,
byte actual)
Method Detail
2038
Method Detail
2039
expected,
actual,
maxRelativeError,
errorMessage)
Asserts that the given objects are equal using the first object's .equal() method
assertEqual
public static void assertEqual(Object expected,
Object actual,
String errorMessage)
Asserts that the given objects are equal using the first object's .equal() method
Parameters:
errorMessage - is a string describing the failure
assertNotEqual
public static void assertNotEqual(byte expected,
byte actual)
Method Detail
2040
assertNotEqual
public static void assertNotEqual(long expected,
long actual,
double minRelativeError)
expected,
actual,
minRelativeError,
errorMessage)
Asserts that the given objects are not equal using the first object's .equal() method
assertNotEqual
public static void assertNotEqual(Object expected,
Object actual,
String errorMessage)
Asserts that the given objects are not equal using the first object's .equal() method
Parameters:
errorMessage - is a string describing the failure
assertArrayEqual
public static void assertArrayEqual(byte[] expected,
byte[] actual)
Method Detail
2041
expected,
actual,
maxRelativeError,
errorMessage)
Method Detail
2042
Method Detail
2043
Asserts that we have a label with the given text baring the given name
Parameters:
name - the name of the label
text - the text of the label
assertLabel
public static void assertLabel(int[] path,
String text)
Asserts that we have a label with the given text baring the given name
Parameters:
path - the path of the label
text - the text of the label
assertLabel
public static void assertLabel(String text)
Asserts that we have a label with the given text baring the given name
Parameters:
text - the text of the label
assertTextArea
public static void assertTextArea(String name,
String text)
Asserts that we have a label with the given text baring the given name
Parameters:
name - the name of the label
text - the text of the label
assertTextArea
public static void assertTextArea(int[] path,
String text)
Asserts that we have a label with the given text baring the given name
Parameters:
path - the path to the text area
text - the text of the label
Method Detail
2044
Asserts that we have a label with the given text baring the given name
Parameters:
text - the text of the label
findTextAreaText
public static TextArea findTextAreaText(String text)
Finds a component with the given name, works even with UI's that weren't created
with the GUI builder
Parameters:
text - the text of the label/button
Returns:
the component with the given TextArea text within the tree
Method Detail
2045
Class TestReporting
java.lang.Object
com.codename1.testing.TestReporting
Direct Known Subclasses:
JUnitXMLReporting
public class
extends Object
Test reports can be overriden to provide custom test reporting options you can replace the test
reporter on the device by sending the build argument
build.testReporter='com.x.MyTestReporterClass'.
Constructor Summary
Constructor and Description
TestReporting()
Method Summary
Modifier and Type
void
static
TestReporting
getInstance()
void
void
static void
setInstance(TestReporting i)
void
Callback to indicate the test execution has finished allowing for a report
to be generated if appropriate
void
writeReport(OutputStream os)
void
Constructor Detail
TestReporting
public TestReporting()
Class TestReporting
2046
Detail
getInstance
public static TestReporting getInstance()
testExecutionFinished
public void testExecutionFinished()
Callback to indicate the test execution has finished allowing for a report to be
generated if appropriate
Method Detail
2047
Class JUnitXMLReporting
java.lang.Object
com.codename1.testing.TestReporting
com.codename1.testing.JUnitXMLReporting
public class
extends TestReporting
Produces test reporting in the format of JUnit XML for compatibility with tools that consume JUnit test
case results see http://code.google.com/p/codenameone/issues/detail?id=446 for more details.
Constructor Summary
Constructor and Description
JUnitXMLReporting()
Method Summary
Modifier and
Type
void
void
void
void
Callback to indicate the test execution has finished allowing for a report to
be generated if appropriate
void
writeReport(OutputStream os)
void
Constructor Detail
JUnitXMLReporting
public JUnitXMLReporting()
Class JUnitXMLReporting
2048
Detail
startingTestCase
public void startingTestCase(UnitTest test)
testExecutionFinished
public void testExecutionFinished()
Callback to indicate the test execution has finished allowing for a report to be
generated if appropriate
Overrides:
testExecutionFinished in class TestReporting
Method Detail
2049
Class DeviceRunner
java.lang.Object
com.codename1.testing.DeviceRunner
Runs the test cases from the test build of the app, notice that this class is abstract since device/app
specific code can exist in the implementation
Constructor Summary
Constructor and Description
DeviceRunner()
Method Summary
Modifier and
Type
void
void
protected
abstract void
protected
abstract void
startApplicationInstance()
This method should cleanup the application so the next test case can
run on a clean application instance
Constructor Detail
DeviceRunner
public DeviceRunner()
Method Detail
runTests
public void runTests()
Class DeviceRunner
2050
This method should cleanup the application so the next test case can run on a clean
application instance
runTest
public void runTest(String testClassName)
Method Detail
2051
Class AbstractTest
java.lang.Object
com.codename1.testing.AbstractTest
All Implemented Interfaces:
UnitTest
A unit test class that simplifies the process of writing test cases for Codename One.
Constructor Summary
Constructor and Description
AbstractTest()
Method Summary
Modifier and
Type
void
void
This method just invokes the test utils method, it is here for convenience
assertArrayEqual(byte[] expected, byte[] actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
void
This method just invokes the test utils method, it is here for convenience
void
This method just invokes the test utils method, it is here for convenience
void
This method just invokes the test utils method, it is here for convenience
void
This method just invokes the test utils method, it is here for convenience
void
void
void
This method just invokes the test utils method, it is here for convenience
assertArrayEqual(int[] expected, int[] actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertArrayEqual(long[] expected, long[] actual,
long maxRelativeError)
This method just invokes the test utils method, it is here for convenience
void
This method just invokes the test utils method, it is here for convenience
void
void
This method just invokes the test utils method, it is here for convenience
assertArrayEqual(Object[] expected, Object[] actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
Class AbstractTest
2052
void
This method just invokes the test utils method, it is here for convenience
assertArrayEqual(short[] expected, short[] actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
void
void
void
void
void
assertBool(boolean b)
This method just invokes the test utils method, it is here for convenience
assertBool(boolean b, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertEqual(byte expected, byte actual)
This method just invokes the test utils method, it is here for convenience
assertEqual(byte expected, byte actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertEqual(double expected, double actual,
double maxRelativeError)
This method just invokes the test utils method, it is here for convenience
void
This method just invokes the test utils method, it is here for convenience
void
void
This method just invokes the test utils method, it is here for convenience
assertEqual(float expected, float actual, double maxRelativeError,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
void
void
void
void
void
void
void
void
void
void
This method just invokes the test utils method, it is here for convenience
assertEqual(int expected, int actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertEqual(long expected, long actual)
This method just invokes the test utils method, it is here for convenience
assertEqual(long expected, long actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertEqual(Object expected, Object actual)
This method just invokes the test utils method, it is here for convenience
assertEqual(Object expected, Object actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertEqual(short expected, short actual)
This method just invokes the test utils method, it is here for convenience
assertEqual(short expected, short actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertException(RuntimeException exception, Runnable expression)
This method just invokes the test utils method, it is here for convenience
assertException(RuntimeException exception, Runnable expression,
String message)
This method just invokes the test utils method, it is here for convenience
void
void
void
void
void
void
void
Method Summary
assertFalse(boolean value)
This method just invokes the test utils method, it is here for convenience
assertFalse(boolean value, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertLabel(int[] path, String text)
This method just invokes the test utils method, it is here for convenience
assertLabel(String text)
This method just invokes the test utils method, it is here for convenience
assertLabel(String name, String text)
This method just invokes the test utils method, it is here for convenience
assertNoException(Runnable expression)
This method just invokes the test utils method, it is here for convenience
assertNoException(Runnable expression, String message)
This method just invokes the test utils method, it is here for convenience
2053
void
This method just invokes the test utils method, it is here for convenience
assertNotEqual(byte expected, byte actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertNotEqual(double expected, double actual,
double minRelativeError)
This method just invokes the test utils method, it is here for convenience
void
This method just invokes the test utils method, it is here for convenience
void
This method just invokes the test utils method, it is here for convenience
void
This method just invokes the test utils method, it is here for convenience
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
Method Summary
This method just invokes the test utils method, it is here for convenience
assertNotEqual(int expected, int actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertNotEqual(long expected, long actual)
This method just invokes the test utils method, it is here for convenience
assertNotEqual(long expected, long actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertNotEqual(Object expected, Object actual)
This method just invokes the test utils method, it is here for convenience
assertNotEqual(Object expected, Object actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertNotEqual(short expected, short actual)
This method just invokes the test utils method, it is here for convenience
assertNotEqual(short expected, short actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertNotNull(Object object)
This method just invokes the test utils method, it is here for convenience
assertNotNull(Object object, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertNotSame(Object expected, Object actual)
This method just invokes the test utils method, it is here for convenience
assertNotSame(Object expected, Object actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertNull(Object object)
This method just invokes the test utils method, it is here for convenience
assertNull(Object object, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertSame(Object expected, Object actual)
This method just invokes the test utils method, it is here for convenience
assertSame(Object expected, Object actual, String errorMessage)
This method just invokes the test utils method, it is here for convenience
assertTextArea(int[] path, String text)
This method just invokes the test utils method, it is here for convenience
assertTextArea(String text)
This method just invokes the test utils method, it is here for convenience
assertTextArea(String name, String text)
This method just invokes the test utils method, it is here for convenience
assertTitle(String title)
This method just invokes the test utils method, it is here for convenience
assertTrue(boolean value)
This method just invokes the test utils method, it is here for convenience
assertTrue(boolean value, String errorMessage)
2054
cleanup()
This method just invokes the test utils method, it is here for convenience
clickButtonByName(String name)
This method just invokes the test utils method, it is here for convenience
clickButtonByPath(int[] path)
This method just invokes the test utils method, it is here for convenience
clickMenuItem(String name)
This method just invokes the test utils method, it is here for convenience
ensureVisible(Component c)
This method just invokes the test utils method, it is here for convenience
ensureVisible(int[] c)
This method just invokes the test utils method, it is here for convenience
ensureVisible(String c)
This method just invokes the test utils method, it is here for convenience
fail()
This method just invokes the test utils method, it is here for convenience
fail(String errorMessage)
This method just invokes the test utils method, it is here for convenience
findByName(String componentName)
This method just invokes the test utils method, it is here for convenience
findLabelText(String text)
This method just invokes the test utils method, it is here for convenience
findTextAreaText(String text)
This method just invokes the test utils method, it is here for convenience
gameKeyPress(int gameKey)
This method just invokes the test utils method, it is here for convenience
gameKeyRelease(int gameKey)
This method just invokes the test utils method, it is here for convenience
getComponentByPath(int[] path)
This method just invokes the test utils method, it is here for convenience
getTimeoutMillis()
int
void
void
void
void
void
void
void
void
void
void
Method Summary
This method just invokes the test utils method, it is here for convenience
keyPress(int keyCode)
This method just invokes the test utils method, it is here for convenience
keyRelease(int keyCode)
This method just invokes the test utils method, it is here for convenience
log(String t)
This method just invokes the test utils method, it is here for convenience
log(Throwable t)
This method just invokes the test utils method, it is here for convenience
pointerDrag(float x, float y, int[] path)
This method just invokes the test utils method, it is here for convenience
pointerDrag(float x, float y, String componentName)
This method just invokes the test utils method, it is here for convenience
pointerPress(float x, float y, int[] path)
This method just invokes the test utils method, it is here for convenience
pointerPress(float x, float y, String componentName)
This method just invokes the test utils method, it is here for convenience
pointerRelease(float x, float y, int[] path)
This method just invokes the test utils method, it is here for convenience
2055
void
This method just invokes the test utils method, it is here for convenience
prepare()
void
boolean
screenshotTest(String screenshotName)
This method just invokes the test utils method, it is here for convenience
selectInList(int[] path, int offset)
void
This method just invokes the test utils method, it is here for convenience
selectInList(String listName, int offset)
void
This method just invokes the test utils method, it is here for convenience
setText(int[] path, String text)
void
This method just invokes the test utils method, it is here for convenience
setText(String name, String text)
void
This method just invokes the test utils method, it is here for convenience
setVerboseMode(boolean v)
void
This method just invokes the test utils method, it is here for convenience
boolean
shouldExecuteOnEDT()
void
This method just invokes the test utils method, it is here for convenience
waitForFormName(String name)
void
This method just invokes the test utils method, it is here for convenience
waitForFormTitle(String title)
void
This method just invokes the test utils method, it is here for convenience
Constructor Detail
AbstractTest
public AbstractTest()
Method Detail
prepare
public void prepare()
2056
Returns false, default tests run in their own thread. Returns true to indicate that the
test expects to be executed on the EDT
Specified by:
shouldExecuteOnEDT in interface UnitTest
Returns:
whether the test should execute on the EDT or the testing thread
assertBool
public void assertBool(boolean b)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertBool
public void assertBool(boolean b,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
fail
public void fail()
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
fail
public void fail(String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertTrue
public void assertTrue(boolean value)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertTrue
public void assertTrue(boolean value,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
Method Detail
2057
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertFalse
public void assertFalse(boolean value,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNull
public void assertNull(Object object)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNull
public void assertNull(Object object,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotNull
public void assertNotNull(Object object)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotNull
public void assertNotNull(Object object,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertSame
public void assertSame(Object expected,
Object actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertSame
public void assertSame(Object expected,
Object actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotSame
public void assertNotSame(Object expected,
Object actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
Method Detail
2058
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(byte expected,
byte actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(byte expected,
byte actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(short expected,
short actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(short expected,
short actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(int expected,
int actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(int expected,
int actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(long expected,
long actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
Method Detail
2059
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(float expected,
float actual,
double maxRelativeError)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(float expected,
float actual,
double maxRelativeError,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(double expected,
double actual,
double maxRelativeError)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(double
double
double
String
expected,
actual,
maxRelativeError,
errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(Object expected,
Object actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertEqual
public void assertEqual(Object expected,
Object actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(byte expected,
byte actual)
This method just invokes the test utils method, it is here for convenience
See Also:
Method Detail
2060
assertNotEqual
public void assertNotEqual(byte expected,
byte actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(short expected,
short actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(short expected,
short actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(int expected,
int actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(int expected,
int actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(long expected,
long actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(long expected,
long actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(float expected,
float actual,
double minRelativeError)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
Method Detail
2061
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(double expected,
double actual,
double minRelativeError)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(double
double
double
String
expected,
actual,
minRelativeError,
errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(Object expected,
Object actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNotEqual
public void assertNotEqual(Object expected,
Object actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(byte[] expected,
byte[] actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(byte[] expected,
byte[] actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(short[] expected,
short[] actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
Method Detail
2062
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(int[] expected,
int[] actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(int[] expected,
int[] actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(long[] expected,
long[] actual,
long maxRelativeError)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(long[] expected,
long[] actual,
long maxRelativeError,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(float[] expected,
float[] actual,
double maxRelativeError)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(float[] expected,
float[] actual,
double maxRelativeError,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(double[] expected,
double[] actual,
double maxRelativeError)
This method just invokes the test utils method, it is here for convenience
Method Detail
2063
assertArrayEqual
public void assertArrayEqual(double[] expected,
double[] actual,
double maxRelativeError,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(Object[] expected,
Object[] actual)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertArrayEqual
public void assertArrayEqual(Object[] expected,
Object[] actual,
String errorMessage)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertException
public void assertException(RuntimeException exception,
Runnable expression)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertException
public void assertException(RuntimeException exception,
Runnable expression,
String message)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNoException
public void assertNoException(Runnable expression)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertNoException
public void assertNoException(Runnable expression,
String message)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
waitFor
public void waitFor(int millis)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
Method Detail
2064
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
findLabelText
public Label findLabelText(String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
clickButtonByLabel
public void clickButtonByLabel(String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
clickButtonByName
public void clickButtonByName(String name)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
clickButtonByPath
public void clickButtonByPath(int[] path)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
goBack
public void goBack()
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
clickMenuItem
public void clickMenuItem(String name)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
ensureVisible
public void ensureVisible(Component c)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
ensureVisible
public void ensureVisible(int[] c)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
ensureVisible
public void ensureVisible(String c)
This method just invokes the test utils method, it is here for convenience
See Also:
Method Detail
2065
waitForFormTitle
public void waitForFormTitle(String title)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
waitForFormName
public void waitForFormName(String name)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
log
public void log(String t)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
log
public void log(Throwable t)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
screenshotTest
public boolean screenshotTest(String screenshotName)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
keyPress
public void keyPress(int keyCode)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
keyRelease
public void keyRelease(int keyCode)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
gameKeyPress
public void gameKeyPress(int gameKey)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
gameKeyRelease
public void gameKeyRelease(int gameKey)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
pointerPress
public void pointerPress(float x,
float y,
String componentName)
Method Detail
2066
pointerRelease
public void pointerRelease(float x,
float y,
String componentName)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
pointerDrag
public void pointerDrag(float x,
float y,
String componentName)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
pointerPress
public void pointerPress(float x,
float y,
int[] path)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
pointerRelease
public void pointerRelease(float x,
float y,
int[] path)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
pointerDrag
public void pointerDrag(float x,
float y,
int[] path)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
getComponentByPath
public Component getComponentByPath(int[] path)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
setText
public void setText(String name,
String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
setText
public void setText(int[] path,
String text)
This method just invokes the test utils method, it is here for convenience
See Also:
Method Detail
2067
assertTitle
public void assertTitle(String title)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertLabel
public void assertLabel(String name,
String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertLabel
public void assertLabel(String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertLabel
public void assertLabel(int[] path,
String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertTextArea
public void assertTextArea(String name,
String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertTextArea
public void assertTextArea(int[] path,
String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
assertTextArea
public void assertTextArea(String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
findTextAreaText
public TextArea findTextAreaText(String text)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
setVerboseMode
public void setVerboseMode(boolean v)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
Method Detail
2068
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
selectInList
public void selectInList(int[] path,
int offset)
This method just invokes the test utils method, it is here for convenience
See Also:
TestUtils
Method Detail
2069
Interface URLCallback
public interface
In platforms that support opening an application via URL this interface can be implemented by the
main class to support such functionality. Notice that build argument must also include some
information, for more details check out this issue:
http://code.google.com/p/codenameone/issues/detail?id=379
Method Summary
Modifier and
Type
boolean
Indicates whether the application should handle the given URL, defaults
to true
Method Detail
shouldApplicationHandleURL
boolean shouldApplicationHandleURL(String url,
String caller)
Indicates whether the application should handle the given URL, defaults to true
Parameters:
url - the URL to handle
caller - the invoking application
Returns:
true to handle the URL, false otherwise
Interface URLCallback
2070
Class NativeLookup
java.lang.Object
com.codename1.system.NativeLookup
public class
extends Object
Creates an instance of the native interface which will call the underlying platform using the convention
documented in the package docs. To understand more about native interfaces you can check out this
quick "How Do I?" tutorial.
Alternatively you can dig deeper into this tutorial for integrating 3rd party native libraries.
Method Summary
Modifier and Type
static
NativeInterface
static void
Method Detail
create
public static NativeInterface create(Class c)
Creates an instance of the given native interface and returns it for user callbacks.
Parameters:
c - the class of the NativeInterface sub interface
Returns:
an instance of that interface that can be invoked or null if the native interface
isn't present on the underlying platform (e.g. simulator platform).
register
public static void register(Class ni,
Class cls)
Do NOT invoke this method. This method is invoked internally by the stub to register
the implementation class that matches a specific interface type.
Parameters:
ni - the native interface
cls - the stub class matching said interface
Method Detail
2071
Interface NativeInterface
public interface
This is a marker interface that should be extended by a user interface in order to indicate that said
interface is implemented in native code. To understand more about native interfaces you can check
out this quick "How Do I?" tutorial.
Alternatively you can dig deeper into this tutorial for integrating 3rd party native libraries.
Method Summary
Modifier and
Type
boolean
Method Detail
isSupported
boolean isSupported()
Method Detail
2072
Class DefaultCrashReporter
java.lang.Object
com.codename1.system.DefaultCrashReporter
All Implemented Interfaces:
CrashReport
public class
extends Object
implements CrashReport
A default implementation of the crash reporter that instantly sends the crash data to the server.
Method Summary
Modifier and Type
void
static String
static String
static String
static String
static void
static void
static void
static void
static void
getCheckboxText()
Method Detail
getErrorText
public static String getErrorText()
Method Detail
2073
Method Detail
2074
Method Detail
2075
Interface CrashReport
All Known Implementing Classes:
DefaultCrashReporter
public interface
Invoked to indicate that an exception occurred, it is up to the developer to decide whether to send the
device log to the server by invoking Log.sendLog(). Notice that sending a log only works for paid
accounts. This interface should be registered with the Display class.
Notice that exceptions will only be reported for threads created by Codename One using the API's
within the Display class, this will not work for exceptions within threads that are created by the new
Thread() API.
Method Summary
Modifier and Type
exception(Throwable t)
void
Method Detail
exception
void exception(Throwable t)
Interface CrashReport
2076
Class LoginCallback
java.lang.Object
com.codename1.social.LoginCallback
This class is used to indicate whether login was successful or not, it is an abstract class rather than
an interface in order to allow additional features in the future.
Constructor Summary
Constructor and Description
LoginCallback()
Method Summary
Modifier and Type
void
void
Constructor Detail
LoginCallback
public LoginCallback()
Method Detail
loginSuccessful
public void loginSuccessful()
Method Detail
2077
Class Login
java.lang.Object
com.codename1.social.Login
Direct Known Subclasses:
FacebookConnect, GoogleConnect
The Login abstract base class is used to simplify Oauth2 authentications services. Services can
override the default Oauth2 web login and offers the native login experience.
Constructor Summary
Constructor and Description
Login()
Method Summary
Modifier and
Type
protected
Oauth2
void
void
AccessToken
abstract
boolean
boolean
boolean
void
void
void
void
void
void
void
Method Detail
Sets the login callback that will receive event callback notification from the
API
setClientId(String id)
2078
void
void
This method tries to validate the last access token if exists, if the last token
is not valid anymore it will try to login the user in order to get a fresh token
The method blocks until a valid token has been granted
void
protected
abstract
boolean
validateToken(String token)
Returns true if the previous granted access token is still valid otherwise
false.
Constructor Detail
Login
public Login()
Method Detail
doLogin
public void doLogin()
Logs in the user. If the service has a native login it will try to use that, otherwise an
Oauth2 web login will be used.
doLogout
public void doLogout()
Indicates if the user is currently logged in. Subclasses that uses a native sdk to
login/logout should override this method.
Returns:
true if logged in
nativelogin
public void nativelogin()
Logs in the current user natively. Subclasses that uses a native sdk to login/logout
should override this method.
nativeLogout
public void nativeLogout()
Logs out the current user natively. Subclasses that uses a native sdk to login/logout
should override this method.
Method Summary
2079
Returns true if this service supports native login. If implementation returns true here,
the nativelogin, nativelogout, nativeIsLoggedIn should be implemented
Returns:
true if the service supports native login
getAccessToken
public AccessToken getAccessToken()
This method tries to validate the last access token if exists, if the last token is not
valid anymore it will try to login the user in order to get a fresh token The method
blocks until a valid token has been granted
Throws:
IOException
validateToken
protected abstract boolean validateToken(String token)
Returns true if the previous granted access token is still valid otherwise false.
Parameters:
token - the access token to check
Returns:
true of the token is valid
setAccessToken
public void setAccessToken(AccessToken token)
Sets the login callback that will receive event callback notification from the API
Parameters:
lc - the login callback or null to remove the existing login callback
setClientId
public void setClientId(String id)
setRedirectURI
public void setRedirectURI(String URI)
Method Detail
2080
Creates the oauth2 to be used to login in case no native login is available for this
service.
Returns:
the Oauth2 to be used to login if no native login available and on the
simulator
Method Detail
2081
Class GoogleConnect
java.lang.Object
com.codename1.social.Login
com.codename1.social.GoogleConnect
public class
extends Login
The GoogleConnect Login class allows the sign in with google functionality. The GoogleConnect
requires to create a corresponding google cloud project. To enable the GoogleConnect to sign-in on
the Simulator create a corresponding web login - https://developers.google.com/+/web/signin/ To
enable the GoogleConnect to sign-in on Android Follow step 1 from here https://developers.google.com/+/mobile/android/getting-started To enable the GoogleConnect to
sign-in on iOS follow step 1 from here - https://developers.google.com/+/mobile/ios/getting-started
Method Summary
Modifier and Type
protected Oauth2
static
GoogleConnect
getInstance()
boolean
protected boolean
Method Detail
getInstance
public static GoogleConnect getInstance()
Class GoogleConnect
2082
Method Detail
2083
Class FacebookConnect
java.lang.Object
com.codename1.social.Login
com.codename1.social.FacebookConnect
public class
extends Login
Invokes the native bundled facebook SDK to login/logout of facebook, notice that in order for this to
work server build arguments must indicate that you are using the facebook sdk! To accomplish this
just define: facebook.appId=YourAppId in your build arguments. In order to obtain the app ID you
need to create a native Android/iOS application and generate the right app id.
Method Summary
Modifier and Type
void
Asks for publish permissions, this call might suspend the application
which might trigger repeated invocations of stop()/start().
createOauth2()
protected Oauth2
void
AccessToken
static
FacebookConnect
String
boolean
Deprecated.
use getAccessToken instead
hasPublishPermissions()
void
void
boolean
boolean
boolean
boolean
Deprecated.
use isUserLoggedIn() instead
isNativeLoginSupported()
void
Deprecated.
use doLogin
void
logout()
Class FacebookConnect
2084
nativeIsLoggedIn()
void
void
protected boolean
Returns true if the previous granted access token is still valid otherwise
false.
Method Detail
getInstance
public static FacebookConnect getInstance()
Method Summary
2085
Asks for publish permissions, this call might suspend the application which might
trigger repeated invocations of stop()/start().
hasPublishPermissions
public boolean hasPublishPermissions()
Method Detail
2086
Method Detail
2087
Class ShareService
java.lang.Object
com.codename1.ui.Command
com.codename1.share.ShareService
All Implemented Interfaces:
ActionListener
Direct Known Subclasses:
EmailShare, FacebookShare, SMSShare
Constructor Summary
Constructor and Description
ShareService(String name, Image icon)
Method Summary
Modifier
and Type
void
abstract
boolean
canShareImage()
void
Once the share service has finished sharing it should call the finish method
getOriginal()
Form
Sets the image to share, this is done by the ShareButton and shouldn't be used
by the developers
void
setMessage(String message)
Sets the message to share, this is done by the ShareButton and shouldn't be
used by the developers
void
setOriginalForm(Form original)
void
Sets the Original Form (this is the Form of the share button)
abstract
void
share(String text)
This is the image sharing method which should be implemented by the service,
if the service returned true on the canShareImage() method Notice not all
services are able to share text and image together, in this case the image
sharing will be preferred by these services
void
Class ShareService
2088
Constructor Detail
ShareService
public ShareService(String name,
Image icon)
Method Detail
actionPerformed
public void actionPerformed(ActionEvent evt)
This is the image sharing method which should be implemented by the service, if the
service returned true on the canShareImage() method Notice not all services are able
to share text and image together, in this case the image sharing will be preferred by
these services
Parameters:
text - text to share
image - image to share
canShareImage
public abstract boolean canShareImage()
Sets the message to share, this is done by the ShareButton and shouldn't be used by
the developers
2089
setImage
public void setImage(String image,
String mime)
Sets the image to share, this is done by the ShareButton and shouldn't be used by
the developers
Parameters:
image - the file path to the image
mime - the image mime type e.g. image/png, image/jpeg
setOriginalForm
public void setOriginalForm(Form original)
Sets the Original Form (this is the Form of the share button)
getOriginal
public Form getOriginal()
Once the share service has finished sharing it should call the finish method
Method Detail
2090
Class SMSShare
java.lang.Object
com.codename1.ui.Command
com.codename1.share.ShareService
com.codename1.share.SMSShare
All Implemented Interfaces:
ActionListener
public class
extends ShareService
Constructor Summary
Constructor and Description
SMSShare()
Default Constructor
Method Summary
Modifier and
Type
boolean
void
Constructor Detail
SMSShare
public SMSShare()
Default Constructor
Class SMSShare
2091
Detail
share
public void share(String toShare)
Method Detail
2092
Class FacebookShare
java.lang.Object
com.codename1.ui.Command
com.codename1.share.ShareService
com.codename1.share.FacebookShare
All Implemented Interfaces:
ActionListener
public class
extends ShareService
Constructor Summary
Constructor and Description
FacebookShare()
Default Constructor
Method Summary
Modifier
and Type
void
boolean
canShareImage()
void
This is the image sharing method which should be implemented by the service, if
the service returned true on the canShareImage() method Notice not all services
are able to share text and image together, in this case the image sharing will be
preferred by these services
void
Class FacebookShare
2093
Constructor
Detail
FacebookShare
public FacebookShare()
Default Constructor
Method Detail
actionPerformed
public void actionPerformed(ActionEvent evt)
This is the image sharing method which should be implemented by the service, if the
service returned true on the canShareImage() method Notice not all services are able
to share text and image together, in this case the image sharing will be preferred by
these services
Overrides:
share in class ShareService
Parameters:
text - text to share
image - image to share
share
public void share(String toShare)
Constructor Detail
2094
Class EmailShare
java.lang.Object
com.codename1.ui.Command
com.codename1.share.ShareService
com.codename1.share.EmailShare
All Implemented Interfaces:
ActionListener
public class
extends ShareService
Constructor Summary
Constructor and Description
EmailShare()
Default Constructor
Method Summary
Modifier
and Type
boolean
void
This is the image sharing method which should be implemented by the service,
if the service returned true on the canShareImage() method Notice not all
services are able to share text and image together, in this case the image
sharing will be preferred by these services
void
Constructor Detail
Method Detail
2095
Default Constructor
Method Detail
share
public void share(String toShare,
String image,
String mimeType)
This is the image sharing method which should be implemented by the service, if the
service returned true on the canShareImage() method Notice not all services are able
to share text and image together, in this case the image sharing will be preferred by
these services
Overrides:
share in class ShareService
Parameters:
toShare - text to share
image - image to share
share
public void share(String toShare)
Constructor Detail
2096
Interface PushCallback
public interface
This callback interface is invoked when a push notification is received by the application. If the main
class of the application implements push callback it will receive push notification calls from the
system. Notice that its very possible that a separate instance of the main class will be created to
perform the push!
Field Summary
Modifier and Type
static int
static int
static int
static int
static int
static int
Method Summary
Modifier and
Type
void
void
registeredForPush(String deviceId)
void
Field Detail
REGISTRATION_ERROR_SERVICE_NOT_AVAILABLE
static final int REGISTRATION_ERROR_SERVICE_NOT_AVAILABLE
Method Detail
2097
Method Detail
push
void push(String value)
Invoked when push registration is complete to pass the device ID to the application.
Parameters:
deviceId - OS native push id you should not use this value and instead use
Push.getPushKey()
See Also:
Push.getPushKey()
pushRegistrationError
void pushRegistrationError(String error,
int errorCode)
Field Detail
2098
Class Push
java.lang.Object
com.codename1.push.Push
public class
extends Object
Utility class for sending a push message to a different device through the Codename One push
servers.
Field Summary
Modifier and Type
static String
Key for the hashtable argument when pushing to the google play store
Constructor Summary
Constructor and Description
Push()
Method Summary
Modifier
and Type
static
String
static
String
static
boolean
static
boolean
static
boolean
static
boolean
Method Detail
Deprecated.
this method sends a push using the old push servers which will be retired, you
need to switch to getPushKey()
getPushKey()
Returns the push device key if the device was previously successfully registered
for push otherwise returns null
sendPushMessage(String body, String deviceKey, boolean production,
String googleAuthKey, String iosCertificateURL,
String iosCertificatePassword)
Deprecated.
this method sends a push using the old push servers which will be retired, you
need to switch to the equivalent method that accepts a push token
sendPushMessage(String token, String body, boolean production,
String googleAuthKey, String iosCertificateURL,
String iosCertificatePassword, int pushType, String... deviceKey)
Sends a push message and returns true if server delivery succeeded, notice
that the push message isn't guaranteed to reach all devices.
sendPushMessage(String body, String deviceKey, boolean production,
String googleAuthKey, String iosCertificateURL,
String iosCertificatePassword, String bbUrl, String bbApp,
String bbPass, String bbPort)
Deprecated.
this method sends a push using the old push servers which will be retired, you
need to switch to the equivalent method that accepts a push token
sendPushMessage(String token, String body, String deviceKey,
boolean production, String googleAuthKey, String iosCertificateURL,
String iosCertificatePassword)
2099
static
boolean
Sends a push message and returns true if server delivery succeeded, notice
that the push message isn't guaranteed to reach all devices.
static
void
static
void
static
void
static
void
Deprecated.
this method sends a push using the old push servers which will be retired, you
need to switch to the equivalent method that accepts a push token
sendPushMessageAsync(String body, String deviceKey,
boolean production, String googleAuthKey, String iosCertificateURL,
String iosCertificatePassword, String bbUrl, String bbApp,
String bbPass, String bbPort)
Deprecated.
this method sends a push using the old push servers which will be retired, you
need to switch to the equivalent method that accepts a push token
sendPushMessageAsync(String token, String body, String deviceKey,
boolean production, String googleAuthKey, String iosCertificateURL,
String iosCertificatePassword)
Sends a push message and returns true if server delivery succeeded, notice
that the push message isn't guaranteed to reach all devices.
sendPushMessageAsync(String token, String body, String deviceKey,
boolean production, String googleAuthKey, String iosCertificateURL,
String iosCertificatePassword, String bbUrl, String bbApp,
String bbPass, String bbPort)
Sends a push message and returns true if server delivery succeeded, notice
that the push message isn't guaranteed to reach all devices.
Field Detail
GOOGLE_PUSH_KEY
public static final String GOOGLE_PUSH_KEY
Key for the hashtable argument when pushing to the google play store
See Also:
Constant Field Values
Constructor Detail
Push
public Push()
Method Detail
sendPushMessage
public static boolean sendPushMessage(String body,
String deviceKey,
boolean production,
String googleAuthKey,
String iosCertificateURL,
String iosCertificatePassword)
Method Summary
2100
Deprecated. this method sends a push using the old push servers which will be
retired, you need to switch to the equivalent method that accepts a push token
Sends a push message and returns true if server delivery succeeded, notice that the
push message isn't guaranteed to reach all devices.
Parameters:
body - the body of the message
deviceKey - an optional parameter (can be null) when sending to a specific
device
production - whether pushing to production or test/sandbox environment
googleAuthKey - authorization key from the google play store
iosCertificateURL - a URL where you host the iOS certificate for this
applications push capabilities.
iosCertificatePassword - the password for the push certificate
bbUrl - the URL to which the push should be submitted when sending a
blackberry push for evaluation use https://pushapi.eval.blackberry.com for
production you will need to apply at https://cp310.pushapi.na.blackberry.com
bbApp - the application id to authenticate on push for RIM devices
bbPass - the application password credentials authenticate on push for RIM
devices
bbPort - the port of the blackberry push
Returns:
true if the message reached the Codename One server successfully, this
makes no guarantee of delivery.
sendPushMessageAsync
public static void sendPushMessageAsync(String body,
String deviceKey,
boolean production,
String googleAuthKey,
String iosCertificateURL,
String iosCertificatePassword)
Deprecated. this method sends a push using the old push servers which will be
retired, you need to switch to the equivalent method that accepts a push token
Sends a push message and returns true if server delivery succeeded, notice that the
push message isn't guaranteed to reach all devices.
Parameters:
body - the body of the message
Method Detail
2101
device
production - whether pushing to production or test/sandbox environment
googleAuthKey - authorization key from the google play store
iosCertificateURL - a URL where you host the iOS certificate for this
Deprecated. this method sends a push using the old push servers which will be
retired, you need to switch to the equivalent method that accepts a push token
Sends a push message and returns true if server delivery succeeded, notice that the
push message isn't guaranteed to reach all devices.
Parameters:
body - the body of the message
deviceKey - an optional parameter (can be null) when sending to a specific
device
production - whether pushing to production or test/sandbox environment
googleAuthKey - authorization key from the google play store
iosCertificateURL - a URL where you host the iOS certificate for this
applications push capabilities.
iosCertificatePassword - the password for the push certificate
bbUrl - the URL to which the push should be submitted when sending a
blackberry push for evaluation use https://pushapi.eval.blackberry.com for
production you will need to apply at https://cp310.pushapi.na.blackberry.com
bbApp - the application id to authenticate on push for RIM devices
bbPass - the application password credentials authenticate on push for RIM
devices
bbPort - the port of the blackberry push
getDeviceKey
public static String getDeviceKey()
Deprecated. this method sends a push using the old push servers which will be
retired, you need to switch to getPushKey()
Returns the push device key if the device was previously successfully registered for
push otherwise returns null
Returns:
the device key that can be used to push to this specific device.
getPushKey
public static String getPushKey()
Returns the push device key if the device was previously successfully registered for
push otherwise returns null
Returns:
the device key that can be used to push to this specific device.
sendPushMessage
public static boolean sendPushMessage(String token,
String body,
String deviceKey,
boolean production,
String googleAuthKey,
String iosCertificateURL,
String iosCertificatePassword)
Method Detail
2102
Sends a push message and returns true if server delivery succeeded, notice that the
push message isn't guaranteed to reach all devices. This method uses the new push
servers
Parameters:
token - the authorization token from the account settings in the
CodenameOne website, this is used to associate push quotas with your app
body - the body of the message
production - whether pushing to production or test/sandbox environment
googleAuthKey - authorization key from the google play store
iosCertificateURL - a URL where you host the iOS certificate for this
applications push capabilities.
iosCertificatePassword - the password for the push certificate
pushType - the type for the push in the server, this is useful for sending
hidden pushes (type 2) should default to 0 or 1
deviceKey - set of devices that should receive the push
Returns:
true if the message reached the Codename One server successfully, this
makes no guarantee of delivery.
sendPushMessage
public static boolean sendPushMessage(String token,
String body,
String deviceKey,
boolean production,
String googleAuthKey,
String iosCertificateURL,
String iosCertificatePassword,
String bbUrl,
String bbApp,
String bbPass,
String bbPort)
Sends a push message and returns true if server delivery succeeded, notice that the
push message isn't guaranteed to reach all devices. This method uses the new push
servers
Parameters:
token - the authorization token from the account settings in the
CodenameOne website, this is used to associate push quotas with your app
body - the body of the message
deviceKey - an optional parameter (can be null) when sending to a specific
device
production - whether pushing to production or test/sandbox environment
Method Detail
2103
for this
applications push capabilities.
iosCertificatePassword - the password for the push certificate
bbUrl - the URL to which the push should be submitted when sending a
blackberry push for evaluation use https://pushapi.eval.blackberry.com for
production you will need to apply at https://cp310.pushapi.na.blackberry.com
bbApp - the application id to authenticate on push for RIM devices
bbPass - the application password credentials authenticate on push for RIM
devices
bbPort - the port of the blackberry push
Returns:
true if the message reached the Codename One server successfully, this
makes no guarantee of delivery.
sendPushMessageAsync
public static void sendPushMessageAsync(String token,
String body,
String deviceKey,
boolean production,
String googleAuthKey,
String iosCertificateURL,
String iosCertificatePassword)
Sends a push message and returns true if server delivery succeeded, notice that the
push message isn't guaranteed to reach all devices. This method uses the new push
servers
Parameters:
token - the authorization token from the account settings in the
CodenameOne website, this is used to associate push quotas with your app
body - the body of the message
deviceKey - an optional parameter (can be null) when sending to a specific
device
production - whether pushing to production or test/sandbox environment
googleAuthKey - authorization key from the google play store
iosCertificateURL - a URL where you host the iOS certificate for this
applications push capabilities.
iosCertificatePassword - the password for the push certificate
sendPushMessageAsync
public static void sendPushMessageAsync(String token,
String body,
String deviceKey,
boolean production,
String googleAuthKey,
String iosCertificateURL,
String iosCertificatePassword,
String bbUrl,
String bbApp,
String bbPass,
String bbPort)
Sends a push message and returns true if server delivery succeeded, notice that the
push message isn't guaranteed to reach all devices. This method uses the new push
servers
Parameters:
token - the authorization token from the account settings in the
CodenameOne website, this is used to associate push quotas with your app
body - the body of the message
deviceKey - an optional parameter (can be null) when sending to a specific
device
production - whether pushing to production or test/sandbox environment
googleAuthKey - authorization key from the google play store
iosCertificateURL - a URL where you host the iOS certificate for this
applications push capabilities.
iosCertificatePassword - the password for the push certificate
bbUrl - the URL to which the push should be submitted when sending a
blackberry push for evaluation use https://pushapi.eval.blackberry.com for
production you will need to apply at https://cp310.pushapi.na.blackberry.com
Method Detail
2104
for RIM
devices
bbPort - the port of the blackberry push
Method Detail
2105
Class Result
java.lang.Object
com.codename1.processing.Result
public class
extends Object
An evaluator for a very small expression language to extract primitive types from structured
information. This implementation is layered over the com.codename1.io.JSONParser and
com.codename1.xml.XMLParser classes. This expression language allows applications to extract
information from structured data returned by web services with minimal effort. The expression
language works a lot like a very small subset of XPath - the expression syntax uses the / character for
sub-elements and square brackets for arrays. Some sample expressions:
Simple expression, get the title of the first photo element.
/photos/photo[1]/title
Globally find the first name of a person with a last name of 'Coolman'.
//person[lastname='Coolman']/firstName
Get the latitude value of the second last result element.
/results[last()-1]/geometry/bounds/northeast/lat
Get the names of players from Germany
/tournament/player[@nationality='Germany']/name
Get the purchase order numbers of any order with a lineitem worth over $5
//order/lineitem[price > 5]/../@ponum
etc
Field Summary
Modifier and Type Field and Description
static char
ARRAY_END
static char
ARRAY_START
static String
JSON
static char
SEPARATOR
static String
XML
Method Summary
Modifier and
Type
boolean
static Result
static Result
Class Result
2106
fromContent(Map content)
static Result
static Result
Object
List
boolean
boolean[]
getAsBoolean(String path)
double
double[]
getAsDoubleArray(String path)
int
int[]
long
long[]
String
String[]
getAsStringArray(String path)
int
int
void
String
Field Detail
JSON
public static final String JSON
See Also:
Constant Field Values
XML
public static final String XML
See Also:
Constant Field Values
Method Summary
2107
See Also:
Constant Field Values
ARRAY_START
public static final char ARRAY_START
See Also:
Constant Field Values
ARRAY_END
public static final char ARRAY_END
See Also:
Constant Field Values
Method Detail
fromContent
public static Result fromContent(String content,
String format)
throws IllegalArgumentException
Create an evaluator object from a structured content document (XML, JSON, etc) as
a string.
Parameters:
content - structured content document as a string.
format - an identifier for the type of content passed (ie. xml, json, etc).
Returns:
Result a result evaluator object
Throws:
IllegalArgumentException - thrown if null content or format is passed.
fromContent
public static Result fromContent(InputStream content,
String format)
throws IllegalArgumentException,
IOException
Create an evaluator object from a structured content document (XML, JSON, etc)
input stream. Normally you would use this method within a content request
implementation, for example:
ConnectionRequest request = new ConnectionRequest() {
protected void readResponse(InputStream input) throws IOException {
Result evaluator = Result.fromContent(input, Result.JSON);
// ... evaluate the result here
}
// ... etc
};
Parameters:
content - structured content document as a string.
format - an identifier for the type of content passed
Field Detail
2108
Create an evaluator object from a structured content document (XML, JSON, etc)
input stream. Normally you would use this method within a content request
implementation, for example:
ConnectionRequest request = new ConnectionRequest() {
protected void readResponse(InputStream input) throws IOException {
Result evaluator = Result.fromContent(input, Result.JSON);
// ... evaluate the result here
}
// ... etc
};
Parameters:
content - structured content document as a string.
format - an identifier for the type of content passed
fromContent
public static Result fromContent(Element content)
throws IllegalArgumentException
hashCode
public int hashCode()
equals
public boolean equals(Object other)
Method Detail
2109
toString
public String toString()
Convert the object to a formatted structured content document. For example, an XML
or JSON document.
Overrides:
toString in class Object
Returns:
a structured content document as a string
getAsBoolean
public boolean getAsBoolean(String path)
throws IllegalArgumentException
Get a boolean value from the requested path. For example: JSON
{
"settings" : [
{
"toggle" : "true",
... etc
}
Expression
boolean value = result.getAsBoolean("/settings[0]/toggle");
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalArgumentException - on error traversing the document, ie. traversing
into an array without using subscripts.
getAsInteger
public int getAsInteger(String path)
throws IllegalArgumentException
Get an integer value from the requested path. For example: JSON
{
"settings"
{
"connection"
{
"max_retries" : "20",
... etc
}
}
Expression
int value = result.getAsInteger("//connection/max_retries");
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalException - on error traversing the document, ie. traversing into an
array without using subscripts.
IllegalArgumentException
Method Detail
2110
Get an long value from the requested path. For example: JSON
{
"settings"
{
"connection"
{
"timeout_milliseconds" : "100000",
... etc
}
}
Expression
long value = result.getAsLong("/settings/connection/timeout_milliseconds");
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalArgumentException - on error traversing the document, ie. traversing
into an array without using subscripts.
getAsDouble
public double getAsDouble(String path)
throws IllegalArgumentException
Get a double value from the requested path. For example: JSON
{
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 42.94959820,
"lng" : -81.24873959999999
},
"southwest" : {
"lat" : 42.94830,
"lng" : -81.24901740000001
}
},
"location" : {
"lat" : 42.94886990,
"lng" : -81.24876030
},
"location_type" : "RANGE_INTERPOLATED",
"viewport" : {
"northeast" : {
"lat" : 42.95029808029150,
"lng" : -81.24752951970851
},
"southwest" : {
"lat" : 42.94760011970850,
"lng" : -81.25022748029151
}
}
// etc
Expression
double
double
double
double
Method Detail
neBoundsLat = result.getAsDouble("//bounds/northeast/lat");
neBoundsLong = result.getAsDouble("//bounds/northeast/lng");
swBoundsLat = result.getAsDouble("//bounds/southwest/lat");
swBoundsLong = result.getAsDouble("//bounds/southwest/lng");
2111
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalArgumentException - on error traversing the document, ie. traversing
into an array without using subscripts.
getAsString
public String getAsString(String path)
throws IllegalArgumentException
Get a string value from the requested path. For example: JSON
{
"profile"
{
"location"
{
"city" : "London",
"region" : "Ontario",
"country" : "Canada",
... etc
},
}
Expression
String city = result.getAsDouble("//city");
String province = result.getAsDouble("//location//region");
String country = result.getAsDouble("profile//location//country");
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalArgumentException - on error traversing the document, ie. traversing
into an array without using subscripts.
get
public Object get(String path)
throws IllegalArgumentException
Get the object value from the requested path. This method may return a Map, List,
String, or null.
Parameters:
path Returns:
the object at the given path, or null.
Throws:
IllegalArgumentException
getSizeOfArray
public int getSizeOfArray(String path)
throws IllegalArgumentException
Get the size of an array at the requested path. For example: JSON
{
"results" : [
{
"address_components" : [
{
"long_name" : "921-989",
"short_name" : "921-989",
Method Detail
2112
Expression
int size = result.getSizeOfArray("/results[0]/address_components");
int size2 = result.getSizeOfArray("results");
int size3 = result.getSizeOfArray("/results[0]/address_components[2]/types");
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalArgumentException - on error traversing the document, ie. traversing
into an array without using subscripts.
getAsStringArray
public String[] getAsStringArray(String path)
throws IllegalArgumentException
Get an array of string values from the requested path. For example: JSON
{
"results" : [
{
"address_components" : [
{
"long_name" : "921-989",
"short_name" : "921-989",
"types" : [ "street_number" ]
},
{
"long_name" : "Country Club Crescent",
"short_name" : "Country Club Crescent",
"types" : [ "route" ]
},
{
"long_name" : "Ontario",
"short_name" : "ON",
"types" : [ "administrative_area_level_1", "political" ]
},
... etc
}
}
Expression
String types[] = result
.getAsStringArray("/results[0]/address_components[2]/types");
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
Method Detail
2113
Get an array of values from the requested path. For example: JSON
{
"results" : [
{
"address_components" : [
{
"long_name" : "921-989",
"short_name" : "921-989",
"types" : [ "street_number" ]
},
{
"long_name" : "Country Club Crescent",
"short_name" : "Country Club Crescent",
"types" : [ "route" ]
},
{
"long_name" : "Ontario",
"short_name" : "ON",
"types" : [ "administrative_area_level_1", "political" ]
},
... etc
}
}
Expression
String types[] = result
.getAsStringArray("/results[0]/address_components[2]/types");
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalArgumentException - on error traversing the document, ie. traversing
into an array without using subscripts.
NumberFormatException - if the value at path can not be converted to an
integer.
getAsLongArray
public long[] getAsLongArray(String path)
throws IllegalArgumentException
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalArgumentException - on error traversing the document, ie. traversing
into an array without using subscripts.
NumberFormatException - if the value at path can not be converted to an long.
Method Detail
2114
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalArgumentException - on error traversing the document, ie. traversing
into an array without using subscripts.
NumberFormatException - if the value at path can not be converted to an
double.
getAsBooleanArray
public boolean[] getAsBooleanArray(String path)
throws IllegalArgumentException
Parameters:
path - Path expression to evaluate
Returns:
the value at the requested path
Throws:
IllegalArgumentException - on error traversing the document, ie. traversing
into an array without using subscripts.
getAsArray
public List getAsArray(String path)
throws IllegalArgumentException
Get a List of values from the requested path. For example: JSON
{
"results" : [
{
"address_components" : [
{
"long_name" : "921-989",
"short_name" : "921-989",
"types" : [ "street_number" ]
},
{
"long_name" : "Country Club Crescent",
"short_name" : "Country Club Crescent",
"types" : [ "route" ]
},
... etc
}
}
Expression
List addressComponents = result.getAsList("/results[0]/address_components");
result = Result.fromContent(addressComponents);
String longName = result.getAsString("[1]/long_name");
Method Detail
2115
Method Detail
2116
Interface RestoreCallback
public interface
Callback interface that the main class must implement in order for the restore option of
in-app-purchasing to work. Once the main class implements this interface the methods within it are
invoked to indicate the various restore states.
Method Summary
Modifier and
Type
void
void
errors.
restoreRequestError(String message)
Indicates that a Purchase.restore() request
void
Method Detail
itemRestored
void itemRestored(String sku)
Indicates a the given SKU was restored by a user. When restoring multiple SKU's at
once multiple calls to this method will be performed.
Parameters:
sku - the sku purchased
restoreRequestComplete
void restoreRequestComplete()
Interface RestoreCallback
2117
Interface PurchaseCallback
public interface
Callback interface that the main class must implement in order for in-app-purchasing to work. Once
the main class implements this interface the methods within it are invoked to indicate the various
purchase states.
Method Summary
Modifier and
Type
void
void
void
void
void
void
void
Method Detail
itemPurchased
void itemPurchased(String sku)
Indicates a the given SKU was purchased by a user. When purchasing multiple
SKU's at once multiple calls to this method will be performed.
Parameters:
sku - the sku purchased
itemPurchaseError
void itemPurchaseError(String sku,
String errorMessage)
Method Detail
2118
Method Detail
2119
Class Purchase
java.lang.Object
com.codename1.payment.Purchase
Represents the status of in-app-purchase goods, this class provides information about products
purchased by a user as well as the ability to purchase additional products. There are generally two
types of payment systems: Manual and managed. In manual payments we pay a specific amount in a
specific currency while with managed payment systems we work against a product catalog defined in
the server.
In-app-purchase API's rely on managed server based products, other payment systems use the
manual approach. An application dealing with virtual goods must support both since not all devices
feature in-app-purchase API's. An application dealing with physical goods & services must use the
latter according to the TOS of current in-app-purchase solutions.
Constructor Summary
Constructor and Description
Purchase()
Method Summary
Modifier and
Type
static
Purchase
static
Purchase
Product[]
Deprecated.
use the version that takes no arguments
getProducts(String[] skus)
boolean
Indicates whether the payment platform supports things such as "item listing"
or requires that items be coded into the system.
isManagedPaymentSupported()
boolean
boolean
boolean
boolean
boolean
boolean
Class Purchase
2120
String
String
purchase(String sku)
void
void
void
subscribe(String sku)
void
void
boolean
Returns true if the given SKU was purchased in the past, notice this method
might not work as expected for Unmanaged/consumable products which can
be purchased multiple times.
Constructor Detail
Purchase
public Purchase()
Method Detail
isManualPaymentSupported
public boolean isManualPaymentSupported()
Indicates whether the purchasing platform supports manual payments which are just
payments of a specific amount of money.
Returns:
true if manual payments are supported
isManagedPaymentSupported
public boolean isManagedPaymentSupported()
Indicates whether the purchasing platform supports managed payments which work
by picking products that are handled by the servers/OS of the platform vendor.
Returns:
true if managed payments are supported
pay
public String pay(double amount,
String currency)
Performs payment of a specific amount based on the manual payment API, notice
that this doesn't use the in-app-purchase functionality of the device!
Parameters:
amount - the amount to pay
Method Summary
2121
Performs payment of a specific amount based on the manual payment API, notice
that this doesn't use the in-app-purchase functionality of the device!
Parameters:
amount - the amount to pay
currency - the three letter currency type
invoiceNumber - application specific invoice number
Returns:
a token representing the pending transaction which will be matched when
receiving a callback from the platform or a null if the payment has failed or
was canceled
Throws:
RuntimeException - This method is a part of the manual payments API and
will fail if isManualPaymentSupported() returns false
isItemListingSupported
public boolean isItemListingSupported()
Indicates whether the payment platform supports things such as "item listing" or
requires that items be coded into the system. iOS provides listing and pricing where
Android expects developers to redirect into the Play application for application details.
Returns:
true if the OS supports this behavior
getProducts
public Product[] getProducts(String[] skus)
Returns true if the given SKU was purchased in the past, notice this method might
not work as expected for Unmanaged/consumable products which can be purchased
multiple times. In addition, this will only return true if the product was purchased (or
has been restored) on the current device.
Parameters:
sku - the id of the product
Returns:
true if the product was purchased
Throws:
RuntimeException - This method is a part of the managed payments API and
will fail if isManagedPaymentSupported() returns false
Method Detail
2122
Method Detail
2123
Method Detail
2124
Class Product
java.lang.Object
com.codename1.payment.Product
public class
extends Object
Constructor Summary
Constructor and Description
Product()
Method Summary
Modifier and Type
String
getDescription()
String
getDisplayName()
String
getLocalizedPrice()
String
getSku()
void
setDescription(String description)
void
setDisplayName(String displayName)
void
setLocalizedPrice(String localizedPrice)
void
setSku(String sku)
Constructor Detail
Product
public Product()
Method Detail
getDisplayName
public String getDisplayName()
Returns:
the displayName
setDisplayName
public void setDisplayName(String displayName)
Parameters:
Class Product
2125
getDescription
public String getDescription()
Returns:
the description
setDescription
public void setDescription(String description)
Parameters:
description
getLocalizedPrice
public String getLocalizedPrice()
Returns:
the localizedPrice
setLocalizedPrice
public void setLocalizedPrice(String localizedPrice)
Parameters:
localizedPrice
getSku
public String getSku()
Returns:
the sku
setSku
public void setSku(String sku)
Parameters:
sku - the sku to set
Method Detail
2126
Interface LocalNotificationCallback
public interface
An interface that can be implemented by the application's main class (i.e. the class with start(),
stop() etc..) to respond to local notifications. This interface only works when it is implemented by the
main class. It will never be called otherwise.
IMPORTANT: THIS CALLBACK IS CALLED OFF THE EDT. ANY UPDATES TO THE UI WILL NEED
TO OCCUR INSIDE A callSerially() block.
See Also:
LocalNotification
Method Summary
Modifier and
Type
void
Callback method that is called when a local notification is received AND the
application is active.
Method Detail
localNotificationReceived
void localNotificationReceived(String notificationId)
Callback method that is called when a local notification is received AND the
application is active. This won't necessarily be called when the notification is
received. If the app is in the background, for example, the notification will manifest
itself as a message to the user's task bar (or equivalent). If the user then clicks on the
notification message, the app will be activated, and this callback method will be
called.
IMPORTANT: THIS CALLBACK IS CALLED OFF THE EDT. ANY UPDATES TO
THE UI WILL NEED TO OCCUR INSIDE A callSerially() block.
Parameters:
notificationId
See Also:
LocalNotification
Interface LocalNotificationCallback
2127
Class LocalNotification
java.lang.Object
com.codename1.notifications.LocalNotification
public class
extends Object
Local notifications are user notifications that are scheduled by the app itself. They are very similar to
push notifications, except that they originate locally, rather than remotely.
They enable an app that isnt running in the foreground to let its users know it has information for
them. The information could be a message, an impending calendar event, or new data on a remote
server. They can display an alert message or they can badge the app icon. They can also play a
sound when the alert or badge number is shown.
When users are notified that the app has a message, event, or other data for them, they can launch
the app and see the details. They can also choose to ignore the notification, in which case the app is
not activated.
This class encapsulates a single notification (though the notification can be repeating).
Usage
See Also:
Display.scheduleLocalNotification(LocalNotification n, long firstTime, int repeat),
Display.cancelLocalNotification(java.lang.String id)
Field Summary
Modifier and
Type
static int
static int
static int
static int
static int
Method Detail
2128
Summary
Method Summary
Modifier
and Type
String
String
String
String
int
String
getId()
void
void
setAlertSound(String alertSound)
void
void
void
void
Field Detail
REPEAT_NONE
public static final int REPEAT_NONE
Constructor Summary
2129
Constructor Detail
LocalNotification
public LocalNotification()
Method Detail
getBadgeNumber
public int getBadgeNumber()
Field Detail
2130
getAlertTitle
public String getAlertTitle()
Gets the alert sound to be sounded when the notification arrives. This should refer to
a sound file that is bundled in the default package of your app.
Returns:
the alertSound
setAlertSound
public void setAlertSound(String alertSound)
Sets the alert sound to be sounded when the notification arrives. This should refer to
a sound file that is bundled in the default package of your app. The name of the file
must start with the "notification_sound" prefix.
LocalNotification n = new LocalNotification();
n.setAlertSound("/notification_sound_bells.mp3");
Parameters:
alertSound
getId
public String getId()
Gets the ID of the notification. The ID is the only information that is passed to
so you
can use it as a lookup key to retrieve the rest of the information as required from
storage or some other mechanism. The ID can also be used to cancel the notification
later using Display.cancelLocalNotification(java.lang.String)
Returns:
the id
setId
LocalNotificationCallback.localNotificationReceived(java.lang.String)
Sets the ID of the notification. The ID is the only information that is passed to
so you
can use it as a lookup key to retrieve the rest of the information as required from
storage or some other mechanism. The ID can also be used to cancel the notification
later using Display.cancelLocalNotification(java.lang.String)
Parameters:
id - the id to set
getAlertImage
LocalNotificationCallback.localNotificationReceived(java.lang.String)
Method Detail
2131
Method Detail
2132
Class Message
java.lang.Object
com.codename1.messaging.Message
public class
extends Object
Field Summary
Modifier and Type Field and Description
static String
MIME_HTML
static String
MIME_IMAGE_JPG
static String
MIME_IMAGE_PNG
static String
MIME_TEXT
Constructor Summary
Constructor and Description
Message(String content)
Method Summary
Modifier and Type
String
String
Map<String,String>
String
String
boolean
static void
void
boolean
Class Message
Send an email message using the Codename One cloud to send the
message, notice that this API will only work for pro accounts
sendMessageViaCloudSync(String sender, String recipient,
String recipientName, String subject, String plainTextBody)
Send an email message using the Codename One cloud to send the
message, notice that this API will only work for pro accounts
2133
void
void
void
setMimeType(String mimeType)
void
Field Detail
MIME_TEXT
public static final String MIME_TEXT
See Also:
Constant Field Values
MIME_HTML
public static final String MIME_HTML
See Also:
Constant Field Values
MIME_IMAGE_JPG
public static final String MIME_IMAGE_JPG
See Also:
Constant Field Values
MIME_IMAGE_PNG
public static final String MIME_IMAGE_PNG
See Also:
Constant Field Values
Constructor Detail
Message
public Message(String content)
Method Detail
getContent
public String getContent()
Method Summary
2134
Returns the attachment map which can be used to add multiple attachments. The
path needs to point at a full absolute file URI within FileSystemStorage, it will not
work with Storage files!
Returns:
a map of full file paths to mime type that can be used to add attachments
setMimeType
public void setMimeType(String mimeType)
Method Detail
sender,
recipient,
recipientName,
subject,
plainTextBody)
2135
sender,
recipient,
recipientName,
subject,
plainTextBody)
Send an email message using the Codename One cloud to send the message, notice
that this API will only work for pro accounts
Parameters:
sender - the name of the sender, notice all email will arrive from Codename
One to avoid spam issues
recipient - the email for the recipient
recipientName - the display name for the recipient
subject - e-mail subject
plainTextBody - when sending an HTML message you should also attach a
plain text fallback message, this is redundant if the email is a plain text
message to begin with
Returns:
true if sending succeeded
isCloudMessageFailSilently
public boolean isCloudMessageFailSilently()
Indicates whether the cloud message should produce an error dialog if sending failed
Returns:
the cloudMessageFailSilently
setCloudMessageFailSilently
public void setCloudMessageFailSilently(boolean cloudMessageFailSilently)
Indicates whether the cloud message should produce an error dialog if sending failed
Parameters:
cloudMessageFailSilently - the cloudMessageFailSilently to set
Method Detail
2136
Class MediaManager
java.lang.Object
com.codename1.media.MediaManager
public class
extends Object
Allow us to create objects using String URI's or with a stream to the media data.
Notice that the underlying platforms contains the actual codecs, therefore you need to play common
media file types such as mp3, mp4 to successfully play them across devices on all target platforms.
The simulator can't accurately reproduce the behavior of this class in all devices/cases.
The sample code below demonstrates simple video playback.
final Form hi = new Form("MediaPlayer", new BorderLayout());
hi.setToolbar(new Toolbar());
Style s = UIManager.getInstance().getComponentStyle("Title");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_VIDEO_LIBRARY, s);
hi.getToolbar().addCommandToRightBar(new Command("", icon) {
{@literal @}Override
public void actionPerformed(ActionEvent evt) {
Display.getInstance().openGallery((e) -> {
if(e != null && e.getSource() != null) {
String file = (String)e.getSource();
try {
Media video = MediaManager.createMedia(file, true);
hi.removeAll();
hi.add(BorderLayout.CENTER, new MediaPlayer(video));
hi.revalidate();
} catch(IOException err) {
Log.e(err);
}
}
}, Display.GALLERY_VIDEO);
}
});
hi.show();
Class MediaManager
2137
Constructor
Summary
Method Summary
Modifier and
Type
static Media
static Media
static Media
static Media
static Media
Creates the Media in the given stream Notice that a Media is "auto
destroyed" on completion and cannot be played twice!
createMedia(InputStream stream, String mimeType,
Runnable onCompletion)
Creates the Media in the given stream Notice that a Media is "auto
destroyed" on completion and cannot be played twice!
createMedia(String uri, boolean isVideo)
static Media
Deprecated.
see createMediaRecorder(String path, String mimeType) instead
createMediaRecorder(String path, String mimeType)
static Media
Creates a Media recorder Object which will record from the device mic to a
file in the given path.
static
String[]
getAvailableRecordingMimeTypes()
static String
Deprecated.
see getAvailableRecordingMimeTypes() instead
Constructor Detail
MediaManager
public MediaManager()
Method Detail
createBackgroundMedia
public static Media createBackgroundMedia(String uri)
throws IOException
Constructor Summary
2138
createMedia
public static Media createMedia(String uri,
boolean isVideo)
throws IOException
Creates the Media in the given stream Notice that a Media is "auto destroyed" on
completion and cannot be played twice!
Parameters:
stream - the stream containing the media data
mimeType - the type of the data in the stream
Returns:
Media a Media Object that can be used to control the playback of the media
Throws:
IOException - if the creation of the Media has failed
createMedia
public static Media createMedia(String uri,
boolean isVideo,
Runnable onCompletion)
throws IOException
Creates the Media in the given stream Notice that a Media is "auto destroyed" on
completion and cannot be played twice!
Parameters:
stream - the stream containing the media data
mimeType - the type of the data in the stream
onCompletion - a Runnable to be called when the media has finished
Returns:
Media a Media Object that can be used to control the playback of the media
Throws:
IOException - if the URI access fails
Method Detail
2139
getMediaRecorderingMimeType
public static String getMediaRecorderingMimeType()
Creates a Media recorder Object which will record from the device mic to a file in the
given path.
Parameters:
path - a file path to where to store the recording, if the file does not exists it
will be created.
mimeType - the output mime type that is supported see
getAvailableRecordingMimeTypes()
Throws:
IllegalArgumentException - if given mime-type is not supported
IOException - id failed to create a Media object
Method Detail
2140
Interface Media
public interface
Media control interface allows for media playback, recording. To get an instance of this interface
(implemented by the native port) see the MediaManager class.
See Also:
MediaManager
Field Summary
Modifier
and Type
static
String
Write only variable that can be used with setVariable to pass the album cover
Image to the native layer so the currently playing media title will be displayed in
the lock screen where applicable
VARIABLE_BACKGROUND_ARTIST
static
String
Write only variable that can be used with setVariable to pass the artist name to
the native layer so the currently playing media title will be displayed in the lock
screen where applicable
VARIABLE_BACKGROUND_DURATION
static
String
Write only variable that can be used with setVariable to pass the duration for the
media as a Long object to the native layer so the currently playing media title
will be displayed in the lock screen where applicable
VARIABLE_BACKGROUND_POSITION
static
String
Write only variable that can be used with setVariable to pass the position in the
media (Long object) to the native layer so the currently playing media title will
be displayed in the lock screen where applicable
VARIABLE_BACKGROUND_SUPPORTED
static
String
Read only variable that can be used with getVariable to query whether the
native layer supports displaying the currently playing media information in the
lock screen.
VARIABLE_BACKGROUND_TITLE
static
String
Write only variable that can be used with setVariable to pass a title for the
native layer so the currently playing media title will be displayed in the lock
screen where applicable
Method Summary
Modifier
and Type
void
int
int
Object
Component
int
Interface Media
2141
isFullScreen()
void
void
void
Optional call that allows the caller to prepare the upcoming media player.
setFullScreen(boolean fullScreen)
void
setNativePlayerMode(boolean nativePlayer)
By calling this the Media (if it's a Video) will be played full screen on the native
Player of the device.
void
setTime(int time)
void
Sets the position in the audio file or doesn't effect if not supported
setVariable(String key, Object value)
void
void
Field Detail
VARIABLE_BACKGROUND_TITLE
static final String VARIABLE_BACKGROUND_TITLE
Write only variable that can be used with setVariable to pass a title for the native
layer so the currently playing media title will be displayed in the lock screen where
applicable
See Also:
Constant Field Values
VARIABLE_BACKGROUND_ARTIST
static final String VARIABLE_BACKGROUND_ARTIST
Write only variable that can be used with setVariable to pass the artist name to the
native layer so the currently playing media title will be displayed in the lock screen
where applicable
See Also:
Constant Field Values
VARIABLE_BACKGROUND_DURATION
static final String VARIABLE_BACKGROUND_DURATION
Write only variable that can be used with setVariable to pass the duration for the
media as a Long object to the native layer so the currently playing media title will be
displayed in the lock screen where applicable
See Also:
Constant Field Values
Method Summary
2142
Write only variable that can be used with setVariable to pass the album cover Image
to the native layer so the currently playing media title will be displayed in the lock
screen where applicable
See Also:
Constant Field Values
VARIABLE_BACKGROUND_POSITION
static final String VARIABLE_BACKGROUND_POSITION
Write only variable that can be used with setVariable to pass the position in the media
(Long object) to the native layer so the currently playing media title will be displayed
in the lock screen where applicable
See Also:
Constant Field Values
VARIABLE_BACKGROUND_SUPPORTED
static final String VARIABLE_BACKGROUND_SUPPORTED
Read only variable that can be used with getVariable to query whether the native
layer supports displaying the currently playing media information in the lock screen.
This will return null or Boolean.TRUE.
See Also:
Constant Field Values
Method Detail
play
void play()
Optional call that allows the caller to prepare the upcoming media player. This is
useful when streaming multiple streams one after another.
cleanup
void cleanup()
Stops the audio playback and cleans up the resources related to it immediately.
getTime
int getTime()
Sets the position in the audio file or doesn't effect if not supported
Parameters:
time - in milli seconds
Field Detail
2143
Sets the Media to be displayed full screen, make sure the getVideoComponent() is
called on the Video Component is added to the current Form
Parameters:
fullScreen setNativePlayerMode
void setNativePlayerMode(boolean nativePlayer)
By calling this the Media (if it's a Video) will be played full screen on the native Player
of the device. Native playing assumes getVideoComponent() hasn't been called on
this Media unexpected behaviour may occur if getVideoComponent() has been called
and the Component is placed on a Form. Some platforms such as BlackBerry is able
to play video only on the native player on those platforms isNativePlayerMode() will
Method Detail
2144
Returns true if this Video Media is in Native player mode. Some platforms such as
BlackBerry is able to play video only on the native player on those platforms
isNativePlayerMode() will always return true If Media supports native playing by
calling to play() the video will start playing in the native player in full screen.
Returns:
true if the player is in native mode
setVariable
void setVariable(String key,
Object value)
Method Detail
2145
Class TiledProvider
java.lang.Object
com.codename1.maps.providers.MapProvider
com.codename1.maps.providers.TiledProvider
Direct Known Subclasses:
GoogleMapsProvider, OpenStreetMapProvider
Field Summary
Modifier and Type Field and Description
protected String
_url
protected int
_zoomLevel
Constructor Summary
Constructor and Description
TiledProvider(String url, Projection projection, Dimension tileSize)
Method Summary
Modifier and Type
BoundingBox
Coord
Tile
protected String
Field Detail
Class TiledProvider
2146
_zoomLevel
protected int _zoomLevel
Constructor Detail
TiledProvider
public TiledProvider(String url,
Projection projection,
Dimension tileSize)
Method Detail
url
protected String url(int zoomLevel,
int xTile,
int yTile)
Field Detail
2147
in class MapProvider
Parameters:
bbox - a bounding box
Returns:
a Tile for the given bounding box
Method Detail
2148
Class OpenStreetMapProvider
java.lang.Object
com.codename1.maps.providers.MapProvider
com.codename1.maps.providers.TiledProvider
com.codename1.maps.providers.OpenStreetMapProvider
public class
extends TiledProvider
Field Summary
Constructor Summary
Constructor and Description
OpenStreetMapProvider()
Empty Constructor
Method Summary
Modifier and Type Method and Description
attribution()
String
int
Constructor Detail
Class OpenStreetMapProvider
2149
Empty Constructor
Method Detail
attribution
public String attribution()
Maximal zoom level. Zoom levels are counted from zero to maxZoomLevel(). 0 is
farest view, where the scale is greatest.
Specified by:
maxZoomLevel in class MapProvider
Returns:
Constructor Detail
2150
Class MapProvider
java.lang.Object
com.codename1.maps.providers.MapProvider
Direct Known Subclasses:
TiledProvider
Constructor Summary
Modifier
protected
Method Summary
Modifier and Type
abstract String
abstract
BoundingBox
int
abstract int
maxZoomLevel()
int
Projection
projection()
abstract Coord
abstract Tile
Dimension
Scale is the distance in map units between each pixel in tile at given
zoom level.
tileFor(BoundingBox bbox)
void
Coord
Method Detail
2151
Detail
MapProvider
protected MapProvider(Projection p,
Dimension tileSize)
Method Detail
tileSize
public void tileSize(Dimension size)
Request map to provide tiles of specific sizes. May not be supported by map
provider. By default it does nothing;
Parameters:
size - requested tile size
bboxFor
public abstract BoundingBox bboxFor(Coord position,
int zoomLevel)
Maximal zoom level. Zoom levels are counted from zero to maxZoomLevel(). 0 is
farest view, where the scale is greatest.
Returns:
minZoomLevel
public int minZoomLevel()
Scale is the distance in map units between each pixel in tile at given zoom level.
Returns:
Scale at given zoom level.
Constructor Detail
2152
translate
public Coord translate(Coord position,
int zoomLevel,
int pixelsX,
int pixelsY)
Method Detail
2153
Class GoogleMapsProvider
java.lang.Object
com.codename1.maps.providers.MapProvider
com.codename1.maps.providers.TiledProvider
com.codename1.maps.providers.GoogleMapsProvider
public class
extends TiledProvider
Field Summary
Modifier and Type
static int
static int
static int
Constructor Summary
Constructor and Description
GoogleMapsProvider(String apiKey)
Method Summary
Modifier and
Type
String
String
static int
boolean
int
void
void
void
Class GoogleMapsProvider
Specifies whether the application requesting the static map is using a sensor
to determine the user's location.
maxZoomLevel()
2154
setTileSize(int aTileSize)
tileFor(BoundingBox bbox)
Tile
Field Detail
REGULAR
public static final int REGULAR
Constructor Detail
GoogleMapsProvider
public GoogleMapsProvider(String apiKey)
Method Detail
Method Summary
2155
Returns:
the tileSize
setTileSize
public static void setTileSize(int aTileSize)
Parameters:
aTileSize
setMapType
public void setMapType(int type)
Maximal zoom level. Zoom levels are counted from zero to maxZoomLevel(). 0 is
farest view, where the scale is greatest.
Specified by:
maxZoomLevel in class MapProvider
Returns:
attribution
public String attribution()
Defines the language to use for display of labels on map tiles. Note that this
parameter is only supported for some country tiles; if the specific language requested
is not supported for the tile set, then the default language for that tileset will be used.
Returns:
the language
setLanguage
public void setLanguage(String language)
Defines the language to use for display of labels on map tiles. Note that this
parameter is only supported for some country tiles; if the specific language requested
is not supported for the tile set, then the default language for that tileset will be used.
Parameters:
language - the language to set
Method Detail
2156
Specifies whether the application requesting the static map is using a sensor to
determine the user's location.
Returns:
the sensor
setSensor
public void setSensor(boolean sensor)
Specifies whether the application requesting the static map is using a sensor to
determine the user's location.
Parameters:
sensor - the sensor to set
Method Detail
2157
Class PointsLayer
java.lang.Object
com.codename1.maps.layers.AbstractLayer
com.codename1.maps.layers.PointsLayer
All Implemented Interfaces:
Layer
public class
extends AbstractLayer
Field Summary
Constructor Summary
Constructor and Description
PointsLayer()
Method Summary
Modifier and
Type
void
void
BoundingBox
void
void
void
void
void
Class PointsLayer
Adds a listener to the Points Layer which will cause an event to dispatch on
click the ActionEvent will contain the pressed PointLayer unprojected
addPoint(PointLayer point)
2158
inherited from
class com.codename1.maps.layers.AbstractLayer
getName, getProjection
Constructor Detail
PointsLayer
public PointsLayer()
Method Detail
setPointIcon
public void setPointIcon(Image icon)
2159
in interface Layer
Specified by:
boundingBox in class AbstractLayer
Returns:
the Layer bounding box
addActionListener
public void addActionListener(ActionListener l)
Adds a listener to the Points Layer which will cause an event to dispatch on click the
ActionEvent will contain the pressed PointLayer unprojected
Parameters:
l - implementation of the action listener interface
removeActionListener
public void removeActionListener(ActionListener l)
Method Detail
2160
Class PointLayer
java.lang.Object
com.codename1.maps.Coord
com.codename1.maps.layers.PointLayer
All Implemented Interfaces:
Layer
public class
extends Coord
implements Layer
Do not use this layer directly, you need to add this layer into a PointsLayer class instance in order for
it to work as expected!
Constructor Summary
Constructor and Description
PointLayer(Coord position, String name, Image icon)
Method Summary
Modifier and Type
BoundingBox
Image
String
getName()
void
void
void
String
toString()
Constructor Detail
Class PointLayer
2161
Method Detail
getName
public String getName()
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
Constructor Detail
2162
Method Detail
2163
Class LinesLayer
java.lang.Object
com.codename1.maps.layers.AbstractLayer
com.codename1.maps.layers.LinesLayer
All Implemented Interfaces:
Layer
Direct Known Subclasses:
ArrowLinesLayer
public class
extends AbstractLayer
Field Summary
Modifier and Type Field and Description
protected int
_lineColor
Constructor Summary
Constructor and Description
LinesLayer()
Method Summary
Modifier and Type
void
BoundingBox
boundingBox()
void
void
protected void
Paint a segment.
Class LinesLayer
2164
Field Detail
_lineColor
protected int _lineColor
Constructor Detail
LinesLayer
public LinesLayer()
Method Detail
paint
public void paint(Graphics g,
Tile screenTile)
Paint a segment.
Parameters:
g - a Graphics Object to paint on
segment - array of Coord to draw a Line.
tile addLineSegment
public void addLineSegment(Coord[] coords)
2165
Method Detail
2166
Interface Layer
All Known Implementing Classes:
AbstractLayer, ArrowLinesLayer, LinesLayer, PointLayer, PointsLayer
public interface
a Layer interface. Each Layer needs to ability to paint itself on the map
Method Summary
Modifier and Type
BoundingBox
String
void
Method Detail
paint
void paint(Graphics g,
Tile screenTile)
Interface Layer
2167
Class ArrowLinesLayer
java.lang.Object
com.codename1.maps.layers.AbstractLayer
com.codename1.maps.layers.LinesLayer
com.codename1.maps.layers.ArrowLinesLayer
All Implemented Interfaces:
Layer
public class
extends LinesLayer
This class is responsible for painting arrows that indicates direction of walk on map.
Field Summary
Constructor Summary
Constructor and Description
ArrowLinesLayer()
Method Summary
Modifier and Type
int
int
int
protected void
void
void
void
Method Detail
2168
inherited from
class com.codename1.maps.layers.LinesLayer
addLineSegment, boundingBox, lineColor, paint
Constructor Detail
ArrowLinesLayer
public ArrowLinesLayer()
Method Detail
paintSegment
protected void paintSegment(Graphics g,
Coord[] segment,
Tile tile)
Paints arrows on each segment. arrowSegmentLength decides how many arrows will
be on each segment.
Overrides:
paintSegment in class LinesLayer
Parameters:
gsegment tile getArrowHeight
public int getArrowHeight()
2169
Method Detail
2170
Class AbstractLayer
java.lang.Object
com.codename1.maps.layers.AbstractLayer
All Implemented Interfaces:
Layer
Direct Known Subclasses:
LinesLayer, PointsLayer
Field Summary
Modifier and Type
protected String
Constructor Summary
Constructor and Description
AbstractLayer(Projection p, String name)
Method Summary
Modifier and Type
abstract BoundingBox
String
Projection
getProjection()
Field Detail
Class AbstractLayer
2171
projection
protected Projection projection
Constructor Detail
AbstractLayer
public AbstractLayer(Projection p,
String name)
Method Detail
getName
public String getName()
Field Detail
2172
Class Tile
java.lang.Object
com.codename1.maps.Tile
Direct Known Subclasses:
ProxyHttpTile
public class
extends Object
This class represents a single tile on a map. a map is been constructed from a few tiles that are been
tiled on next to the other.
Constructor Summary
Constructor and Description
Tile(Dimension dimension, BoundingBox boundingBox, Image image)
Method Summary
Modifier and
Type
Dimension
protected
void
BoundingBox
boolean
void
Paints the tile on the Graphics Object translated to the given x, y, This
method paints the tile image if available or will call paintTileLoading
paintTileLoading(Graphics g)
void
Point
Coord
static void
void
This flag indicates if the Tile should paint a Loading image or Text or simply
not do any painting if a map image is not ready for painting
setsTileReadyListener(ActionListener listener)
static void
static void
String
Method Detail
Sets a static image that will be drawn on the map if the tile image is not
available yet.
setTileLoadingText(String tileLoadingText)
2173
Constructor Detail
Tile
public Tile(Dimension dimension,
BoundingBox boundingBox,
Image image)
Method Detail
pointPosition
public Point pointPosition(Coord point)
2174
Paints the tile on the Graphics Object translated to the given x, y, This method paints
the tile image if available or will call paintTileLoading
Parameters:
g - Graphics object to paint on.
x - translate to x before painting
y - translate to y before painting
paintTileLoading
public void paintTileLoading(Graphics g)
This flag indicates if the Tile should paint a Loading image or Text or simply not do
any painting if a map image is not ready for painting
Parameters:
if - true a Loading rect is displayed when map image is being downloaded
setTileLoadingImage
public static void setTileLoadingImage(Image tileLoadingImage)
Sets a static image that will be drawn on the map if the tile image is not available yet.
Parameters:
tileLoadingImage setTileLoadingText
public static void setTileLoadingText(String tileLoadingText)
Sets a static text to paint. This will be used if the map if the tile image is not available
yet and the tileLoadingImage is null
Parameters:
tileLoadingText setsTileReadyListener
public void setsTileReadyListener(ActionListener listener)
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Method Detail
2175
Method Detail
in class Object
2176
Class ProxyHttpTile
java.lang.Object
com.codename1.maps.Tile
com.codename1.maps.ProxyHttpTile
public class
extends Tile
This Tile brings the tile image from a given http url.
Constructor Summary
Constructor and Description
ProxyHttpTile(Dimension tileSize, BoundingBox bbox, String url)
Method Summary
Modifier and Type
boolean
Constructor Detail
ProxyHttpTile
public ProxyHttpTile(Dimension tileSize,
BoundingBox bbox,
String url)
Method Detail
paint
public boolean paint(Graphics g)
Class ProxyHttpTile
2177
Method Detail
2178
Class Projection
java.lang.Object
com.codename1.maps.Projection
Direct Known Subclasses:
Mercator
This class represents a projection type. a Projection has the ability to translate a WGS84 Coordinate
to a projected Coordinate.
Constructor Summary
Modifier
protected
Method Summary
Modifier and
Type
BoundingBox
BoundingBox
abstract Coord
Coord[]
BoundingBox
abstract Coord
Constructor Detail
Projection
protected Projection(BoundingBox extent)
Class Projection
2179
Detail
extent
public BoundingBox extent()
Method Detail
2180
Class Mercator
java.lang.Object
com.codename1.maps.Projection
com.codename1.maps.Mercator
public class
extends Projection
Constructor Summary
Constructor and Description
Mercator()
Method Summary
Modifier and
Type
static Coord
Coord
static Coord
Coord
Constructor Detail
Mercator
public Mercator()
Method Detail
Class Mercator
2181
Method Detail
2182
Interface MapListener
public interface
Method Summary
Modifier and Type
void
Method Detail
mapPositionUpdated
void mapPositionUpdated(Component source,
int zoom,
Coord center)
Interface MapListener
2183
Class MapComponent
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.maps.MapComponent
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
All communication with the map and layers should be done in WGS84, it takes care of coordinates
transformation.
Field Summary
Constructor Summary
Constructor and Description
MapComponent()
Empty constructor creates a map with OpenStreetMapProvider on the Last known Location
of the LocationManager
MapComponent(MapProvider provider)
Constructor
MapComponent(MapProvider provider, Coord centerPosition, int zoomLevel,
boolean cacheEnabled)
Constructor
MapComponent(MapProvider provider, Location centerPosition, int zoomLevel)
Constructor
MapComponent(MapProvider provider, Location centerPosition, int zoomLevel,
boolean cacheEnabled)
Constructor
Method Summary
Modifier and
Type
void
void
void
Method Detail
2184
static long
calcPreferredSize()
focusGained()
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
MapProvider
int
Returns the current value of the property name, this method is used by the
GUI builder
getProvider()
protected
boolean
isDownKey(int keyCode)
protected
boolean
isLeftKey(int keyCode)
protected
boolean
isRightKey(int keyCode)
protected
boolean
isUpKey(int keyCode)
protected
boolean
isZoomInKey(int keyCode)
protected
boolean
isZoomOutKey(int keyCode)
protected
boolean
isZoomToLayersKey(int keyCode)
void
protected
void
void
void
Method Summary
If this Component is focused, the key pressed event will call this method
laidOut()
This is a callback method to inform the Component when it's been laidout
on the parent Container
moveDown()
2185
void
void
void
pointerDragged(int[] x, int[] y)
void
If this Component is focused, the pointer dragged event will call this method
pointerDragged(int x, int y)
void
If this Component is focused, the pointer dragged event will call this method
pointerPressed(int x, int y)
void
If this Component is focused, the pointer pressed event will call this method
pointerReleased(int x, int y)
void
If this Component is focused, the pointer released event will call this method
protected
void
void
void
void
Repaint this Component, the repaint call causes a callback of the paint
method on the event dispatch thread.
void
Sets a new value to the given property, returns an error message if failed
and null if successful.
String
setZoomLevel(int zoom)
void
protected
boolean
shouldBlockSideSwipe()
A component that might need side swipe such as the slider could block it
from being used for some other purpose when on top of said component.
zoomIn()
void
void
void
void
Zoom map to the center of the given coordinate with the given zoom level
zoomToLayers()
void
2186
Constructor Detail
MapComponent
public MapComponent()
2187
Constructor
Parameters:
provider - map provider
centerPosition - center position
zoomLevel - zoom level
MapComponent
public MapComponent(MapProvider provider,
Location centerPosition,
int zoomLevel,
boolean cacheEnabled)
Constructor
Parameters:
provider - map provider
centerPosition - center position
zoomLevel - zoom level
cacheEnabled - is cache enabled
MapComponent
public MapComponent(MapProvider provider,
Coord centerPosition,
int zoomLevel)
Constructor
Parameters:
provider - map provider
centerPosition - center position
zoomLevel - zoom level
MapComponent
public MapComponent(MapProvider provider,
Coord centerPosition,
int zoomLevel,
boolean cacheEnabled)
Constructor
Parameters:
provider - map provider
centerPosition - center position
zoomLevel - zoom level
cacheEnabled - is cache enabled
Method Detail
paintBackground
public void paintBackground(Graphics g)
Constructor Detail
2188
laidOut
protected void laidOut()
This is a callback method to inform the Component when it's been laidout on the
parent Container
Overrides:
laidOut in class Component
shouldBlockSideSwipe
protected boolean shouldBlockSideSwipe()
A component that might need side swipe such as the slider could block it from being
used for some other purpose when on top of said component.
Overrides:
shouldBlockSideSwipe in class Component
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Container
Returns:
the calculated preferred size based on component content
focusGained
protected void focusGained()
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerPressed
public void pointerPressed(int x,
int y)
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Container
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerDragged
public void pointerDragged(int[] x,
int[] y)
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
Method Detail
2189
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
getCoordFromPosition
public Coord getCoordFromPosition(int x,
int y)
If this Component is focused, the key pressed event will call this method
Overrides:
keyPressed in class Container
Parameters:
keyCode - the key code value to indicate a physical key.
addLayer
public void addLayer(Layer layer)
Method Detail
2190
moveLeft
public void moveLeft()
Method Detail
2191
Zoom map to the center of the given coordinate with the given zoom level
Parameters:
coord - center map to this coordinate, coord should be in wg84 format
zoomLevel - zoom map to this level;
Throws:
IllegalArgumentException - if the coord is not wg84 format
zoomToLayers
public void zoomToLayers()
Method Detail
2192
latitude1,
longitude1,
latitude2,
longitude2)
Method Detail
2193
Returns:
distance in meters
addMapListener
public void addMapListener(MapListener listener)
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
2194
Class Coord
java.lang.Object
com.codename1.maps.Coord
Direct Known Subclasses:
PointLayer
public class
extends Object
Constructor Summary
Constructor and Description
Coord(Coord toClone)
Copy Constructor
Coord(double latitude, double longitude)
Method Summary
Modifier and
Type
boolean
double
double
int
boolean
void
void
void
String
Coord
Coord
Class Coord
2195
Constructor Detail
Coord
public Coord(double latitude,
double longitude)
Copy Constructor
Parameters:
toClone - to copy
Method Detail
getLongitude
public double getLongitude()
2196
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
translate
public Coord translate(double latitude,
double longitude)
Create a new Coord object which is translated with the given coordinates
Parameters:
latitude - translate current latitude with this latitude
longitude - translate current longitude with this longitude
Returns:
a new translated Coord object
translate
public Coord translate(Coord coordinates)
Create a new Coord object which is translated with the given coordinates
Parameters:
coordinates - translate current Coord with the given coordinates
Returns:
a new translated Coord object
equals
public boolean equals(Object other)
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Object
hashCode
public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of
hashtables such as those provided by java.util.Hashtable. The general contract of
hashCode is: Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application. If two objects are equal
according to the equals(Object) method, then calling the hashCode method on each
of the two objects must produce the same integer result. It is not required that if two
objects are unequal according to the equals(java.lang.Object) method, then calling
the hashCode method on each of the two objects must produce distinct integer
Method Detail
2197
Method Detail
2198
Class BoundingBox
java.lang.Object
com.codename1.maps.BoundingBox
public class
extends Object
Constructor Summary
Constructor and Description
BoundingBox(Coord southWest, Coord northEast)
Method Summary
Modifier and
Type
boolean
static
BoundingBox
static
BoundingBox
boolean
create a smallest bounding box that contains all of the given coordinates
create(Vector coords)
/** create a smallest bounding box that contains all of the given
coordinates
equals(Object other)
BoundingBox
create a new bounding box that extends this bounding box with the
given bounding box
getNorthEast()
Coord
Coord
int
double
latitudeDifference()
double
longitudeDifference()
boolean
String
projected()
Class BoundingBox
2199
Detail
BoundingBox
public BoundingBox(Coord southWest,
Coord northEast)
Method Detail
getSouthWest
public Coord getSouthWest()
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
latitudeDifference
public double latitudeDifference()
Returns:
The difference between SE and NW getLongitude in degrees.
longitudeDifference
public double longitudeDifference()
Returns:
The difference between SE and NW latitudes in degrees.
contains
public boolean contains(Coord cur)
Constructor Detail
2200
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Object
hashCode
public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of
hashtables such as those provided by java.util.Hashtable. The general contract of
hashCode is: Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application. If two objects are equal
according to the equals(Object) method, then calling the hashCode method on each
of the two objects must produce the same integer result. It is not required that if two
objects are unequal according to the equals(java.lang.Object) method, then calling
the hashCode method on each of the two objects must produce distinct integer
results. However, the programmer should be aware that producing distinct integer
results for unequal objects may improve the performance of hashtables. As much as
is reasonably practical, the hashCode method defined by class Object does return
distinct integers for distinct objects. (This is typically implemented by converting the
internal address of the object into an integer, but this implementation technique is not
required by the JavaTM programming language.)
Overrides:
hashCode in class Object
create
public static BoundingBox create(Coord[] coords)
create a smallest bounding box that contains all of the given coordinates
Parameters:
coords - given coordinates to create a wrapping bounding box.
Returns:
a bounding box that contains all of the coordinates
create
public static BoundingBox create(Vector coords)
/** create a smallest bounding box that contains all of the given coordinates
Parameters:
coords - given coordinates to create a wrapping bounding box.
Returns:
a bounding box that contains all of the coordinates
extend
public BoundingBox extend(BoundingBox other)
create a new bounding box that extends this bounding box with the given bounding
box
Parameters:
Method Detail
2201
other - a bounding box that needs to extends the current bounding box
Returns:
a new bounding box that was extended from the current and the other
projected
public boolean projected()
Method Detail
2202
Class MakerPlugin
java.lang.Object
com.codename1.maker.MakerPlugin
Deprecated.
this class is no longer supported and will be removed in an upcoming revision
public abstract class
extends Object
A Maker plugin allows developers to build extensions to the Codename One Maker tool, it is
implemented as an abstract class to allow future extensibility.
Constructor Summary
Constructor and Description
MakerPlugin()
Deprecated.
Method Summary
Modifier and Type
abstract Container
Deprecated.
Creates a container version of the UI that will be added to the
flow based on maker logic
createStandaloneUI()
Form
Deprecated.
Creates a standalone version of the UI that will be shown by
the maker tool, notice that back functionality will be added by
the maker tool and should not be incorporated into the form!
The default implementation just used the embedded container
version.
getDescription()
String
Deprecated.
The description that the user has set to this plugin
getDeveloperEmailId()
abstract String
Deprecated.
Returns the email for the developer used in registration to the
Codename One build server
getIcon()
EncodedImage
Deprecated.
The icon that the user has set to this plugin
getMetaData()
Hashtable<String,Object>
Deprecated.
The meta data associated with the given plugin based on the
definitions in the accompanying plugin descriptor file
getPackageName()
abstract String
Deprecated.
A unique identifier for this specific plugin
getPluginName()
abstract String
Class MakerPlugin
Deprecated.
Returns the user displayable name of the plugin
2203
Deprecated.
The title that the user has set to this plugin
String
setDescription(String description)
Deprecated.
The description that the user has set to this plugin
void
setIcon(EncodedImage icon)
Deprecated.
The icon that the user has set to this plugin
void
setMetaData(Hashtable<String,Object> data)
Deprecated.
The meta data associated with the given plugin based on the
definitions in the accompanying plugin descriptor file
void
setTitle(String title)
Deprecated.
The title that the user has set to this plugin
void
Constructor Detail
MakerPlugin
public MakerPlugin()
Deprecated.
Method Detail
getPackageName
public abstract String getPackageName()
Deprecated.
A unique identifier for this specific plugin
Returns:
the package of the plugin in the form of com.companyname.pluginname etc.
getDeveloperEmailId
public abstract String getDeveloperEmailId()
Deprecated.
Returns the email for the developer used in registration to the Codename One build
server
Returns:
the email for the developer used in registration to the Codename One build
server
getPluginName
public abstract String getPluginName()
Deprecated.
Returns the user displayable name of the plugin
Returns:
the user displayable name of the plugin
Method Summary
2204
Deprecated.
The title that the user has set to this plugin
Returns:
the title
setTitle
public final void setTitle(String title)
Deprecated.
The title that the user has set to this plugin
Parameters:
title - the title to set
getDescription
public final String getDescription()
Deprecated.
The description that the user has set to this plugin
Returns:
the description
setDescription
public final void setDescription(String description)
Deprecated.
The description that the user has set to this plugin
Parameters:
description - the description to set
getIcon
public final EncodedImage getIcon()
Deprecated.
The icon that the user has set to this plugin
Returns:
the icon
setIcon
public final void setIcon(EncodedImage icon)
Deprecated.
The icon that the user has set to this plugin
Parameters:
icon - the icon to set
setMetaData
public final void setMetaData(Hashtable<String,Object> data)
Deprecated.
The meta data associated with the given plugin based on the definitions in the
accompanying plugin descriptor file
Parameters:
data - the data
getMetaData
public final Hashtable<String,Object> getMetaData()
Deprecated.
The meta data associated with the given plugin based on the definitions in the
accompanying plugin descriptor file
Returns:
the data
Method Detail
2205
Deprecated.
Creates a container version of the UI that will be added to the flow based on maker
logic
Returns:
the embedded UI
createStandaloneUI
public Form createStandaloneUI()
Deprecated.
Creates a standalone version of the UI that will be shown by the maker tool, notice
that back functionality will be added by the maker tool and should not be incorporated
into the form! The default implementation just used the embedded container version.
Normally developers don't need to override this method unless they need specific
behavior for a form
Returns:
the standalone UI
Method Detail
2206
Class LocationRequest
java.lang.Object
com.codename1.location.LocationRequest
public class
extends Object
This class is used when requesting to listen to location update. See setLocationListener
Field Summary
Modifier and Type
static int
static int
static int
When accuracy is not highly important and you want to save battery
Constructor Summary
Constructor and Description
LocationRequest()
Empty Constructor
LocationRequest(int priority, long interval)
Simple Constructor
Method Summary
Modifier and Type
long
int
Field Detail
PRIORITY_HIGH_ACCUARCY
public static int PRIORITY_HIGH_ACCUARCY
Class LocationRequest
2207
When accuracy is not highly important and you want to save battery
PRIORITY_LOW_ACCUARCY
public static int PRIORITY_LOW_ACCUARCY
Constructor Detail
LocationRequest
public LocationRequest()
Empty Constructor
LocationRequest
public LocationRequest(int priority,
long interval)
Simple Constructor
Parameters:
priority - The priority we are interested to listen for location updates.
PRIORITY_HIGH_ACCUARCY, PRIORITY_MEDIUM_ACCUARCY,
PRIORITY_LOW_ACCUARCY High priority means gps locations which is
CPU intensive and consumes more battery. Medium priority is less intensive
in terms of battery and might return a gps or a network location which is less
accurate. Low priority won't consume the battery and will return a gps
location if available otherwise the location would be a network location.
interval - time in milliseconds which determines what are the time intervals
that we would like to get updates from the OS. This is a request only and
might not be respected by the underlying OS
Method Detail
getPriority
public int getPriority()
Field Detail
2208
Class LocationManager
java.lang.Object
com.codename1.location.LocationManager
Field Summary
Modifier and Type
static int
AVAILABLE
static int
OUT_OF_SERVICE
static int
TEMPORARILY_UNAVAILABLE
Constructor Summary
Constructor and Description
LocationManager()
Method Summary
Modifier and Type
void
protected void
protected abstract
void
Method Detail
2209
clearBackgroundListener()
protected Class
abstract Location
Gets the current Location of the device, in most cases this uses
the GPS.
getCurrentLocationSync()
Location
Location
abstract Location
protected
LocationListener
static LocationManager
protected
LocationRequest
int
boolean
boolean
boolean
boolean
void
void
void
void
protected void
Method Summary
2210
Field Detail
AVAILABLE
public static final int AVAILABLE
See Also:
Constant Field Values
OUT_OF_SERVICE
public static final int OUT_OF_SERVICE
See Also:
Constant Field Values
TEMPORARILY_UNAVAILABLE
public static final int TEMPORARILY_UNAVAILABLE
See Also:
Constant Field Values
Constructor Detail
LocationManager
public LocationManager()
Method Detail
getLocationManager
public static LocationManager getLocationManager()
Gets the current Location of the device, in most cases this uses the GPS. Notice!
This method will only return a valid value after the location listener callback returns
Returns:
2211
Returns the current location synchronously, this is useful if you just want to know the
location NOW and don't care about tracking location. Notice that this method will
block until a result is returned so you might want to use something like
InfiniteProgress while this is running
Returns:
the current location or null in case of an error
getCurrentLocationSync
public Location getCurrentLocationSync(long timeout)
Returns the current location synchronously, this is useful if you just want to know the
location NOW and don't care about tracking location. Notice that this method will
block until a result is returned so you might want to use something like
InfiniteProgress while this is running
Parameters:
timeout - timeout in milliseconds or -1 to never timeout
Returns:
the current location or null in case of an error
getLastKnownLocation
public abstract Location getLastKnownLocation()
Sets a LocationListener on the device, use this method if you need to be updated on
the device Locations rather then calling getCurrentLocation.
Parameters:
l - a LocationListener or null to stop the current listener from getting updates
setLocationListener
public void setLocationListener(LocationListener l,
LocationRequest req)
Sets a LocationListener on the device, use this method if you need to be updated on
the device Locations rather then calling getCurrentLocation.
Parameters:
l - a LocationListener or null to stop the current listener from getting updates
req - provide the settings in which we are interested to get updates to the
Listener.
setBackgroundLocationListener
public void setBackgroundLocationListener(Class locationListener)
Use this method to track background location updates when the application is not
running anymore. Do not perform long operations here, iOS wake-up time is very
short(around 10 seconds). Notice this listener can sends events also when the app is
in the foreground, therefore it is recommended to check the app state before deciding
how to process this event. Use Display.isMinimized() to know if the app is currently
running.
Parameters:
locationListener - a class that implements the LocationListener interface
this class must have an empty constructor since the underlying
implementation will try to create an instance and invoke the locationUpdated
method
Method Detail
2212
Adds a geo fence listener to gets an event once the device is in/out of the Geofence
range. The GeoFence events can arrive in the background therefore it is
recommended to check the app state before deciding how to process this event. Use
Display.isMinimized() to know if the app is currently running. if
isGeofenceSupported() returns false this method does nothing
NOTE: For iOS you must include the ios.background_modes build hint with a value
that includes "location" for geofencing to work.
Parameters:
- a Class that implements the GeofenceListener interface this class
must have an empty constructor
gf - a Geofence to track
removeGeoFencing
listener
Method Detail
2213
Returns true if the platform is able to detect if the GPS is on or off. see also
isGPSEnabled()
Returns:
true if platform is able to detect GPS on/off
isBackgroundLocationSupported
public boolean isBackgroundLocationSupported()
Method Detail
2214
Interface LocationListener
public interface
Method Summary
Modifier and
Type
void
This method is been called by the system when Location is being updated
providerStateChanged(int newState)
This method is been called by the system when the provider state has
being Changed
void
Method Detail
locationUpdated
void locationUpdated(Location location)
This method is been called by the system when Location is being updated
Parameters:
location - a Location Object
providerStateChanged
void providerStateChanged(int newState)
This method is been called by the system when the provider state has being
Changed
Parameters:
newState - a new state one of the following: LocationManager.AVAILABLE,
LocationManager.OUT_OF_SERVICE or
LocationManager.TEMPORARILY_UNAVAILABLE
Interface LocationListener
2215
Class Location
java.lang.Object
com.codename1.location.Location
public class
extends Object
Constructor Summary
Constructor and Description
Location()
Method Summary
Modifier
and Type
float
double
float
double
double
double
Deprecated.
use getLongitude
getStatus()
int
long
float
void
void
void
void
void
void
Method Detail
Deprecated.
use setLongitude
2216
void
setTimeStamp(long timeStamp)
void
void
String
toString()
Constructor Detail
Location
public Location()
Method Detail
getAccuracy
public float getAccuracy()
Method Summary
2217
setAltitude
public void setAltitude(double altitude)
Method Detail
2218
setStatus
public void setStatus(int status)
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
Method Detail
2219
Interface GeofenceListener
public interface
Method Summary
Modifier and Type
onEntered(String id)
void
This callback gets called once the device enters the Geofence area
onExit(String id)
void
This callback gets called once the device is out of the Geofence area
Method Detail
onExit
void onExit(String id)
This callback gets called once the device is out of the Geofence area
onEntered
void onEntered(String id)
This callback gets called once the device enters the Geofence area
Interface GeofenceListener
2220
Class Geofence
java.lang.Object
com.codename1.location.Geofence
public class
extends Object
Metadata for geofencing support that allows tracking user location in the background while the app is
inactive. Usage:
public class GeofenceListenerImpl implements GeofenceListener {
public void onExit(String id) {
System.out.println("Exited "+id);
}
public void onEntered(String id) {
System.out.println("Entered "+id);
}
}
Form hi = new Form("Hi World");
hi.addComponent(new Label("Hi World"));
Location loc = new Location();
loc.setLatitude(51.5033630);
loc.setLongitude(-0.1276250);
Geofence gf = new Geofence("test", loc, 100, 100000);
LocationManager.getLocationManager().addGeoFencing(GeofenceListenerImpl.class, gf);
hi.show();
Constructor Summary
Constructor and Description
Geofence(String id, Location loc, int radius, long expiration)
Constructor
Method Summary
Modifier and Type Method and Description
getExpiration()
long
Simple Getter
getId()
String
Simple Getter
Location
getLoc()
Simple Getter
getRadius()
int
Simple Getter
Constructor Detail
Method Detail
2221
Constructor
Parameters:
id - unique identifier
loc - the center location of this Geofence
radius - the radius in meters
expiration - the expiration time in milliseconds
Method Detail
getId
public String getId()
Simple Getter
Returns:
the id
getLoc
public Location getLoc()
Simple Getter
Returns:
the center Location
getExpiration
public long getExpiration()
Simple Getter
Returns:
the Geofence expiration
getRadius
public int getRadius()
Simple Getter
Returns:
Geofence radius
Constructor Detail
2222
Class SimpleDateFormat
java.lang.Object
com.codename1.l10n.Format
com.codename1.l10n.DateFormat
com.codename1.l10n.SimpleDateFormat
All Implemented Interfaces:
Cloneable
public class
extends DateFormat
A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API. See
http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
Field Summary
Constructor Summary
Constructor and Description
SimpleDateFormat()
Method Summary
Modifier and Type
void
Object
clone()
format(Date source)
String
DateFormatSymbols
Date
void
String
toPattern()
Method Detail
2223
Constructor Detail
SimpleDateFormat
public SimpleDateFormat()
Method Detail
toPattern
public String toPattern()
Returns:
the pattern
getDateFormatSymbols
public DateFormatSymbols getDateFormatSymbols()
Get the date format symbols for parsing/formatting textual components of dates in a
localization sensitive way.
Returns:
current symbols.
setDateFormatSymbols
public void setDateFormatSymbols(DateFormatSymbols newSymbols)
Apply new date format symbols for parsing/formatting textual components of dates in
a localisation sensitive way.
Parameters:
newSymbols - new format symbols.
applyPattern
public void applyPattern(String pattern)
Overrides:
clone
in class DateFormat
format
public String format(Date source)
2224
in class DateFormat
Parameters:
source - date to be formatted.
Returns:
formatted date.
parse
public Date parse(String source)
throws ParseException
Method Detail
2225
Class ParseException
java.lang.Object
java.lang.Throwable
java.lang.Exception
com.codename1.l10n.ParseException
public class
extends Exception
Constructor Summary
Constructor and Description
ParseException(String s, int errorOffset)
Method Summary
Modifier and Type Method and Description
int
getErrorOffset()
Constructor Detail
ParseException
public ParseException(String s,
int errorOffset)
Parameters:
errorOffset
Method Detail
getErrorOffset
public int getErrorOffset()
Returns:
the errorOffset
Class ParseException
2226
Class L10NManager
java.lang.Object
com.codename1.l10n.L10NManager
public class
extends Object
The localization manager allows adapting values for display in different locales
Constructor Summary
Modifier
protected
Method Summary
Modifier and Type
String
String
String
String
String
String
String
String
String
String
static L10NManager
String
String
boolean
double
double
int
Method Detail
Returns the current locale language as an ISO 639 two letter code
getLocale()
2227
long
void
Constructor Detail
L10NManager
protected L10NManager(String language,
String locale)
Method Detail
getLanguage
public String getLanguage()
Returns the current locale language as an ISO 639 two letter code
Returns:
iso language string
setLocale
public void setLocale(String locale,
String language)
Method Summary
2228
Method Detail
2229
Method Detail
2230
Class Format
java.lang.Object
com.codename1.l10n.Format
All Implemented Interfaces:
Cloneable
Direct Known Subclasses:
DateFormat
An abstract class for parsing and formatting localisation sensitive information, compatible with JDK 6.
See Also:
http://docs.oracle.com/javase/6/docs/api/java/text/Format.html
Constructor Summary
Constructor and Description
Format()
Method Summary
Modifier and Type
abstract String
abstract Object
Format an object.
parseObject(String source)
Constructor Detail
Format
public Format()
Method Detail
format
public abstract String format(Object source)
throws IllegalArgumentException
Format an object.
Parameters:
source - object to be formatted to text.
Returns:
formatted text.
Throws:
Class Format
2231
parseObject
public abstract Object parseObject(String source)
throws ParseException
Method Detail
2232
Class DateFormatSymbols
java.lang.Object
com.codename1.l10n.DateFormatSymbols
All Implemented Interfaces:
Cloneable
public class
extends Object
implements Cloneable
Field Summary
Modifier and Type Field and Description
static int
ZONE_ID
static int
ZONE_LONGNAME
static int
ZONE_LONGNAME_DST
static int
ZONE_SHORTNAME
static int
ZONE_SHORTNAME_DST
Constructor Summary
Constructor and Description
DateFormatSymbols()
Method Summary
Modifier and Type
Object
clone()
String[]
getAmPmStrings()
String[]
getEras()
String[]
getMonths()
Hashtable<String,String>
getResourceBundle()
String[]
getShortMonths()
String[]
getShortWeekdays()
String[]
getWeekdays()
String[][]
getZoneStrings()
void
setAmPmStrings(String[] newAmpms)
void
setEras(String[] newEras)
void
setMonths(String[] newMonths)
void
setResourceBundle(Hashtable<String,String> newResourceBundle)
void
setShortMonths(String[] newShortMonths)
void
setShortWeekdays(String[] newShortWeekdays)
void
setWeekdays(String[] newWeekdays)
void
setZoneStrings(String[][] newZoneStrings)
Class DateFormatSymbols
2233
Field Detail
ZONE_ID
public static final int ZONE_ID
See Also:
Constant Field Values
ZONE_LONGNAME
public static final int ZONE_LONGNAME
See Also:
Constant Field Values
ZONE_SHORTNAME
public static final int ZONE_SHORTNAME
See Also:
Constant Field Values
ZONE_LONGNAME_DST
public static final int ZONE_LONGNAME_DST
See Also:
Constant Field Values
ZONE_SHORTNAME_DST
public static final int ZONE_SHORTNAME_DST
See Also:
Constant Field Values
Constructor Detail
DateFormatSymbols
public DateFormatSymbols()
Method Detail
getAmPmStrings
public String[] getAmPmStrings()
setAmPmStrings
public void setAmPmStrings(String[] newAmpms)
getResourceBundle
public Hashtable<String,String> getResourceBundle()
setResourceBundle
public void setResourceBundle(Hashtable<String,String> newResourceBundle)
getZoneStrings
public String[][] getZoneStrings()
2234
setShortWeekdays
public void setShortWeekdays(String[] newShortWeekdays)
getShortWeekdays
public String[] getShortWeekdays()
getWeekdays
public String[] getWeekdays()
setWeekdays
public void setWeekdays(String[] newWeekdays)
setShortMonths
public void setShortMonths(String[] newShortMonths)
getShortMonths
public String[] getShortMonths()
setMonths
public void setMonths(String[] newMonths)
getMonths
public String[] getMonths()
getEras
public String[] getEras()
setEras
public void setEras(String[] newEras)
clone
public Object clone()
Method Detail
2235
Class DateFormatPatterns
java.lang.Object
com.codename1.l10n.DateFormatPatterns
public class
extends Object
Field Summary
Modifier and Type
static String
static String
static String
static String
static String
static String
static String
static String
Constructor Summary
Constructor and Description
DateFormatPatterns()
Method Summary
Field Detail
RFC2822
public static final String RFC2822
Class DateFormatPatterns
2236
Constructor Detail
DateFormatPatterns
public DateFormatPatterns()
Field Detail
2237
Class DateFormat
java.lang.Object
com.codename1.l10n.Format
com.codename1.l10n.DateFormat
All Implemented Interfaces:
Cloneable
Direct Known Subclasses:
SimpleDateFormat
public class
extends Format
A class for parsing and formatting localisation sensitive dates, compatible with Jave 6 SDK. This
implementation uses the Codename One localization manager for handling formatting dates. Parsing
dates is not implemented in this class since the localization pattern is not exposed.
See Also:
http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
Field Summary
Modifier and Type
static int
static int
static int
static int
static int
Method Summary
Modifier and
Type
Object
boolean
String
String
static
DateFormat
getDateInstance()
static
DateFormat
getDateInstance(int style)
static
DateFormat
static
DateFormat
Constructor Detail
2238
getTimeInstance()
static
DateFormat
getTimeInstance(int style)
int
Date
Object
Field Detail
FULL
public static final int FULL
Method Detail
format
public String format(Object obj)
throws IllegalArgumentException
Method Summary
2239
getInstance
public static final DateFormat getInstance()
Method Detail
2240
Get a DateFormat instance that uses a given style for dates and times.
Parameters:
style - style to use for parsing and formatting (SHORT, MEDIUM, LONG,
FULL, DEFAULT);
Returns:
a DateFormat instance.
See Also:
SHORT, MEDIUM, LONG, FULL, DEFAULT
hashCode
public int hashCode()
Method Detail
2241
Method Detail
2242
Class JavascriptContext
java.lang.Object
com.codename1.javascript.JavascriptContext
public class
extends Object
Represents a Javascript context of a single BrowserComponent. This provides support for executing
Javascript in the BrowserComponent, registering Java callbacks to allow Javascript to call Java
functions, and returning values from Javascript to Java.
Typically you would obtain a context for a BrowserComponent via its constructor, passing the
BrowserComponent to the context.
E.g.
WebBrowser b = new WebBrowser();
BrowserComponent bc = (BrowserComponent)b.getInternal();
JavascriptContext ctx = new JavascriptContext(bc);
JSObject window = (JSObject)ctx.get("window");
Field Summary
Modifier and Type
static boolean
Constructor Summary
Constructor and Description
JavascriptContext(BrowserComponent c)
Method Summary
Modifier
and Type
Object
Object
Object
void
void
void
Object
Class JavascriptContext
cleanup()
2243
JSObject
getWindow()
set(String key, Object value)
void
void
void
void
Field Detail
DEBUG
public static boolean DEBUG
Constructor Detail
JavascriptContext
public JavascriptContext(BrowserComponent c)
Method Detail
setBrowserComponent
public final void setBrowserComponent(BrowserComponent c)
Executes a javascript string and returns the result of the execution as an appropriate
object value depending on the type of value that was returned.
Return value types will depend on the Javascript type returned. The following table
shows the mappings:
Method Summary
2244
java.lang.Boolean
JSObject
JSObject
null
null
Example
//Get the window object
JSObject window = (JSObject)ctx.get("window");
// Create a new empty Javascript Object
JSObject newObj = (JSObject)ctx.get("{}");
// Get the current document body contents as a string.
String html = (String)ctx.get("document.body.innerHTML");
// Get a numerical result
Double result = (Double)ctx.get("1+2");
// Get a Javascript function object
JSObject func = (JSObject)ctx.get("function(a,b){ return a+b }");
// Get a boolean result
Boolean res = (Boolean)ctx.get("1 < 2");
Parameters:
javascript - The javascript to be executed.
Returns:
The result of the javascript expression.
getWindow
public JSObject getWindow()
getAsync
public void getAsync(String javascript,
Callback callback)
set
public void set(String key,
Object value)
Sets a Javascript value given a compatible Java object value. This is an abstraction
upon javascript to execute key = value.
The key is any Javascript expression whose result can be assigned. The value is a
Java object that will be converted into a Javascript object as follows:
Java type Converted to
Double
Number
Integer
Number
Float
Number
Long
Number
String
String
JSObject Object by ref
null
null
Hence if you want to set a Javascript string value, you can just pass a Java string into
this method and it will be converted.
JSObject "By Ref"
You may notice that if you pass a JSObject as the value parameter, the table above
indicates that it is passed by reference. A JSObject merely stores a reference to a
Method Detail
2245
Parameters:
key - A javascript expression whose result is being assigned the value.
value - The object or value that is being assigned to the Javascript variable
on the left.
set
public void set(String key,
Object value,
boolean async)
setAsync
public void setAsync(String key,
Object value)
call
public Object call(JSObject func,
JSObject self,
Object[] params)
Method Detail
2246
Parameters:
func - The Javascript function object that is being called.
self - Javascript Object that should act as "this" for the function call.
params - The parameters that should be passed to the function. These
parameters should be passed as Java objects but will be converted into their
associated Javascript version.
Returns:
The result of the function call. Javascript results will be automatically
converted to their associated Java types.
callAsync
public void callAsync(JSObject
JSObject
Object[]
Callback
func,
self,
params,
callback)
call
public Object call(String jsFunc,
JSObject self,
Object[] params)
Calls a Javascript function with the given parameters. This would translate roughly
into executing the following javascript: jsFunc.call(self, param1, param1, ...,
paramn)
Parameters:
- A javascript expression that resolves to a function object that is to be
called.
self - The Javascript object that is used as "this" for the method call.
params - Array of the Javascript parameters, as Java objects. These use the
same conversions as are described in the docs for set().
Returns:
Returns the return value converted to the corresponding Java object type.
callAsync
jsFunc
call
public Object call(String jsFunc,
JSObject self,
Object[] params,
boolean async,
Callback callback)
Method Detail
2247
Class JSObject
java.lang.Object
com.codename1.javascript.JSObject
public class
extends Object
A Java Wrapper around a Javascript object. In Javascript there are only a few different types:
Number, String, Boolean, Null, Undefined, and Object. Arrays and functions are objects also.
A JSObject is associated with a particular JavascriptContext and it is backed by a Javascript object
inside the javascript context. This object acts as a proxy to call methods and access properties of the
actual javascript object.
All return values for Javascript calls in the JavascriptContext will be converted to the appropriate
Java type. Javascript objects will automatically be wrapped in a JSObject proxy.
Getting and Setting Properties
JSObject provides get(String) and set(String,Object) methods to get and set properties on the
object. E.g.
obj.set("name", "Steve");
obj.set("age", 12);
String name = (String)obj.get("name");
Double age = (Double)obj.get("age");
// Steve
// 12.0
Typed Getters
The return value of get(String) will be one of Double, String, Boolean, or JSObject depending on the
type of Javascript value that is being returned. get(String) requires you to cast the return value to
the correct type, which is a bit a pain. Luckily, JSObject provides a set of typed getter methods that
will automatically cast to particular types:
getInt()
getString()
getDouble()
getObject()
getBoolean()
Returns int
Returns String
Returns double
Returns JSObject
Returns boolean
Indexed Properties
JSObject can wrap Javascript arrays also. You can retrieve the indexed properties of the array using
indexed versions of get(int) and set(int,Object) (i.e. they take an int as their first parameter
instead of a String). There are also typed versions of the indexed get(int) method to allow directly
returning values of the correct type without having to type cast
Example, looping through array
JSObject allows you to call Javascript object methods on the wrapped Javascript object via the its
call(String,Object[]) method. It takes the name of the method (i.e. property name that stores the
function), and an array of parameters to pass to the method.
Class JSObject
2248
Since, in Javascript, functions are objects, it is possible to wrap a function with a JSObject object also.
You can then call the function using the alternate version of the #call(JSObject,Object[]) method.
JSObject window = (JSObject)context.get("window");
// reference to the window object so that we can pass it as the context
// of the function call.
JSObject myfunc = (JSObject)context.get("function(a,b){ return a+b}");
Double result = (Double)myfunc.call(window, new Object[]{new Integer(1), new Integer(2)});
The JSFunction interface allows you to implement functions in Java that can be called from
Javascript. You can assign any JSFunction object to be a member method of an existing JSObject via
the JSObject.set() method. Then the function can be called from javascript just like any other
Javascript method. JSFunction methods are called asynchronously from Javascript to prevent
deadlocks. If you require a return value to Javascript, you can do that by passing a callback function
which is called by the JSFunction with some parameters.
The following example, adds a camera object to the Javascript environment that has a capture()
method, which can be used to capture images using the device's camera:
// Create a new Javascript object "camera"
final JSObject camera = (JSObject)ctx.get("{}");
// Create a capture() method on the camera object
// as a JSFunction callback.
camera.set("capture", new JSFunction(){
public void apply(JSObject self, final Object[] args) {
Display.getInstance().capturePhoto(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
String imagePath = (String)evt.getSource();
// Get the callback function that was provided
// from javascript
JSObject callback = (JSObject)args[0];
ctx.call(
callback, // The function
camera,
// The "this" object
new Object[]{"file://"+imagePath}
);
// Parameters
}
});
}
});
We can then capture photos directly from Javascript using a function similar to the following:
camera.capture(function(url){
if ( url == null ){
// No image was captured
return;
}
Class JSObject
2249
Constructor Summary
Constructor and Description
JSObject(JavascriptContext context, String expr)
Method Summary
Modifier and
Type
Object
Object
Object
void
void
void
double
callDouble(String key)
void
int
callInt(String key)
void
JSObject
callObject(String key)
void
String
callString(String key)
void
Object
Object
boolean
boolean
double
double
int
int
JSObject
JSObject
Constructor Summary
2250
String
String
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
String
Constructor Detail
JSObject
public JSObject(JavascriptContext context,
String expr)
Parameters:
context - The javascript context in which this object is being created.
expr - A javascript expression that resolves to an Javascript Object.
Method Detail
Method Summary
2251
Parameters:
key - The name of the property to retrieve on this object.
Returns:
The value of the property specified converted to the appropriate Java value.
See @ref JavascriptContext.get() for a table of the Javascript to Java type
conversions.
getString
public String getString(String key)
Method Detail
2252
This method is useful only for JSObjects that encapsulate Javascript arrays. It
provides a method to get indexed properties of the array. E.g. to retrieve the 5th
element of the wrapped array, you could use this method.
Example
JSObject colors = ctx.get("['red','green','blue']");
String red = (String)colors.get(0);
String green = (String)colors.get(1);
String blue = (String)colors.get(2);
It may be more convenient to use the typed wrapper methods so that you don't have
to typecast the values. E.g.
String red = colors.getString(0);
String green = colors.getString(1);
String blue = colors.getString(2);
Method Detail
2253
Parameters:
index - The index of the entry within the array to return.
Returns:
The value of the specified indexed element.
getString
public String getString(int index)
Method Detail
2254
setInt
public void setInt(String key,
int value,
boolean async)
setInt
public void setInt(String key,
int value)
setDouble
public void setDouble(String key,
double value,
boolean async)
setDouble
public void setDouble(String key,
double value)
setBoolean
public void setBoolean(String key,
boolean value,
boolean async)
setBoolean
public void setBoolean(String key,
boolean value)
set
public void set(int index,
Object js,
boolean async)
set
public void set(int index,
Object js)
setInt
public void setInt(int index,
int value,
boolean async)
setInt
public void setInt(int index,
int value)
setDouble
public void setDouble(int index,
double value,
boolean async)
setDouble
public void setDouble(int index,
double value)
setBoolean
public void setBoolean(int index,
boolean value,
boolean async)
setBoolean
public void setBoolean(int index,
boolean value)
toJSPointer
public String toJSPointer()
Method Detail
2255
callAsync
public void callAsync(String key,
Object[] params,
Callback callback)
call
public Object call(String key)
callAsync
public void callAsync(String key,
Callback callback)
callInt
public int callInt(String key)
callIntAsync
public void callIntAsync(String key,
Callback<Integer> callback)
callDouble
public double callDouble(String key)
callDoubleAsync
public void callDoubleAsync(String key,
Callback<Double> callback)
callString
public String callString(String key)
callStringAsync
public void callStringAsync(String key,
Callback<String> callback)
callObject
public JSObject callObject(String key)
callObjectAsync
public void callObjectAsync(String key,
Callback<JSObject> callback)
call
public Object call(Object[] params)
Calls the object as a function statically. In this case "this" will be window.
E.g.
JSObject alert = (JSObject)ctx.get("window.alert");
alert.call(new Object[]{"An alert message"});
Method Detail
2256
Parameters:
- The parameters to pass to the function. These will be converted to
the appropriate Javascript type.
Returns:
The result of the javascript function call converted to the appropriate Java
type.
callAsync
params
Method Detail
2257
Interface JSFunction
public interface
The JSFunction interface allows you to implement functions in Java that can be called from
Javascript. You can assign any JSFunction object to be a member method of an existing JSObject via
the JSObject.set() method. Then the function can be called from javascript just like any other
Javascript method. JSFunction methods are called asynchronously from Javascript to prevent
deadlocks. If you require a return value to Javascript, you can do that by passing a callback function
which is called by the JSFunction with some parameters.
The following example, adds a camera object to the Javascript environment that has a capture()
method, which can be used to capture images using the device's camera:
// Create a new Javascript object "camera"
final JSObject camera = (JSObject)ctx.get("{}");
// Create a capture() method on the camera object
// as a JSFunction callback.
camera.set("capture", new JSFunction(){
public void apply(JSObject self, final Object[] args) {
Display.getInstance().capturePhoto(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
String imagePath = (String)evt.getSource();
// Get the callback function that was provided
// from javascript
JSObject callback = (JSObject)args[0];
ctx.call(
callback, // The function
camera, // The "this" object
new Object[]{"file://"+imagePath} // Parameters
);
}
});
}
});
We can then capture photos directly from Javascript using a function similar to the following:
camera.capture(function(url){
if ( url == null ){
// No image was captured
return;
}
// Fetch the preview <img> tag.
var image = document.getElementById('preview-image');
// Set the preview URL to the image that was taken.
image.src = url;
});
Interface JSFunction
2258
Method
Summary
Method Detail
apply
void apply(JSObject self,
Object[] args)
Method Summary
2259
Class TarUtils
java.lang.Object
com.codename1.io.tar.TarUtils
public class
extends Object
Constructor Summary
Constructor and Description
TarUtils()
Method Summary
Modifier and Type
static long
Constructor Detail
TarUtils
public TarUtils()
Method Detail
calculateTarSize
public static long calculateTarSize(String path)
throws IOException
Method Detail
2260
Class TarOutputStream
java.lang.Object
java.io.OutputStream
com.codename1.io.BufferedOutputStream
com.codename1.io.tar.TarOutputStream
All Implemented Interfaces:
AutoCloseable
public class
extends BufferedOutputStream
Field Summary
Constructor Summary
Constructor and Description
TarOutputStream(OutputStream out)
Method Summary
Modifier and Type
void
protected void
protected void
closeCurrentEntry()
void
void
Checks if the bytes being written exceed the current entry size.
write(int b)
void
Method Detail
2261
Detail
TarOutputStream
public TarOutputStream(OutputStream out)
Method Detail
close
public void close()
throws IOException
write
public void write(int b)
throws IOException
write
public void write(byte[] b,
int off,
int len)
throws IOException
Checks if the bytes being written exceed the current entry size.
Overrides:
write in class BufferedOutputStream
Parameters:
b - the data.
off - the start offset in the data.
len - the number of bytes to write.
Throws:
IOException - if an I/O error occurs.
See Also:
FilterOutputStream.write(byte[], int, int)
putNextEntry
public void putNextEntry(TarEntry entry)
throws IOException
Constructor Detail
2262
closeCurrentEntry
protected void closeCurrentEntry()
throws IOException
pad
protected void pad()
throws IOException
Method Detail
2263
Class TarInputStream
java.lang.Object
java.io.InputStream
com.codename1.io.BufferedInputStream
com.codename1.io.tar.TarInputStream
All Implemented Interfaces:
AutoCloseable
public class
extends BufferedInputStream
Constructor Summary
Constructor and Description
TarInputStream(InputStream in)
Method Summary
Modifier and
Type
protected void
TarEntry
boolean
void
Not supported
boolean
markSupported()
Tests if this input stream supports the mark and reset methods.
read()
int
Read a byte
read(byte[] b, int off, int len)
Checks if the bytes being read exceed the entry size and adjusts the byte
array length.
int
reset()
void
Not supported
void
setDefaultSkip(boolean defaultSkip)
skip(long n)
long
protected void
skipPad()
Skips the pad at the end of each tar entry file content
Class TarInputStream
2264
Constructor Detail
TarInputStream
public TarInputStream(InputStream in)
Method Detail
markSupported
public boolean markSupported()
Not supported
Overrides:
mark in class BufferedInputStream
Parameters:
readlimit - the maximum limit of bytes that can be read before the mark
position becomes invalid.
reset
public void reset()
throws IOException
Not supported
Overrides:
reset
in class BufferedInputStream
Throws:
- if this stream has not been marked or, if the mark has been
invalidated, or the stream has been closed by invoking its
BufferedInputStream.close() method, or an I/O error occurs.
IOException
read
public int read()
throws IOException
Read a byte
Overrides:
read in class BufferedInputStream
Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException - if this input stream has been closed by invoking its
BufferedInputStream.close() method, or an I/O error occurs.
See Also:
FilterInputStream.read()
2265
Checks if the bytes being read exceed the entry size and adjusts the byte array
length. Updates the byte counters
Overrides:
read in class BufferedInputStream
Parameters:
b - destination buffer.
off - offset at which to start storing bytes.
len - maximum number of bytes to read.
Returns:
the number of bytes read, or -1 if the end of the stream has been reached.
Throws:
IOException - if this input stream has been closed by invoking its
BufferedInputStream.close() method, or an I/O error occurs.
See Also:
FilterInputStream.read(byte[], int, int)
getNextEntry
public TarEntry getNextEntry()
throws IOException
closeCurrentEntry
protected void closeCurrentEntry()
throws IOException
skipPad
protected void skipPad()
throws IOException
Skips the pad at the end of each tar entry file content
Throws:
IOException
skip
public long skip(long n)
throws IOException
Method Detail
2266
Method Detail
2267
Class TarHeader
java.lang.Object
com.codename1.io.tar.TarHeader
public class
extends Object
Header
Offset
0
100
108
116
124
136
148
156
157
Size
100
8
8
8
12
12
8
1
100
Field
File name
File mode
Owner's numeric user ID
Group's numeric user ID
File size in bytes
Last modification time in numeric Unix time format
Checksum for header block
Link indicator (file type)
Name of linked file
File Types
Value
'0'
(ASCII NUL)
'1'
'2'
'3'
'4'
'5'
'6'
'7'
Meaning
Normal file
Normal file (now obsolete)
Hard link
Symbolic link
Character special
Block special
Directory
FIFO
Contigous
Ustar header
Offset
257
263
265
297
329
337
345
Size
6
2
32
32
8
8
155
Field
UStar indicator "ustar"
UStar version "00"
Owner user name
Owner group name
Device major number
Device minor number
Filename prefix
Field Summary
Modifier and Type
int
checkSum
static int
CHKSUMLEN
static int
DEVLEN
int
devMajor
int
devMinor
static int
GIDLEN
static int
GNAMELEN
static String
Class TarHeader
GNU_TMAGIC
2268
groupId
StringBuffer
groupName
static byte
LF_BLK
static byte
LF_CHR
static byte
LF_CONTIG
static byte
LF_DIR
static byte
LF_FIFO
static byte
LF_LINK
static byte
LF_NORMAL
static byte
LF_OLDNORM
static byte
LF_SYMLINK
byte
linkFlag
StringBuffer
linkName
StringBuffer
magic
static int
MAGICLEN
int
mode
static int
MODELEN
long
modTime
static int
MODTIMELEN
StringBuffer
name
static int
NAMELEN
long
size
static int
SIZELEN
static String
TMAGIC
static int
UIDLEN
static int
UNAMELEN
int
userId
StringBuffer
userName
Constructor Summary
Constructor and Description
TarHeader()
Method Summary
Modifier and Type
static int
Field Summary
2269
Field Detail
NAMELEN
public static final int NAMELEN
See Also:
Constant Field Values
MODELEN
public static final int MODELEN
See Also:
Constant Field Values
UIDLEN
public static final int UIDLEN
See Also:
Constant Field Values
GIDLEN
public static final int GIDLEN
See Also:
Constant Field Values
SIZELEN
public static final int SIZELEN
See Also:
Constant Field Values
MODTIMELEN
public static final int MODTIMELEN
See Also:
Constant Field Values
CHKSUMLEN
public static final int CHKSUMLEN
See Also:
Constant Field Values
LF_OLDNORM
public static final byte LF_OLDNORM
See Also:
Constant Field Values
LF_NORMAL
public static final byte LF_NORMAL
See Also:
Constant Field Values
LF_LINK
public static final byte LF_LINK
See Also:
Constant Field Values
Field Detail
2270
See Also:
Constant Field Values
LF_CHR
public static final byte LF_CHR
See Also:
Constant Field Values
LF_BLK
public static final byte LF_BLK
See Also:
Constant Field Values
LF_DIR
public static final byte LF_DIR
See Also:
Constant Field Values
LF_FIFO
public static final byte LF_FIFO
See Also:
Constant Field Values
LF_CONTIG
public static final byte LF_CONTIG
See Also:
Constant Field Values
MAGICLEN
public static final int MAGICLEN
See Also:
Constant Field Values
TMAGIC
public static final String TMAGIC
See Also:
Constant Field Values
GNAMELEN
public static final int GNAMELEN
See Also:
Field Detail
2271
See Also:
Constant Field Values
name
public StringBuffer name
mode
public int mode
userId
public int userId
groupId
public int groupId
size
public long size
modTime
public long modTime
checkSum
public int checkSum
linkFlag
public byte linkFlag
linkName
public StringBuffer linkName
magic
public StringBuffer magic
userName
public StringBuffer userName
groupName
public StringBuffer groupName
devMajor
public int devMajor
devMinor
public int devMinor
Constructor Detail
TarHeader
public TarHeader()
Method Detail
parseName
public static StringBuffer parseName(byte[] header,
int offset,
int length)
Field Detail
2272
name header
offset
length
Returns:
The header's entry name.
getNameBytes
public static int getNameBytes(StringBuffer name,
byte[] buf,
int offset,
int length)
Method Detail
2273
Class TarEntry
java.lang.Object
com.codename1.io.tar.TarEntry
public class
extends Object
Field Summary
Modifier and Type
protected String
file
Constructor Summary
Constructor and Description
TarEntry(byte[] headerBuf)
TarEntry(String file, String entryName)
Method Summary
Modifier and Type
long
boolean
void
computeCheckSum(byte[] buf)
Calculate checksum
equals(TarEntry it)
extractTarHeader(String entryName)
String
getFile()
int
getGroupId()
String
getGroupName()
TarHeader
getHeader()
Date
getModTime()
String
getName()
long
getSize()
int
getUserId()
String
getUserName()
boolean
isDescendent(TarEntry desc)
boolean
void
Class TarEntry
isDirectory()
void
setGroupId(int groupId)
void
setGroupName(String groupName)
void
void
setModTime(Date time)
2274
setModTime(long time)
void
setName(String name)
void
setSize(long size)
void
setUserId(int userId)
void
setUserName(String userName)
writeEntryHeader(byte[] outbuf)
void
Field Detail
file
protected String file
header
protected TarHeader header
Constructor Detail
TarEntry
public TarEntry(String file,
String entryName)
TarEntry
public TarEntry(byte[] headerBuf)
Method Detail
equals
public boolean equals(TarEntry it)
isDescendent
public boolean isDescendent(TarEntry desc)
getHeader
public TarHeader getHeader()
getName
public String getName()
setName
public void setName(String name)
getUserId
public int getUserId()
setUserId
public void setUserId(int userId)
getGroupId
public int getGroupId()
Method Summary
2275
getUserName
public String getUserName()
setUserName
public void setUserName(String userName)
getGroupName
public String getGroupName()
setGroupName
public void setGroupName(String groupName)
setIds
public void setIds(int userId,
int groupId)
setModTime
public void setModTime(long time)
setModTime
public void setModTime(Date time)
getModTime
public Date getModTime()
getFile
public String getFile()
getSize
public long getSize()
setSize
public void setSize(long size)
isDirectory
public boolean isDirectory()
Calculate checksum
Parameters:
buf Returns:
writeEntryHeader
public void writeEntryHeader(byte[] outbuf)
Method Detail
2276
Method Detail
2277
Class TarConstants
java.lang.Object
com.codename1.io.tar.TarConstants
public class
extends Object
Field Summary
Modifier and Type Field and Description
static int
DATA_BLOCK
static int
EOF_BLOCK
static int
HEADER_BLOCK
Constructor Summary
Constructor and Description
TarConstants()
Method Summary
Field Detail
EOF_BLOCK
public static final int EOF_BLOCK
See Also:
Constant Field Values
DATA_BLOCK
public static final int DATA_BLOCK
See Also:
Constant Field Values
HEADER_BLOCK
public static final int HEADER_BLOCK
See Also:
Constant Field Values
Constructor Detail
Class TarConstants
2278
Constructor Detail
2279
Class Octal
java.lang.Object
com.codename1.io.tar.Octal
public class
extends Object
Constructor Summary
Constructor and Description
Octal()
Method Summary
Modifier and
Type
static int
Constructor Detail
Octal
public Octal()
Method Detail
parseOctal
public static long parseOctal(byte[] header,
int offset,
int length)
Parse an octal string from a header buffer. This is used for the file permission mode
value.
Parameters:
header - The header buffer from which to parse.
offset - The offset into the buffer from which to parse.
length - The number of header bytes to parse.
Returns:
Class Octal
2280
Method Detail
2281
Class TwitterRESTService
java.lang.Object
com.codename1.io.ConnectionRequest
com.codename1.io.services.TwitterRESTService
All Implemented Interfaces:
IOProgressListener
public class
extends ConnectionRequest
Calls to the Twitter REST API can be performed via this class although currently support for
authentication isn't implemented due to the transition to oAuth instead of basic authentication.
Field Summary
Modifier and Type Field and Description
static String
METHOD_TWEETS
static String
METHOD_USER_TIMELINE
Constructor Summary
Constructor and Description
TwitterRESTService(String method)
Method Summary
Modifier and Type
String
Hashtable<String,Object>
Hashtable<String,Object>
int
static String
protected void
Class TwitterRESTService
Returns the full Hashtable parse tree read from the server
getStatus(int offset)
2282
setToken(String token)
Field Detail
METHOD_USER_TIMELINE
public static final String METHOD_USER_TIMELINE
See Also:
Constant Field Values
METHOD_TWEETS
public static final String METHOD_TWEETS
See Also:
Constant Field Values
Constructor Detail
TwitterRESTService
public TwitterRESTService(String method)
Method Summary
2283
Method Detail
initToken
public static String initToken(String consumerKey,
String consumerSecret)
Callback for the server response with the input stream from the server. This method
is invoked on the network thread
Overrides:
readResponse in class ConnectionRequest
Parameters:
input - the input stream containing the response
Throws:
IOException - when a read input occurs
getParseTree
public Hashtable<String,Object> getParseTree()
Returns the full Hashtable parse tree read from the server
Returns:
the parse tree
getStatusesCount
public int getStatusesCount()
Constructor Detail
2284
Gets the id string of the first entry which is important if we want to set the id to start
with in the next request
Returns:
the id of the first entry
Method Detail
2285
Class RSSService
java.lang.Object
com.codename1.io.ConnectionRequest
com.codename1.io.services.RSSService
All Implemented Interfaces:
IOProgressListener, ParserCallback
public class
extends ConnectionRequest
implements ParserCallback
Simple RSS read and parse request, to handle errors just subclass this and override parsingError.
Field Summary
Constructor Summary
Constructor and Description
RSSService(String url)
Method Summary
Modifier
and Type
Image
Vector
boolean
Indicates whether more entries might be available since the limt might have
been reached
isCreatePlainTextDetails()
boolean
Class RSSService
2286
readResponse(InputStream input)
Callback for the server response with the input stream from the server.
setCreatePlainTextDetails(boolean createPlainTextDetails)
void
void
setIconPlaceholder(Image iconPlaceholder)
Constructor Detail
RSSService
public RSSService(String url)
Method Summary
2287
Method Detail
readResponse
protected void readResponse(InputStream input)
throws IOException
Callback for the server response with the input stream from the server. This method
is invoked on the network thread
Overrides:
readResponse in class ConnectionRequest
Parameters:
input - the input stream containing the response
Throws:
IOException - when a read input occurs
getResults
public Vector getResults()
Called when encountering an error while parsing the XML document. When
implementing this, the developer should return true if the error should be ignored and
the document needs to be further parsed, or false to stop parsing and issue an error
to the user Note that this method is always called NOT on the EDT thread.
Specified by:
parsingError in interface ParserCallback
Parameters:
errorId - The error ID, one of the ERROR_* constants
tag - The tag in which the error occured (Can be null for non-tag related
errors)
attribute - The attribute in which the error occured (Can be null for
non-attribute related errors)
value - The value in which the error occured (Can be null for non-value
related errors)
description - A verbal description of the error
Returns:
true to continue parsing, false to stop
hasMore
public boolean hasMore()
Constructor Detail
2288
Returns:
the iconPlaceholder
setIconPlaceholder
public void setIconPlaceholder(Image iconPlaceholder)
Parameters:
iconPlaceholder
Method Detail
2289
Class ImageDownloadService
java.lang.Object
com.codename1.io.ConnectionRequest
com.codename1.io.services.ImageDownloadService
All Implemented Interfaces:
IOProgressListener
Deprecated.
this class uses an unconventional storage mechanism and has many issues, we recommend
replacing it with the simpler and more powerful URLImage or Util.dowloadFileTo* calls.
public class
extends ConnectionRequest
Simplifies the process of implementing an image link for labels and lists by binding a request to a
component. On the completion of the request a Codename One encoded image is created and
installs itself into the given component. For the case of a Label this is seamless, in case of a List
renderer the model or the renderer must register itself as a listener and update the data when the
response arrives.
See Also:
URLImage, Util.downloadUrlToFile(java.lang.String, java.lang.String, boolean),
Util.downloadUrlToStorage(java.lang.String, java.lang.String, boolean)
Field Summary
Constructor Summary
Constructor and Description
ImageDownloadService(String url, ActionListener l)
Deprecated.
Accepts the url to bind to the list renderer, on completion the action listener will be invoked
with the image so a list can be updated with the data
ImageDownloadService(String url, Component targetList, int targetOffset,
String targetKey)
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives.
ImageDownloadService(String url, Label parentLabel)
Deprecated.
Accepts the url to bind to the label, on completion the label will be updated and revalidated
with the new image.
ImageDownloadService(String url, List targetList, int targetOffset,
String targetKey)
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives.
Method Summary
Class ImageDownloadService
2290
static void
Deprecated.
Binds an error listener that will fire an instance of NetworkEvent with an error
for a specific fetch operation if applicable
createImageToFileSystem(String url, ActionListener callback,
String destFile)
static void
Deprecated.
Constructs an image request that will automatically populate the given Label
when the response arrives, it will cache the file locally.
createImageToFileSystem(String url, Component targetList,
int targetOffset, String targetKey, String destFile,
Dimension toScale, byte priority)
static void
Deprecated.
Constructs an image request that will automatically populate the given list
when the response arrives, it will cache the file locally as a file in the file
storage.
createImageToFileSystem(String url, Component targetList,
int targetOffset, String targetKey, String destFile,
Image placeholder, byte priority)
static void
Deprecated.
Constructs an image request that will automatically populate the given list
when the response arrives, it will cache the file locally as a file in the file
storage.
createImageToFileSystem(String url, Component targetList,
ListModel model, int targetOffset, String targetKey,
String destFile, Image placeholder, byte priority)
static void
Deprecated.
Constructs an image request that will automatically populate the given list
when the response arrives, it will cache the file locally as a file in the file
storage.
createImageToFileSystem(String url, List targetList,
int targetOffset, String targetKey, String destFile,
Dimension toScale)
static void
static void
Deprecated.
Constructs an image request that will automatically populate the given list
when the response arrives, it will cache the file locally as a file in the file
storage.
createImageToStorage(String url, ActionListener callback,
String cacheId)
Deprecated.
createImageToStorage(String url, ActionListener callback,
String cacheId, boolean keep)
static void
Deprecated.
Constructs an image request that will automatically populate the given Label
when the response arrives, it will cache the file locally.
createImageToStorage(String url, Component targetList,
int targetOffset, String targetKey, String cacheId, Dimension scale,
byte priority)
static void
Deprecated.
Constructs an image request that will automatically populate the given list
when the response arrives, it will cache the file locally as a file in the file
storage.
createImageToStorage(String url, Component targetList,
int targetOffset, String targetKey, String cacheId,
Image placeholderImage, byte priority)
static void
static void
Method Summary
Deprecated.
Constructs an image request that will automatically populate the given list
when the response arrives, it will cache the file locally as a file in the file
storage.
createImageToStorage(String url, Component targetList,
ListModel model, int targetOffset, String targetKey, String cacheId,
Image placeholderImage, byte priority)
2291
Deprecated.
Constructs an image request that will automatically populate the given Label
when the response arrives, it will cache the file locally to the Storage
createImageToStorage(String url, Label l, String cacheId,
Dimension toScale, byte priority)
static void
Deprecated.
Constructs an image request that will automatically populate the given Label
when the response arrives, it will cache the file locally to the Storage
createImageToStorage(String url, Label l, String cacheId,
Image placeholder, byte priority)
static void
Deprecated.
Constructs an image request that will automatically populate the given Label
when the response arrives, it will cache the file locally to the Storage
createImageToStorage(String url, List targetList, int targetOffset,
String targetKey, String cacheId, Dimension scale)
static void
Deprecated.
Constructs an image request that will automatically populate the given list
when the response arrives, it will cache the file locally as a file in the file
storage.
equals(Object o)
boolean
Deprecated.
Indicates whether some other object is "equal to" this one.
getDefaultTimeout()
static int
Deprecated.
Indicates the default timeout to use for image download service, -1 indicates
no default is set.
getResult()
EncodedImage
Deprecated.
Returns the image returned from the server, this method is useful for
renderers
handleErrorResponseCode(int code, String message)
protected
void
Deprecated.
Handles a server response code that is not 200 and not a redirect (unless
redirect handling is disabled)
handleException(Exception err)
protected
void
Deprecated.
Handles an exception thrown when performing a network operation, the
default implementation shows a retry dialog.
isAlwaysRevalidate()
static
boolean
static
boolean
Deprecated.
By default lists don't revalidate on every change to avoid "jumpiness" when
scrolling
isDefaultMaintainAspectRatio()
Deprecated.
isDownloadToStyles()
boolean
static
boolean
Deprecated.
Downloads the image to the style objects associated with this component,
effectively sets the bgImage property on all the styles for the component
instead of invoking setIcon
isFastScale()
Deprecated.
Fast scaling uses runtime draw scaling rather than the Image scaled method.
isMaintainAspectRatio()
boolean
Method Summary
Deprecated.
2292
protected
void
Deprecated.
A callback method that's invoked on the EDT after the readResponse()
method has finished, this is the place where developers should change their
Codename One user interface to avoid race conditions that might be
triggered by modifications within readResponse.
readResponse(InputStream input)
Deprecated.
Callback for the server response with the input stream from the server.
removeErrorListener(ActionListener listener)
static void
Deprecated.
Unbinds an error listener that will fire an instance of NetworkEvent with an
error for a specific fetch operation if applicable
setAlwaysRevalidate(boolean aAlwaysRevalidate)
static void
Deprecated.
By default lists don't revalidate on every change to avoid "jumpiness" when
scrolling
setDefaultMaintainAspectRatio(boolean aDefaultMaintainAspectRatio)
static void
Deprecated.
setDefaultTimeout(int aDefaultTimeout)
static void
Deprecated.
Indicates the default timeout to use for image download service, -1 indicates
no default is set.
setDownloadToStyles(boolean downloadToStyles)
Deprecated.
Downloads the image to the style objects associated with this component,
effectively sets the bgImage property on all the styles for the component
instead of invoking setIcon
void
Deprecated.
This method is invoked when an image finished downloading and should be
set to an offset in the list model.
setFastScale(boolean aFastScale)
static void
Deprecated.
Fast scaling uses runtime draw scaling rather than the Image scaled method.
setMaintainAspectRatio(boolean maintainAspectRatio)
Deprecated.
void
2293
Constructor Detail
ImageDownloadService
public ImageDownloadService(String url,
ActionListener l)
Deprecated.
Accepts the url to bind to the list renderer, on completion the action listener will be
invoked with the image so a list can be updated with the data
Parameters:
url - the image URL
l - an action listener callback
ImageDownloadService
public ImageDownloadService(String url,
Component targetList,
int targetOffset,
String targetKey)
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives. This assumes the GenericListCellRenderer style of list which relies
on a map based model approach.
Parameters:
url - the image URL
targetList - the list that should be updated when the data arrives
targetOffset - the offset within the list to insert the image
targetKey - the key for the map in the target offset
ImageDownloadService
public ImageDownloadService(String url,
List targetList,
int targetOffset,
String targetKey)
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives. This assumes the GenericListCellRenderer style of list which relies
on a Map based model approach.
Parameters:
url - the image URL
targetList - the list that should be updated when the data arrives
targetOffset - the offset within the list to insert the image
targetKey - the key for the map in the target offset
ImageDownloadService
public ImageDownloadService(String url,
Label parentLabel)
Deprecated.
Accepts the url to bind to the label, on completion the label will be updated and
revalidated with the new image.
Parameters:
url - the image URL
parentLabel - the label to update
2294
Method Detail
isFastScale
public static boolean isFastScale()
Deprecated.
Fast scaling uses runtime draw scaling rather than the Image scaled method. This
works better on smartphones but doesn't work well on feature phones
Returns:
the fastScale
setFastScale
public static void setFastScale(boolean aFastScale)
Deprecated.
Fast scaling uses runtime draw scaling rather than the Image scaled method. This
works better on smartphones but doesn't work well on feature phones
Parameters:
aFastScale - the fastScale to set
isAlwaysRevalidate
public static boolean isAlwaysRevalidate()
Deprecated.
By default lists don't revalidate on every change to avoid "jumpiness" when scrolling
Returns:
the alwaysRevalidate
setAlwaysRevalidate
public static void setAlwaysRevalidate(boolean aAlwaysRevalidate)
Deprecated.
By default lists don't revalidate on every change to avoid "jumpiness" when scrolling
Parameters:
aAlwaysRevalidate - the alwaysRevalidate to set
isDefaultMaintainAspectRatio
public static boolean isDefaultMaintainAspectRatio()
Deprecated.
Returns:
the defaultMaintainAspectRatio
setDefaultMaintainAspectRatio
Deprecated.
Parameters:
aDefaultMaintainAspectRatio
getDefaultTimeout
public static int getDefaultTimeout()
Deprecated.
Indicates the default timeout to use for image download service, -1 indicates no
default is set.
Returns:
the defaultTimeout
setDefaultTimeout
public static void setDefaultTimeout(int aDefaultTimeout)
Deprecated.
Indicates the default timeout to use for image download service, -1 indicates no
default is set.
Method Detail
2295
setEntryInListModel
protected void setEntryInListModel(int offset,
Image img)
Deprecated.
This method is invoked when an image finished downloading and should be set to an
offset in the list model. This is useful for special cases with complex list model
hierarchies or proxies.
Parameters:
offset - the offset in the list given when creating the service
img - the image
createImageToFileSystem
public static void createImageToFileSystem(String url,
List targetList,
int targetOffset,
String targetKey,
String destFile,
Dimension toScale)
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives, it will cache the file locally as a file in the file storage. This assumes
the GenericListCellRenderer style of list which relies on a map based model
approach.
Parameters:
url - the image URL
targetList - the list that should be updated when the data arrives
targetOffset - the offset within the list to insert the image
targetKey - the key for the map in the target offset
destFile - local file to store the data into the given path
createImageToFileSystem
public static void createImageToFileSystem(String url,
Component targetList,
int targetOffset,
String targetKey,
String destFile,
Dimension toScale,
byte priority)
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives, it will cache the file locally as a file in the file storage. This assumes
the GenericListCellRenderer style of list which relies on a map based model
approach.
Parameters:
url - the image URL
targetList - the list that should be updated when the data arrives
targetOffset - the offset within the list to insert the image
targetKey - the key for the map in the target offset
destFile - local file to store the data into the given path
createImageToFileSystem
public static void createImageToFileSystem(String url,
Component targetList,
int targetOffset,
String targetKey,
String destFile,
Image placeholder,
byte priority)
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives, it will cache the file locally as a file in the file storage. This assumes
the GenericListCellRenderer style of list which relies on a map based model
Method Detail
2296
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives, it will cache the file locally as a file in the file storage. This assumes
the GenericListCellRenderer style of list which relies on a map based model
approach.
Parameters:
url - the image URL
targetList - the list that should be updated when the data arrives
model - the list model
targetOffset - the offset within the list to insert the image
targetKey - the key for the map in the target offset
destFile - local file to store the data into the given path
handleException
protected void handleException(Exception err)
Deprecated.
Handles an exception thrown when performing a network operation, the default
implementation shows a retry dialog.
Overrides:
handleException in class ConnectionRequest
Parameters:
err - the exception thrown
handleErrorResponseCode
protected void handleErrorResponseCode(int code,
String message)
Deprecated.
Handles a server response code that is not 200 and not a redirect (unless redirect
handling is disabled)
Overrides:
handleErrorResponseCode in class ConnectionRequest
Parameters:
code - the response code from the server
message - the response message from the server
addErrorListener
public static void addErrorListener(ActionListener listener)
Deprecated.
Binds an error listener that will fire an instance of NetworkEvent with an error for a
specific fetch operation if applicable
Parameters:
listener - the listener
removeErrorListener
public static void removeErrorListener(ActionListener listener)
Deprecated.
Method Detail
2297
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives, it will cache the file locally as a file in the file storage. This assumes
the GenericListCellRenderer style of list which relies on a map based model
approach.
Parameters:
url - the image URL
targetList - the list that should be updated when the data arrives
targetOffset - the offset within the list to insert the image
targetKey - the key for the map in the target offset
cacheId - a unique identifier to be used to store the image into storage
scale - the scale of the image to put in the List or null
createImageToStorage
public static void createImageToStorage(String url,
Component targetList,
int targetOffset,
String targetKey,
String cacheId,
Dimension scale,
byte priority)
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives, it will cache the file locally as a file in the file storage. This assumes
the GenericListCellRenderer style of list which relies on a map based model
approach.
Parameters:
url - the image URL
targetList - the list that should be updated when the data arrives
targetOffset - the offset within the list to insert the image
targetKey - the key for the map in the target offset
cacheId - a unique identifier to be used to store the image into storage
scale - the scale of the image to put in the List or null
createImageToStorage
public static void createImageToStorage(String url,
Component targetList,
int targetOffset,
String targetKey,
String cacheId,
Image placeholderImage,
byte priority)
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives, it will cache the file locally as a file in the file storage. This assumes
the GenericListCellRenderer style of list which relies on a map based model
approach.
Parameters:
url - the image URL
targetList - the list that should be updated when the data arrives
targetOffset - the offset within the list to insert the image
targetKey - the key for the map in the target offset
cacheId - a unique identifier to be used to store the image into storage
placeholderImage - the image placeholder
Method Detail
2298
Deprecated.
Constructs an image request that will automatically populate the given list when the
response arrives, it will cache the file locally as a file in the file storage. This assumes
the GenericListCellRenderer style of list which relies on a map based model
approach.
Parameters:
url - the image URL
targetList - the list that should be updated when the data arrives
model - the model destination
targetOffset - the offset within the list to insert the image
targetKey - the key for the map in the target offset
cacheId - a unique identifier to be used to store the image into storage
placeholderImage - the image placeholder
createImageToStorage
public static void createImageToStorage(String url,
Label l,
String cacheId,
Dimension toScale)
Deprecated.
Constructs an image request that will automatically populate the given Label when
the response arrives, it will cache the file locally to the Storage
Parameters:
url - the image URL
l - the Label that should be updated when the data arrives to just use storage
and the url as the key
cacheId - a unique identifier to be used to store the image into storage
toScale - the scale dimension or null
createImageToStorage
public static void createImageToStorage(String url,
Label l,
String cacheId,
Dimension toScale,
byte priority)
Deprecated.
Constructs an image request that will automatically populate the given Label when
the response arrives, it will cache the file locally to the Storage
Parameters:
url - the image URL
l - the Label that should be updated when the data arrives to just use storage
and the url as the key
cacheId - a unique identifier to be used to store the image into storage
toScale - the scale dimension or null
priority - the priority for the task
createImageToStorage
public static void createImageToStorage(String url,
Label l,
String cacheId,
Image placeholder,
byte priority)
Deprecated.
Constructs an image request that will automatically populate the given Label when
the response arrives, it will cache the file locally to the Storage
Method Detail
2299
Deprecated.
Constructs an image request that will automatically populate the given Label when
the response arrives, it will cache the file locally.
Parameters:
url - the image URL
callback - the callback that should be updated when the data arrives
destFile - local file to store the data into the given path
createImageToStorage
public static void createImageToStorage(String url,
ActionListener callback,
String cacheId)
Deprecated.
createImageToStorage
public static void createImageToStorage(String url,
ActionListener callback,
String cacheId,
boolean keep)
Deprecated.
Constructs an image request that will automatically populate the given Label when
the response arrives, it will cache the file locally.
Parameters:
url - the image URL
callback - the callback that should be updated when the data arrives
cacheId - a unique identifier to be used to store the image into storage
keep - if set to true keeps the file in RAM once loaded
postResponse
protected void postResponse()
Deprecated.
A callback method that's invoked on the EDT after the readResponse() method has
finished, this is the place where developers should change their Codename One user
interface to avoid race conditions that might be triggered by modifications within
readResponse. Notice this method is only invoked on a successful response and will
not be invoked in case of a failure.
Overrides:
postResponse in class ConnectionRequest
readResponse
protected void readResponse(InputStream input)
throws IOException
Deprecated.
Callback for the server response with the input stream from the server. This method
is invoked on the network thread
Overrides:
readResponse in class ConnectionRequest
Parameters:
input - the input stream containing the response
Throws:
IOException - when a read input occurs
Method Detail
2300
getResult
public EncodedImage getResult()
Deprecated.
Returns the image returned from the server, this method is useful for renderers
Returns:
the result
isDownloadToStyles
public boolean isDownloadToStyles()
Deprecated.
Downloads the image to the style objects associated with this component, effectively
sets the bgImage property on all the styles for the component instead of invoking
setIcon
Returns:
the downloadToStyles
setDownloadToStyles
public void setDownloadToStyles(boolean downloadToStyles)
Deprecated.
Downloads the image to the style objects associated with this component, effectively
sets the bgImage property on all the styles for the component instead of invoking
setIcon
Parameters:
downloadToStyles - the downloadToStyles to set
equals
public boolean equals(Object o)
Deprecated.
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class ConnectionRequest
isMaintainAspectRatio
public boolean isMaintainAspectRatio()
Deprecated.
Returns:
the maintainAspectRatio
setMaintainAspectRatio
public void setMaintainAspectRatio(boolean maintainAspectRatio)
Deprecated.
Parameters:
maintainAspectRatio
Method Detail
2301
Class CachedDataService
java.lang.Object
com.codename1.io.ConnectionRequest
com.codename1.io.services.CachedDataService
All Implemented Interfaces:
IOProgressListener
public class
extends ConnectionRequest
Simple service that allows downloading and caching data locally. When the data is requested again
the server is queried with a conditional get query.
Field Summary
Method Summary
Modifier and
Type
protected
void
protected
void
protected
void
protected
void
Handles a server response code that is not 200 and not a redirect (unless
redirect handling is disabled)
handleException(Exception err)
Allows reading the headers from the connection by calling the getHeader()
method.
readResponse(InputStream input)
Callback for the server response with the input stream from the server.
register()
static void
static void
Checks that the cached data is up to date and if a newer version exits it
updates the data in place
Class CachedDataService
2302
Method Detail
register
public static void register()
Makes sure the cached data class is properly registered as an externalizable. This
must be invoked for caching to work
updateData
public static void updateData(CachedData d,
ActionListener callback)
Checks that the cached data is up to date and if a newer version exits it updates the
data in place
Parameters:
d - the data to check
callback - optional callback to be invoked on request completion
handleException
protected void handleException(Exception err)
Handles a server response code that is not 200 and not a redirect (unless redirect
handling is disabled)
Overrides:
handleErrorResponseCode in class ConnectionRequest
Parameters:
code - the response code from the server
message - the response message from the server
readHeaders
protected void readHeaders(Object connection)
throws IOException
2303
Callback for the server response with the input stream from the server. This method
is invoked on the network thread
Overrides:
readResponse in class ConnectionRequest
Parameters:
input - the input stream containing the response
Throws:
IOException - when a read input occurs
Method Detail
2304
Class CachedData
java.lang.Object
com.codename1.io.services.CachedData
All Implemented Interfaces:
Externalizable
public class
extends Object
implements Externalizable
Cached data class for use with the cached data service
Constructor Summary
Constructor and Description
CachedData()
Method Summary
Modifier
and Type
void
byte[]
getData()
getObjectId()
String
The object id must be unique, it is used to identify the object when loaded even
when it is obfuscated.
String
getUrl()
getVersion()
Returns the version for the current persistance code, the version will be pased
to internalized thus allowing the internalize method to recognize classes
persisted in older revisions
int
void
Loads the object from the input stream and allows deserialization
void
setData(byte[] data)
void
setUrl(String url)
Constructor Detail
CachedData
public CachedData()
Class CachedData
2305
Method Detail
getVersion
public int getVersion()
Returns the version for the current persistance code, the version will be pased to
internalized thus allowing the internalize method to recognize classes persisted in
older revisions
Specified by:
getVersion in interface Externalizable
Returns:
version number for the persistant code
externalize
public void externalize(DataOutputStream out)
throws IOException
Allows us to store an object state, this method must be implemented in order to save
the state of an object
Specified by:
externalize in interface Externalizable
Parameters:
out - the stream into which the object must be serialized
Throws:
IOException - the method may throw an exception
internalize
public void internalize(int version,
DataInputStream in)
throws IOException
Loads the object from the input stream and allows deserialization
Specified by:
internalize in interface Externalizable
Parameters:
version - the version the class returned during the externalization processs
in - the input stream used to load the class
Throws:
IOException - the method may throw an exception
getObjectId
public String getObjectId()
Returns:
the data
setData
public void setData(byte[] data)
Parameters:
data
Method Detail
2306
getUrl
public String getUrl()
Returns:
the url
setUrl
public void setUrl(String url)
Parameters:
url - the url to set
Method Detail
2307
Class ZStream
java.lang.Object
com.codename1.io.gzip.ZStream
Direct Known Subclasses:
Deflater, Inflater
Deprecated.
Not for public use in the future.
@Deprecated
public class
extends Object
ZStream
Field Summary
Modifier and Type Field and Description
avail_in
Deprecated.
int
avail_out
Deprecated.
int
msg
Deprecated.
String
next_in
Deprecated.
byte[]
next_in_index
Deprecated.
int
next_out
Deprecated.
byte[]
next_out_index
Deprecated.
int
total_in
Deprecated.
long
total_out
Deprecated.
long
Constructor Summary
Constructor and Description
ZStream()
Deprecated.
ZStream(com.codename1.io.gzip.Checksum adler)
Deprecated.
Class ZStream
2308
Method Summary
Modifier
and Type
int
Deprecated.
deflateEnd()
int
Deprecated.
deflateInit(int level)
int
Deprecated.
deflateInit(int level, boolean nowrap)
int
Deprecated.
deflateInit(int level, int bits)
int
Deprecated.
deflateInit(int level, int bits, boolean nowrap)
int
Deprecated.
deflateInit(int level, int bits, int memlevel)
int
int
Deprecated.
deflateInit(int level, int bits, int memlevel,
com.codename1.io.gzip.JZlib.WrapperType wrapperType)
Deprecated.
deflateParams(int level, int strategy)
int
Deprecated.
deflateSetDictionary(byte[] dictionary, int dictLength)
int
Deprecated.
end()
int
Deprecated.
Those methods are expected to be override by Inflater and Deflater.
finished()
boolean
Deprecated.
free()
void
Deprecated.
getAdler()
long
Deprecated.
getAvailIn()
int
Deprecated.
getAvailOut()
int
Deprecated.
getMessage()
String
Deprecated.
byte[]
getNextIn()
Constructor Summary
2309
Deprecated.
getNextOut()
byte[]
Deprecated.
getNextOutIndex()
int
Deprecated.
getTotalIn()
long
Deprecated.
getTotalOut()
long
Deprecated.
inflate(int f)
int
Deprecated.
inflateEnd()
int
Deprecated.
inflateFinished()
boolean
Deprecated.
inflateInit()
int
Deprecated.
inflateInit(boolean nowrap)
int
Deprecated.
inflateInit(int w)
int
Deprecated.
inflateInit(int w, boolean nowrap)
int
Deprecated.
inflateInit(int w, com.codename1.io.gzip.JZlib.WrapperType wrapperType)
int
Deprecated.
inflateInit(com.codename1.io.gzip.JZlib.WrapperType wrapperType)
int
Deprecated.
inflateSetDictionary(byte[] dictionary, int dictLength)
int
Deprecated.
inflateSync()
int
Deprecated.
inflateSyncPoint()
int
Deprecated.
setAvailIn(int avail_in)
void
Deprecated.
setAvailOut(int avail_out)
void
Deprecated.
void
setInput(byte[] buf)
Method Summary
2310
Deprecated.
void
Deprecated.
void
setNextIn(byte[] next_in)
Deprecated.
void
setNextInIndex(int next_in_index)
Deprecated.
void
setNextOut(byte[] next_out)
Deprecated.
void
setNextOutIndex(int next_out_index)
Deprecated.
void
setOutput(byte[] buf)
Deprecated.
void
Deprecated.
void
Field Detail
next_in
public byte[] next_in
Deprecated.
next_in_index
public int next_in_index
Deprecated.
avail_in
public int avail_in
Deprecated.
total_in
public long total_in
Deprecated.
next_out
public byte[] next_out
Deprecated.
2311
Deprecated.
avail_out
public int avail_out
Deprecated.
total_out
public long total_out
Deprecated.
msg
public String msg
Deprecated.
Constructor Detail
ZStream
public ZStream()
Deprecated.
ZStream
public ZStream(com.codename1.io.gzip.Checksum adler)
Deprecated.
Method Detail
inflateInit
public int inflateInit()
Deprecated.
inflateInit
public int inflateInit(boolean nowrap)
Deprecated.
inflateInit
public int inflateInit(int w)
Deprecated.
inflateInit
public int inflateInit(com.codename1.io.gzip.JZlib.WrapperType wrapperType)
Deprecated.
inflateInit
public int inflateInit(int w,
com.codename1.io.gzip.JZlib.WrapperType wrapperType)
Deprecated.
Field Detail
2312
Deprecated.
inflate
public int inflate(int f)
Deprecated.
inflateEnd
public int inflateEnd()
Deprecated.
inflateSync
public int inflateSync()
Deprecated.
inflateSyncPoint
public int inflateSyncPoint()
Deprecated.
inflateSetDictionary
public int inflateSetDictionary(byte[] dictionary,
int dictLength)
Deprecated.
inflateFinished
public boolean inflateFinished()
Deprecated.
deflateInit
public int deflateInit(int level)
Deprecated.
deflateInit
public int deflateInit(int level,
boolean nowrap)
Deprecated.
deflateInit
public int deflateInit(int level,
int bits)
Deprecated.
deflateInit
public int deflateInit(int level,
int bits,
int memlevel,
com.codename1.io.gzip.JZlib.WrapperType wrapperType)
Deprecated.
deflateInit
public int deflateInit(int level,
int bits,
int memlevel)
Deprecated.
Method Detail
2313
Deprecated.
deflate
public int deflate(int flush)
Deprecated.
deflateEnd
public int deflateEnd()
Deprecated.
deflateParams
public int deflateParams(int level,
int strategy)
Deprecated.
deflateSetDictionary
public int deflateSetDictionary(byte[] dictionary,
int dictLength)
Deprecated.
getAdler
public long getAdler()
Deprecated.
free
public void free()
Deprecated.
setOutput
public void setOutput(byte[] buf)
Deprecated.
setOutput
public void setOutput(byte[] buf,
int off,
int len)
Deprecated.
setInput
public void setInput(byte[] buf)
Deprecated.
setInput
public void setInput(byte[] buf,
boolean append)
Deprecated.
setInput
public void setInput(byte[] buf,
int off,
int len,
boolean append)
Method Detail
2314
Deprecated.
setNextIn
public void setNextIn(byte[] next_in)
Deprecated.
getNextInIndex
public int getNextInIndex()
Deprecated.
setNextInIndex
public void setNextInIndex(int next_in_index)
Deprecated.
getAvailIn
public int getAvailIn()
Deprecated.
setAvailIn
public void setAvailIn(int avail_in)
Deprecated.
getNextOut
public byte[] getNextOut()
Deprecated.
setNextOut
public void setNextOut(byte[] next_out)
Deprecated.
getNextOutIndex
public int getNextOutIndex()
Deprecated.
setNextOutIndex
public void setNextOutIndex(int next_out_index)
Deprecated.
getAvailOut
public int getAvailOut()
Deprecated.
setAvailOut
public void setAvailOut(int avail_out)
Deprecated.
getTotalOut
public long getTotalOut()
Deprecated.
Method Detail
2315
Deprecated.
getMessage
public String getMessage()
Deprecated.
end
public int end()
Deprecated.
Those methods are expected to be override by Inflater and Deflater. In the future,
they will become abstract methods.
finished
public boolean finished()
Deprecated.
Method Detail
2316
Class JZlib
java.lang.Object
com.codename1.io.gzip.JZlib
Field Summary
Modifier and Type
static int
DEF_WBITS
static int
MAX_WBITS
Z_ASCII
static int
Z_BEST_COMPRESSION
static int
Z_BEST_SPEED
static byte
Z_BINARY
static int
Z_BUF_ERROR
static int
Z_DATA_ERROR
static int
Z_DEFAULT_COMPRESSION
static int
Z_DEFAULT_STRATEGY
static int
Z_ERRNO
static int
Z_FILTERED
static int
Z_FINISH
static int
Z_FULL_FLUSH
static int
Z_HUFFMAN_ONLY
static int
Z_MEM_ERROR
static int
Z_NEED_DICT
static int
Z_NO_COMPRESSION
static int
Z_NO_FLUSH
static int
Z_OK
static int
Z_PARTIAL_FLUSH
static int
Z_STREAM_END
static int
Z_STREAM_ERROR
static int
Z_SYNC_FLUSH
static byte
Z_UNKNOWN
static int
Z_VERSION_ERROR
Constructor Summary
Class JZlib
2317
Method Summary
Modifier and Type
static long
static long
static String
version()
Field Detail
MAX_WBITS
public static final int MAX_WBITS
See Also:
Constant Field Values
DEF_WBITS
public static final int DEF_WBITS
See Also:
Constant Field Values
W_NONE
public static final com.codename1.io.gzip.JZlib.WrapperType W_NONE
W_ZLIB
public static final com.codename1.io.gzip.JZlib.WrapperType W_ZLIB
W_GZIP
public static final com.codename1.io.gzip.JZlib.WrapperType W_GZIP
W_ANY
public static final com.codename1.io.gzip.JZlib.WrapperType W_ANY
Z_NO_COMPRESSION
public static final int Z_NO_COMPRESSION
See Also:
Constant Field Values
Z_BEST_SPEED
public static final int Z_BEST_SPEED
See Also:
Constant Field Values
Z_BEST_COMPRESSION
public static final int Z_BEST_COMPRESSION
See Also:
Constant Field Values
Constructor Summary
2318
See Also:
Constant Field Values
Z_FILTERED
public static final int Z_FILTERED
See Also:
Constant Field Values
Z_HUFFMAN_ONLY
public static final int Z_HUFFMAN_ONLY
See Also:
Constant Field Values
Z_DEFAULT_STRATEGY
public static final int Z_DEFAULT_STRATEGY
See Also:
Constant Field Values
Z_NO_FLUSH
public static final int Z_NO_FLUSH
See Also:
Constant Field Values
Z_PARTIAL_FLUSH
public static final int Z_PARTIAL_FLUSH
See Also:
Constant Field Values
Z_SYNC_FLUSH
public static final int Z_SYNC_FLUSH
See Also:
Constant Field Values
Z_FULL_FLUSH
public static final int Z_FULL_FLUSH
See Also:
Constant Field Values
Z_FINISH
public static final int Z_FINISH
See Also:
Constant Field Values
Z_OK
public static final int Z_OK
See Also:
Constant Field Values
Z_STREAM_END
public static final int Z_STREAM_END
See Also:
Constant Field Values
Field Detail
2319
See Also:
Constant Field Values
Z_ERRNO
public static final int Z_ERRNO
See Also:
Constant Field Values
Z_STREAM_ERROR
public static final int Z_STREAM_ERROR
See Also:
Constant Field Values
Z_DATA_ERROR
public static final int Z_DATA_ERROR
See Also:
Constant Field Values
Z_MEM_ERROR
public static final int Z_MEM_ERROR
See Also:
Constant Field Values
Z_BUF_ERROR
public static final int Z_BUF_ERROR
See Also:
Constant Field Values
Z_VERSION_ERROR
public static final int Z_VERSION_ERROR
See Also:
Constant Field Values
Z_BINARY
public static final byte Z_BINARY
See Also:
Constant Field Values
Z_ASCII
public static final byte Z_ASCII
See Also:
Constant Field Values
Z_UNKNOWN
public static final byte Z_UNKNOWN
See Also:
Constant Field Values
Constructor Detail
Field Detail
2320
Method Detail
version
public static String version()
adler32_combine
public static long adler32_combine(long adler1,
long adler2,
long len2)
crc32_combine
public static long crc32_combine(long crc1,
long crc2,
long len2)
Constructor Detail
2321
Class InflaterInputStream
java.lang.Object
java.io.InputStream
com.codename1.io.gzip.FilterInputStream
com.codename1.io.gzip.InflaterInputStream
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
GZIPInputStream
public class
extends FilterInputStream
Field Summary
Modifier and Type
protected byte[]
inflater
protected boolean
myinflater
Constructor Summary
Constructor and Description
InflaterInputStream(InputStream in)
InflaterInputStream(InputStream in, boolean nowrap)
InflaterInputStream(InputStream in, Inflater inflater)
InflaterInputStream(InputStream in, Inflater inflater, int size)
InflaterInputStream(InputStream in, Inflater inflater, int size,
boolean close_in)
Method Summary
Modifier and
Type
int
Returns the number of bytes that can be read (or skipped over) from this
input stream without blocking by the next caller of a method for this input
stream.
close()
void
protected
void
Method Detail
Closes this input stream and releases any system resources associated with
the stream.
fill()
2322
getAvailIn()
Inflater
getInflater()
long
getTotalIn()
long
getTotalOut()
mark(int readlimit)
void
boolean
markSupported()
Tests if this input stream supports the mark and reset methods.
read()
int
int
Reads up to len bytes of data from the input stream into an array of bytes.
void
readHeader()
reset()
Repositions this stream to the position at the time the mark method was last
called on this input stream.
void
skip(long n)
long
Skips over and discards n bytes of data from this input stream.
Field Detail
inflater
protected final Inflater inflater
buf
protected byte[] buf
DEFAULT_BUFSIZE
protected static final int DEFAULT_BUFSIZE
See Also:
Constant Field Values
myinflater
protected boolean myinflater
Constructor Detail
InflaterInputStream
public InflaterInputStream(InputStream in)
throws IOException
Throws:
IOException
Method Summary
2323
Throws:
IOException
InflaterInputStream
public InflaterInputStream(InputStream in,
Inflater inflater)
throws IOException
Throws:
IOException
InflaterInputStream
public InflaterInputStream(InputStream in,
Inflater inflater,
int size)
throws IOException
Throws:
IOException
InflaterInputStream
public InflaterInputStream(InputStream in,
Inflater inflater,
int size,
boolean close_in)
throws IOException
Throws:
IOException
Method Detail
read
public int read()
throws IOException
read
public int read(byte[] b,
int off,
int len)
throws IOException
Constructor Detail
2324
available
public int available()
throws IOException
skip
public long skip(long n)
throws IOException
close
public void close()
throws IOException
Method Detail
2325
Throws:
IOException
markSupported
public boolean markSupported()
getTotalIn
public long getTotalIn()
getTotalOut
public long getTotalOut()
Method Detail
2326
readHeader
public void readHeader()
throws IOException
Throws:
IOException
getInflater
public Inflater getInflater()
Method Detail
2327
Class Inflater
java.lang.Object
com.codename1.io.gzip.ZStream
com.codename1.io.gzip.Inflater
Field Summary
Constructor Summary
Constructor and Description
Inflater()
Inflater(boolean nowrap)
Inflater(int w)
Inflater(int w, boolean nowrap)
Inflater(int w, com.codename1.io.gzip.JZlib.WrapperType wrapperType)
Inflater(com.codename1.io.gzip.JZlib.WrapperType wrapperType)
Method Summary
Modifier and
Type
int
Class Inflater
boolean
finished()
int
inflate(int f)
int
init()
int
init(boolean nowrap)
int
init(int w)
int
int
init(int w,
com.codename1.io.gzip.JZlib.WrapperType wrapperType)
int
init(com.codename1.io.gzip.JZlib.WrapperType wrapperType)
int
int
sync()
int
syncPoint()
2328
Constructor Detail
Inflater
public Inflater()
Inflater
public Inflater(com.codename1.io.gzip.JZlib.WrapperType wrapperType)
throws GZIPException
Throws:
GZIPException
Inflater
public Inflater(int w,
com.codename1.io.gzip.JZlib.WrapperType wrapperType)
throws GZIPException
Throws:
GZIPException
Inflater
public Inflater(int w)
throws GZIPException
Throws:
GZIPException
Inflater
public Inflater(boolean nowrap)
throws GZIPException
Throws:
GZIPException
Inflater
public Inflater(int w,
boolean nowrap)
throws GZIPException
Throws:
GZIPException
Method Detail
init
public int init()
2329
init
public int init(int w,
com.codename1.io.gzip.JZlib.WrapperType wrapperType)
init
public int init(boolean nowrap)
init
public int init(int w)
init
public int init(int w,
boolean nowrap)
inflate
public int inflate(int f)
Overrides:
inflate
in class ZStream
end
public int end()
syncPoint
public int syncPoint()
setDictionary
public int setDictionary(byte[] dictionary,
int dictLength)
finished
public boolean finished()
Overrides:
finished
Method Detail
in class ZStream
2330
Class GZIPOutputStream
java.lang.Object
java.io.OutputStream
com.codename1.io.gzip.FilterOutputStream
com.codename1.io.gzip.DeflaterOutputStream
com.codename1.io.gzip.GZIPOutputStream
All Implemented Interfaces:
AutoCloseable
public class
extends DeflaterOutputStream
Field Summary
Constructor Summary
Constructor and Description
GZIPOutputStream(OutputStream out)
GZIPOutputStream(OutputStream out, Deflater deflater, int size,
boolean close_out)
GZIPOutputStream(OutputStream out, int size)
GZIPOutputStream(OutputStream out, int size, boolean close_out)
Method Summary
Modifier and Type
long
getCRC()
void
setComment(String comment)
void
setModifiedTime(long mtime)
void
setName(String name)
void
setOS(int os)
Class GZIPOutputStream
2331
inherited from
class com.codename1.io.gzip.FilterOutputStream
write
Constructor Detail
GZIPOutputStream
public GZIPOutputStream(OutputStream out)
throws IOException
Throws:
IOException
GZIPOutputStream
public GZIPOutputStream(OutputStream out,
int size)
throws IOException
Throws:
IOException
GZIPOutputStream
public GZIPOutputStream(OutputStream out,
int size,
boolean close_out)
throws IOException
Throws:
IOException
GZIPOutputStream
public GZIPOutputStream(OutputStream out,
Deflater deflater,
int size,
boolean close_out)
throws IOException
Throws:
IOException
Method Detail
setModifiedTime
public void setModifiedTime(long mtime)
throws GZIPException
Throws:
GZIPException
setOS
public void setOS(int os)
throws GZIPException
Throws:
GZIPException
2332
Throws:
GZIPException
setComment
public void setComment(String comment)
throws GZIPException
Throws:
GZIPException
getCRC
public long getCRC()
throws GZIPException
Throws:
GZIPException
Method Detail
2333
Class GZIPInputStream
java.lang.Object
java.io.InputStream
com.codename1.io.gzip.FilterInputStream
com.codename1.io.gzip.InflaterInputStream
com.codename1.io.gzip.GZIPInputStream
All Implemented Interfaces:
AutoCloseable
public class
extends InflaterInputStream
Field Summary
Constructor Summary
Constructor and Description
GZIPInputStream(InputStream in)
GZIPInputStream(InputStream in, Inflater inflater, int size, boolean close_in)
GZIPInputStream(InputStream in, int size, boolean close_in)
Method Summary
Modifier and Type Method and Description
String
getComment()
long
getCRC()
long
getModifiedtime()
String
getName()
int
getOS()
void
readHeader()
Class GZIPInputStream
2334
inherited from
class com.codename1.io.gzip.FilterInputStream
read
Constructor Detail
GZIPInputStream
public GZIPInputStream(InputStream in)
throws IOException
Throws:
IOException
GZIPInputStream
public GZIPInputStream(InputStream in,
int size,
boolean close_in)
throws IOException
Throws:
IOException
GZIPInputStream
public GZIPInputStream(InputStream in,
Inflater inflater,
int size,
boolean close_in)
throws IOException
Throws:
IOException
Method Detail
getModifiedtime
public long getModifiedtime()
getOS
public int getOS()
getName
public String getName()
getComment
public String getComment()
getCRC
public long getCRC()
throws GZIPException
Throws:
GZIPException
readHeader
public void readHeader()
throws IOException
Overrides:
readHeader
in class InflaterInputStream
2335
Method Detail
2336
Class GZIPHeader
java.lang.Object
com.codename1.io.gzip.GZIPHeader
public class
extends Object
See Also:
"http://www.ietf.org/rfc/rfc1952.txt"
Field Summary
Modifier and Type Field and Description
static byte
OS_AMIGA
static byte
OS_ATARI
static byte
OS_CPM
static byte
OS_MACOS
static byte
OS_MSDOS
static byte
OS_OS2
static byte
OS_QDOS
static byte
OS_RISCOS
static byte
OS_TOPS20
static byte
OS_UNIX
static byte
OS_UNKNOWN
static byte
OS_VMCMS
static byte
OS_VMS
static byte
OS_WIN32
static byte
OS_ZSYSTEM
Constructor Summary
Constructor and Description
GZIPHeader()
Method Summary
Modifier and Type
Object
clone()
String
getComment()
long
getCRC()
long
getModifiedTime()
String
getName()
int
getOS()
void
setComment(String comment)
Class GZIPHeader
2337
setCRC(long crc)
void
setModifiedTime(long mtime)
void
setName(String name)
void
setOS(int os)
Field Detail
OS_MSDOS
public static final byte OS_MSDOS
See Also:
Constant Field Values
OS_AMIGA
public static final byte OS_AMIGA
See Also:
Constant Field Values
OS_VMS
public static final byte OS_VMS
See Also:
Constant Field Values
OS_UNIX
public static final byte OS_UNIX
See Also:
Constant Field Values
OS_ATARI
public static final byte OS_ATARI
See Also:
Constant Field Values
OS_OS2
public static final byte OS_OS2
See Also:
Constant Field Values
OS_MACOS
public static final byte OS_MACOS
See Also:
Constant Field Values
OS_TOPS20
public static final byte OS_TOPS20
See Also:
Constant Field Values
Method Summary
2338
See Also:
Constant Field Values
OS_VMCMS
public static final byte OS_VMCMS
See Also:
Constant Field Values
OS_ZSYSTEM
public static final byte OS_ZSYSTEM
See Also:
Constant Field Values
OS_CPM
public static final byte OS_CPM
See Also:
Constant Field Values
OS_QDOS
public static final byte OS_QDOS
See Also:
Constant Field Values
OS_RISCOS
public static final byte OS_RISCOS
See Also:
Constant Field Values
OS_UNKNOWN
public static final byte OS_UNKNOWN
See Also:
Constant Field Values
Constructor Detail
GZIPHeader
public GZIPHeader()
Method Detail
setModifiedTime
public void setModifiedTime(long mtime)
getModifiedTime
public long getModifiedTime()
setOS
public void setOS(int os)
getOS
public int getOS()
Field Detail
2339
getName
public String getName()
setComment
public void setComment(String comment)
getComment
public String getComment()
setCRC
public void setCRC(long crc)
getCRC
public long getCRC()
clone
public Object clone()
Method Detail
2340
Class GZIPException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
com.codename1.io.gzip.GZIPException
public class
extends IOException
Constructor Summary
Constructor and Description
GZIPException()
GZIPException(String s)
Method Summary
Constructor Detail
GZIPException
public GZIPException()
GZIPException
public GZIPException(String s)
Class GZIPException
2341
Class GZConnectionRequest
java.lang.Object
com.codename1.io.ConnectionRequest
com.codename1.io.gzip.GZConnectionRequest
All Implemented Interfaces:
IOProgressListener
public class
extends ConnectionRequest
Field Summary
Constructor Summary
Constructor and Description
GZConnectionRequest()
Method Summary
Modifier and
Type
protected void
Allows reading the headers from the connection by calling the getHeader()
method.
readResponse(InputStream input)
protected void
protected void
Constructor Detail
2342
Constructor Detail
GZConnectionRequest
public GZConnectionRequest()
Method Detail
readHeaders
protected void readHeaders(Object connection)
throws IOException
Allows reading the headers from the connection by calling the getHeader() method.
Overrides:
readHeaders in class ConnectionRequest
Parameters:
connection - used when invoking getHeader
Throws:
IOException - thrown on failure
readResponse
protected final void readResponse(InputStream input)
throws IOException
2343
Class FilterOutputStream
java.lang.Object
java.io.OutputStream
com.codename1.io.gzip.FilterOutputStream
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
DeflaterOutputStream
public class
extends OutputStream
Field Summary
Modifier and Type
Constructor Summary
Modifier
Method Summary
Modifier and
Type
Closes this output stream and releases any system resources associated
with this stream.
void
flush()
Flushes this output stream and forces any buffered output bytes to be
written out.
void
write(byte[] b)
void
Writes b.length bytes from the specified byte array to this output stream.
write(byte[] b, int offset, int length)
Writes len bytes from the specified byte array starting at offset off to this
output stream.
void
write(int b)
void
Field Detail
Method Detail
2344
Constructor Detail
FilterOutputStream
protected FilterOutputStream(OutputStream underlying)
Method Detail
write
public void write(int b)
throws IOException
write
public void write(byte[] b)
throws IOException
write
public void write(byte[] b,
int offset,
int length)
throws IOException
flush
public void flush()
throws IOException
Field Detail
2345
close
public void close()
throws IOException
Method Detail
2346
Class FilterInputStream
java.lang.Object
java.io.InputStream
com.codename1.io.gzip.FilterInputStream
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
InflaterInputStream
public class
extends InputStream
Field Summary
Modifier and Type
protected InputStream in
Constructor Summary
Modifier
Method Summary
Modifier
and Type
int
Returns the number of bytes that can be read (or skipped over) from this input
stream without blocking by the next caller of a method for this input stream.
close()
void
void
boolean
int
Closes this input stream and releases any system resources associated with
the stream.
mark(int readlimit)
Tests if this input stream supports the mark and reset methods.
read()
int
int
Reads some number of bytes from the input stream and stores them into the
buffer array b.
read(byte[] b, int offset, int length)
Reads up to len bytes of data from the input stream into an array of bytes.
reset()
void
long
Class FilterInputStream
Repositions this stream to the position at the time the mark method was last
called on this input stream.
skip(long n)
Skips over and discards n bytes of data from this input stream.
2347
Field Detail
in
protected InputStream in
Constructor Detail
FilterInputStream
protected FilterInputStream(InputStream underlying)
Method Detail
read
public int read()
throws IOException
read
public int read(byte[] b)
throws IOException
read
public int read(byte[] b,
int offset,
int length)
throws IOException
2348
skip
public long skip(long n)
throws IOException
available
public int available()
throws IOException
close
public void close()
throws IOException
Method Detail
2349
mark
public void mark(int readlimit)
markSupported
public boolean markSupported()
Method Detail
2350
Class DeflaterOutputStream
java.lang.Object
java.io.OutputStream
com.codename1.io.gzip.FilterOutputStream
com.codename1.io.gzip.DeflaterOutputStream
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
GZIPOutputStream
public class
extends FilterOutputStream
Field Summary
Modifier and Type
protected byte[]
deflater
protected boolean
mydeflater
Constructor Summary
Constructor and Description
DeflaterOutputStream(OutputStream out)
DeflaterOutputStream(OutputStream out, Deflater def)
DeflaterOutputStream(OutputStream out, Deflater deflater, int size)
DeflaterOutputStream(OutputStream out, Deflater deflater, int size,
boolean close_out)
Method Summary
Modifier and
Type
void
Closes this output stream and releases any system resources associated
with this stream.
protected int
deflate(int flush)
void
finish()
flush()
void
Flushes this output stream and forces any buffered output bytes to be
written out.
Deflater
getDeflater()
boolean
getSyncFlush()
Class DeflaterOutputStream
2351
getTotalIn()
long
getTotalOut()
void
setSyncFlush(boolean syncFlush)
write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this
output stream.
void
write(int b)
void
Field Detail
deflater
protected final Deflater deflater
buffer
protected byte[] buffer
mydeflater
protected boolean mydeflater
DEFAULT_BUFSIZE
protected static final int DEFAULT_BUFSIZE
See Also:
Constant Field Values
Constructor Detail
DeflaterOutputStream
public DeflaterOutputStream(OutputStream out)
throws IOException
Throws:
IOException
DeflaterOutputStream
public DeflaterOutputStream(OutputStream out,
Deflater def)
throws IOException
Throws:
IOException
DeflaterOutputStream
public DeflaterOutputStream(OutputStream out,
Deflater deflater,
int size)
throws IOException
Throws:
IOException
Method Summary
2352
Throws:
IOException
Method Detail
write
public void write(int b)
throws IOException
write
public void write(byte[] b,
int off,
int len)
throws IOException
finish
public void finish()
throws IOException
Throws:
IOException
close
public void close()
throws IOException
Constructor Detail
2353
in class FilterOutputStream
Throws:
IOException
deflate
protected int deflate(int flush)
throws IOException
Throws:
IOException
flush
public void flush()
throws IOException
getTotalIn
public long getTotalIn()
getTotalOut
public long getTotalOut()
setSyncFlush
public void setSyncFlush(boolean syncFlush)
getSyncFlush
public boolean getSyncFlush()
getDeflater
public Deflater getDeflater()
Method Detail
2354
Class Deflater
java.lang.Object
com.codename1.io.gzip.ZStream
com.codename1.io.gzip.Deflater
Field Summary
Constructor Summary
Constructor and Description
Deflater()
Deflater(int level)
Deflater(int level, boolean nowrap)
Deflater(int level, int bits)
Deflater(int level, int bits, boolean nowrap)
Deflater(int level, int bits, int memlevel)
Deflater(int level, int bits, int memlevel,
com.codename1.io.gzip.JZlib.WrapperType wrapperType)
Method Summary
Modifier
and Type
int
copy(Deflater src)
int
deflate(int flush)
int
Class Deflater
end()
boolean
finished()
int
init(int level)
int
int
int
int
int
int
int
2355
Constructor Detail
Deflater
public Deflater()
Deflater
public Deflater(int level)
throws GZIPException
Throws:
GZIPException
Deflater
public Deflater(int level,
boolean nowrap)
throws GZIPException
Throws:
GZIPException
Deflater
public Deflater(int level,
int bits)
throws GZIPException
Throws:
GZIPException
Deflater
public Deflater(int level,
int bits,
boolean nowrap)
throws GZIPException
Throws:
GZIPException
Deflater
public Deflater(int level,
int bits,
int memlevel,
com.codename1.io.gzip.JZlib.WrapperType wrapperType)
throws GZIPException
Throws:
GZIPException
Deflater
public Deflater(int level,
int bits,
int memlevel)
throws GZIPException
2356
Method Detail
init
public int init(int level)
init
public int init(int level,
boolean nowrap)
init
public int init(int level,
int bits)
init
public int init(int level,
int bits,
int memlevel,
com.codename1.io.gzip.JZlib.WrapperType wrapperType)
init
public int init(int level,
int bits,
int memlevel)
init
public int init(int level,
int bits,
boolean nowrap)
deflate
public int deflate(int flush)
Overrides:
deflate
in class ZStream
end
public int end()
setDictionary
public int setDictionary(byte[] dictionary,
int dictLength)
finished
public boolean finished()
Overrides:
finished
in class ZStream
copy
public int copy(Deflater src)
Constructor Detail
2357
Class Deflate
java.lang.Object
com.codename1.io.gzip.Deflate
Method Summary
Modifier and Type Method and Description
Object
clone()
Method Detail
clone
public Object clone()
Method Detail
2358
Class CRC32
java.lang.Object
com.codename1.io.gzip.CRC32
Constructor Summary
Constructor and Description
CRC32()
Method Summary
Modifier and Type
CRC32
copy()
static int[]
getCRC32Table()
long
getValue()
void
reset()
void
reset(long vv)
void
Constructor Detail
CRC32
public CRC32()
Method Detail
update
public void update(byte[] buf,
int index,
int len)
reset
public void reset()
reset
public void reset(long vv)
getValue
public long getValue()
Method Detail
2359
getCRC32Table
public static int[] getCRC32Table()
Method Detail
2360
Class Adler32
java.lang.Object
com.codename1.io.gzip.Adler32
Constructor Summary
Constructor and Description
Adler32()
Method Summary
Modifier and Type
Adler32
copy()
long
getValue()
void
reset()
void
reset(long init)
void
Constructor Detail
Adler32
public Adler32()
Method Detail
reset
public void reset(long init)
reset
public void reset()
getValue
public long getValue()
update
public void update(byte[] buf,
int index,
int len)
Class Adler32
2361
Method Detail
2362
Class WebServiceProxyCall
java.lang.Object
com.codename1.io.WebServiceProxyCall
public class
extends Object
Utility class used by the webservice proxy code to invoke server code
static class
Field Summary
Modifier and Type
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
static int
Class WebServiceProxyCall
2363
TYPE_INT
Constructor Summary
Constructor and Description
WebServiceProxyCall()
Method Summary
Modifier and Type
static
WebServiceProxyCall.WSDefinition
static void
static Object
invokeWebserviceSync(WebServiceProxyCall.WSDefinition d
Object... arguments)
Field Detail
Field Summary
2364
Field Detail
2365
Field Detail
2366
Field Detail
2367
Constructor Detail
WebServiceProxyCall
public WebServiceProxyCall()
Method Detail
invokeWebserviceSync
public static Object invokeWebserviceSync(WebServiceProxyCall.WSDefinition def,
Object... arguments)
throws IOException
Creates a webservice definition object which can be used to invoke the webservice.
Parameters:
url - the url of the webservice
serviceName - the name of the service method
returnType - the return type for the webservice one of the TYPE_* constants
argumentTypes - the arguments for the webservice using the TYPE_*
constants
Returns:
a WSDefinition object
Field Detail
2368
Class WebServiceProxyCall.WSDefinition
java.lang.Object
com.codename1.io.WebServiceProxyCall.WSDefinition
Enclosing class:
WebServiceProxyCall
Webservice definition type, allows defining the argument values for a specific WS call
Constructor Summary
Constructor and Description
WSDefinition()
Method Summary
Constructor Detail
WSDefinition
public WSDefinition()
Method Detail
2369
Class Util
java.lang.Object
com.codename1.io.Util
public class
extends Object
Constructor Summary
Constructor and Description
Util()
Method Summary
Modifier
and Type
static
void
static
void
static
void
static
String
static
boolean
static
void
static
void
static
boolean
static
void
static
void
static
String
Constructor Detail
Closes the object (connection, stream etc.) without throwing any exception, even
if the object is null
copy(InputStream i, OutputStream o)
Copy the input stream into the output stream, closes both streams when
finishing or in a case of an exception
copy(InputStream i, OutputStream o, int bufferSize)
Copy the input stream into the output stream, closes both streams when
finishing or in a case of an exception
decode(String s, String enc, boolean plusToSpace)
Blocking method that will download the given URL to the file system storage and
return when the operation completes
downloadUrlToFileSystemInBackground(String url, String fileName)
Non-blocking method that will download the given URL to file system storage in
the background and return immediately
downloadUrlToFileSystemInBackground(String url, String fileName,
ActionListener onCompletion)
Non-blocking method that will download the given URL to file system storage in
the background and return immediately
downloadUrlToStorage(String url, String fileName, boolean showProgress)
Blocking method that will download the given URL to storage and return when
the operation completes
downloadUrlToStorageInBackground(String url, String fileName)
Non-blocking method that will download the given URL to storage in the
background and return immediately.
downloadUrlToStorageInBackground(String url, String fileName,
ActionListener onCompletion)
Non-blocking method that will download the given URL to storage in the
background and return immediately
encodeBody(byte[] buf)
Deprecated.
use encodeUrl(char[]) instead
2370
encodeBody(char[] buf)
Encode a string for HTML post requests matching the style used in
application/x-www-form-urlencoded
encodeBody(String str)
Encode a string for HTML post requests matching the style used in
application/x-www-form-urlencoded
encodeUrl(byte[] buf)
Deprecated.
use encodeUrl(char[]) instead
static
String
encodeUrl(char[] buf)
static
String
encodeUrl(String str)
static
String
static
String
These chars will not be encoded by the encoding method in this class as
requested in RFE 427 http://java.net/jira/browse/LWUIT-427
getURLBasePath(String url)
Returns the URL's base path, which is the same as the path only without an
ending file e.g.: http://domain.com/f/f.html would return as: /f/
static
String
getURLHost(String url)
static
String
getURLPath(String url)
static
String
getURLProtocol(String url)
static
int
static
void
Finds the object at the given offset while using the == operator and not the
equals method call, it doesn't rely on the ordering of the elements like the Arrays
method.
insertObjectAtOffset(Object[] sourceArray, Object[] destinationArray,
int offset, Object o)
static
boolean
Deprecated.
this method serves as a temporary workaround for an XMLVM bug and will be
removed once the bug is fixed
instanceofDoubleArray(Object o)
static
boolean
Deprecated.
this method serves as a temporary workaround for an XMLVM bug and will be
removed once the bug is fixed
instanceofFloatArray(Object o)
static
boolean
Deprecated.
this method serves as a temporary workaround for an XMLVM bug and will be
removed once the bug is fixed
instanceofIntArray(Object o)
static
boolean
Deprecated.
this method serves as a temporary workaround for an XMLVM bug and will be
removed once the bug is fixed
instanceofLongArray(Object o)
static
boolean
Deprecated.
this method serves as a temporary workaround for an XMLVM bug and will be
removed once the bug is fixed
instanceofObjArray(Object o)
static
boolean
Deprecated.
this method serves as a temporary workaround for an XMLVM bug and will be
removed once the bug is fixed
instanceofShortArray(Object o)
static
boolean
Method Summary
Deprecated.
this method serves as a temporary workaround for an XMLVM bug and will be
removed once the bug is fixed
2371
static
int
readAll(InputStream i, byte[] b)
static
void
static
void
The read fully method from data input stream is very useful for all types of
streams...
readFully(InputStream i, byte[] b, int off, int len)
The read fully method from data input stream is very useful for all types of
streams...
static
byte[]
readInputStream(InputStream i)
static
Object
readObject(DataInputStream input)
static
String
readToString(InputStream i)
static
String
static
String
readUTF(DataInputStream d)
static
void
register(Externalizable e)
static
void
static
String
static
void
static
void
static
void
static
void
static
void
static
String[]
Removes the object at the source array offset and copies all other objects to the
destination array
removeObjectAtOffset(Object[] sourceArray, Object[] destinationArray,
Object o)
Removes the object at the source array offset and copies all other objects to the
destination array
setIgnorCharsWhileEncoding(String s)
These chars will not be encoded by the encoding method in this class as
requested in RFE 427 http://java.net/jira/browse/LWUIT-427
setImplementation(com.codename1.impl.CodenameOneImplementation impl)
Invoked internally from Display, this method is for internal use only
sleep(int t)
Shorthand method for Thread sleep that doesn't throw the stupid interrupted
checked exception
split(String original, String separator)
Provides a utility method breaks a given String to array of String according to the
given separator
toCharArray(String s)
static
char[]
toCharArray should return a new array always, however some devices might
suffer a bug that allows mutating a String (serious security hole in the JVM)
hence this method simulates the proper behavior
wait(Object o, int t)
static
void
Shorthand method wait method that doesn't throw the stupid interrupted
checked exception, it also includes the synchronized block to further reduce
code clutter
static
void
static
void
writeUTF(String s, DataOutputStream d)
Method Summary
2372
Constructor Detail
Util
public Util()
Method Detail
setIgnorCharsWhileEncoding
public static void setIgnorCharsWhileEncoding(String s)
These chars will not be encoded by the encoding method in this class as requested in
RFE 427 http://java.net/jira/browse/LWUIT-427
Parameters:
s - set of characters to skip when encoding
getIgnorCharsWhileEncoding
public static String getIgnorCharsWhileEncoding()
These chars will not be encoded by the encoding method in this class as requested in
RFE 427 http://java.net/jira/browse/LWUIT-427
Returns:
chars skipped
copy
public static void copy(InputStream i,
OutputStream o)
throws IOException
Copy the input stream into the output stream, closes both streams when finishing or
in a case of an exception
Parameters:
i - source
o - destination
Throws:
IOException
copy
public static void copy(InputStream i,
OutputStream o,
int bufferSize)
throws IOException
Copy the input stream into the output stream, closes both streams when finishing or
in a case of an exception
Parameters:
i - source
o - destination
bufferSize - the size of the buffer, which should be a power of 2 large
enoguh
Throws:
IOException
cleanup
public static void cleanup(Object o)
Closes the object (connection, stream etc.) without throwing any exception, even if
the object is null
Parameters:
2373
register
public static void register(Externalizable e)
Method Detail
2374
Deprecated. this method serves as a temporary workaround for an XMLVM bug and
will be removed once the bug is fixed
This method allows working around issue 58
Parameters:
o - object to test
Returns:
true if it matches the state
instanceofByteArray
public static boolean instanceofByteArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and
will be removed once the bug is fixed
This method allows working around issue 58
Parameters:
o - object to test
Returns:
true if it matches the state
instanceofShortArray
public static boolean instanceofShortArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and
will be removed once the bug is fixed
This method allows working around issue 58
Parameters:
o - object to test
Returns:
true if it matches the state
instanceofLongArray
public static boolean instanceofLongArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and
will be removed once the bug is fixed
This method allows working around issue 58
Parameters:
o - object to test
Returns:
true if it matches the state
instanceofIntArray
public static boolean instanceofIntArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and
will be removed once the bug is fixed
This method allows working around issue 58
Parameters:
o - object to test
Returns:
true if it matches the state
instanceofFloatArray
public static boolean instanceofFloatArray(Object o)
Deprecated. this method serves as a temporary workaround for an XMLVM bug and
will be removed once the bug is fixed
This method allows working around issue 58
Parameters:
o - object to test
Returns:
true if it matches the state
Method Detail
2375
Deprecated. this method serves as a temporary workaround for an XMLVM bug and
will be removed once the bug is fixed
This method allows working around issue 58
Parameters:
o - object to test
Returns:
true if it matches the state
readObject
public static Object readObject(DataInputStream input)
throws IOException
toCharArray should return a new array always, however some devices might suffer a
bug that allows mutating a String (serious security hole in the JVM) hence this
method simulates the proper behavior
Parameters:
s - a string
Returns:
the contents of the string as a char array guaranteed to be a copy of the
current array
decode
public static String decode(String s,
String enc,
boolean plusToSpace)
Encode a string for HTML post requests matching the style used in
application/x-www-form-urlencoded
Parameters:
str - none encoded string
Returns:
encoded string
Method Detail
2376
Encode a string for HTML post requests matching the style used in
application/x-www-form-urlencoded
Parameters:
buf - none encoded string
Returns:
encoded string
encodeBody
public static String encodeBody(byte[] buf)
Method Detail
2377
Returns the URL's base path, which is the same as the path only without an ending
file e.g.: http://domain.com/f/f.html would return as: /f/
Parameters:
url - absolute URL
Returns:
the path within the host
writeUTF
public static void writeUTF(String s,
DataOutputStream d)
throws IOException
Writes a string with a null flag, this allows a String which may be null
Parameters:
s - the string to write
d - the destination output stream
Throws:
IOException
readUTF
public static String readUTF(DataInputStream d)
throws IOException
readFully
public static void readFully(InputStream i,
byte[] b)
throws IOException
The read fully method from data input stream is very useful for all types of streams...
Parameters:
b - the buffer into which the data is read.
Throws:
IOException - the stream has been closed and the contained input stream
does not support reading after close, or another I/O error occurs.
readFully
public static final void readFully(InputStream i,
byte[] b,
int off,
int len)
throws IOException
The read fully method from data input stream is very useful for all types of streams...
Parameters:
Method Detail
2378
read.
Throws:
- the stream has been closed and the contained input stream
does not support reading after close, or another I/O error occurs.
IOException
readAll
public static int readAll(InputStream i,
byte[] b)
throws IOException
Provides a utility method breaks a given String to array of String according to the
given separator
Parameters:
original - the String to break
separator - the pattern to look in the original String
Returns:
array of Strings from the original String
setImplementation
Invoked internally from Display, this method is for internal use only
Parameters:
impl - implementation instance
mergeArrays
public static void mergeArrays(Object[] arr1,
Object[] arr2,
Object[] destinationArray)
Removes the object at the source array offset and copies all other objects to the
destination array
Parameters:
sourceArray - the source array
destinationArray - the resulting array which should be of the length
sourceArray.length - 1
o - the object to remove from the array
removeObjectAtOffset
public static void removeObjectAtOffset(Object[] sourceArray,
Object[] destinationArray,
int offset)
Removes the object at the source array offset and copies all other objects to the
destination array
Parameters:
Method Detail
2379
sourceArray.length - 1
offset - the offset of the array
insertObjectAtOffset
public static void insertObjectAtOffset(Object[] sourceArray,
Object[] destinationArray,
int offset,
Object o)
Finds the object at the given offset while using the == operator and not the equals
method call, it doesn't rely on the ordering of the elements like the Arrays method.
Parameters:
arr - the array
value - the value to search
Returns:
the offset or -1
downloadUrlToStorage
public static boolean downloadUrlToStorage(String url,
String fileName,
boolean showProgress)
Blocking method that will download the given URL to storage and return when the
operation completes
Parameters:
url - the URL
fileName - the storage file name
showProgress - whether to block the UI until download completes/fails
Returns:
true on success false on error
downloadUrlToFile
public static boolean downloadUrlToFile(String url,
String fileName,
boolean showProgress)
Blocking method that will download the given URL to the file system storage and
return when the operation completes
Parameters:
url - the URL
fileName - the file name
showProgress - whether to block the UI until download completes/fails
Returns:
true on success false on error
downloadUrlToStorageInBackground
public static void downloadUrlToStorageInBackground(String url,
String fileName)
Non-blocking method that will download the given URL to storage in the background
and return immediately. This method can be used to fetch data dynamically and
asynchronously e.g. in this code it is used to fetch book covers for the ImageViewer:
Form hi = new Form("ImageViewer", new BorderLayout());
Method Detail
2380
Method Detail
2381
Parameters:
url - the URL
fileName - the storage file name
downloadUrlToFileSystemInBackground
public static void downloadUrlToFileSystemInBackground(String url,
String fileName)
Non-blocking method that will download the given URL to file system storage in the
background and return immediately
Parameters:
url - the URL
fileName - the file name
downloadUrlToStorageInBackground
public static void downloadUrlToStorageInBackground(String url,
String fileName,
ActionListener onCompletion)
Non-blocking method that will download the given URL to storage in the background
and return immediately
Parameters:
url - the URL
fileName - the storage file name
onCompletion - invoked when download completes
downloadUrlToFileSystemInBackground
public static void downloadUrlToFileSystemInBackground(String url,
String fileName,
ActionListener onCompletion)
Non-blocking method that will download the given URL to file system storage in the
background and return immediately
Parameters:
url - the URL
fileName - the file name
onCompletion - invoked when download completes
Method Detail
2382
Shorthand method for Thread sleep that doesn't throw the stupid interrupted checked
exception
Parameters:
t - the time
wait
public static void wait(Object o,
int t)
Shorthand method wait method that doesn't throw the stupid interrupted checked
exception, it also includes the synchronized block to further reduce code clutter
Parameters:
o - the object to wait on
t - the time
Method Detail
2383
Class Storage
java.lang.Object
com.codename1.io.Storage
public class
extends Object
Constructor Summary
Constructor and Description
Storage()
Method Summary
Modifier and
Type
void
void
InputStream
OutputStream
void
int
boolean
Storage is cached for faster access, however this might cause a problem
with refreshing objects since they are not cloned.
clearStorage()
void
static Storage
static boolean
Returns the storage instance or null if the storage wasn't initialized using a
call to init(String) first.
isInitialized()
boolean
String[]
Object
void
void
Class Storage
Reads the object from the storage, returns null if the object isn't there
setHardCacheSize(int size)
2384
Constructor Detail
Storage
public Storage()
Method Detail
setHardCacheSize
public void setHardCacheSize(int size)
Returns the storage instance or null if the storage wasn't initialized using a call to
init(String) first.
Returns:
storage instance
clearCache
public void clearCache()
Storage is cached for faster access, however this might cause a problem with
refreshing objects since they are not cloned. Clearing the cache allows to actually
reload from the storage file.
flushStorageCache
public void flushStorageCache()
Flush the storage cache allowing implementations that cache storage objects to store
deleteStorageFile
public void deleteStorageFile(String name)
Method Summary
2385
createInputStream
public InputStream createInputStream(String name)
throws IOException
exists
public boolean exists(String name)
Writes the given object to storage assuming it is an externalizable type or one of the
supported types
Parameters:
name - store name
o - object to store
Returns:
true for success, false for failue
Method Detail
2386
Reads the object from the storage, returns null if the object isn't there
Parameters:
name - name of the store
Returns:
object stored under that name
isNormalizeNames
public boolean isNormalizeNames()
Method Detail
2387
Class SocketConnection
java.lang.Object
com.codename1.io.SocketConnection
Callback for establishment of a socket connection. Notice this callback is always invoked on a new
separate thread to allow uninterrupted IO.
Constructor Summary
Constructor and Description
SocketConnection()
Method Summary
Modifier and
Type
abstract void
abstract void
boolean
Constructor Detail
SocketConnection
public SocketConnection()
Method Detail
connectionError
public abstract void connectionError(int errorCode,
String message)
Invoked in case of an error in the socket connection, this method is invoked off the
EDT
Parameters:
errorCode - the error code
message - error message if applicable
Class SocketConnection
2388
Invoked when a socket connection is established, this method is invoked off the EDT
Parameters:
is - input stream for the socket
os - output stream for the socket
isConnected
public boolean isConnected()
Method Detail
2389
Class Socket
java.lang.Object
com.codename1.io.Socket
public class
extends Object
Method Summary
Modifier and Type
static void
static String
static boolean
static boolean
static
Socket.StopListening
Method Detail
isSupported
public static boolean isSupported()
Returns true if server sockets are supported in this port, if this method returns false
invocations of listen will always fail
Returns:
true if server sockets are supported in this port, false otherwise
Class Socket
2390
Method Detail
2391
Interface Socket.StopListening
Enclosing class:
Socket
Method Summary
Modifier and Type Method and Description
stop()
void
Stop listening
Method Detail
stop
void stop()
Stop listening
Interface Socket.StopListening
2392
Class Properties
java.lang.Object
java.util.AbstractMap<K,V>
java.util.HashMap<String,String>
com.codename1.io.Properties
All Implemented Interfaces:
Map<String,String>
public class
extends HashMap<String,String>
A Properties object is a Hashtable where the keys and values must be Strings. Each property can
have a default Properties list which specifies the default values to be used when a given key is not
found in this Properties instance.
Character Encoding
Note that in some cases Properties uses ISO-8859-1 instead of UTF-8. ISO-8859-1 is only capable
of representing a tiny subset of Unicode. Use either the loadFromXML/storeToXML methods (which use
UTF-8 by default) or the load/store overloads that take an OutputStreamWriter (so you can supply a
UTF-8 instance) instead.
See Also:
Hashtable, java.lang.System#getProperties
Field Summary
Modifier and Type
protected Properties
The default values for keys not found in this Properties instance.
Constructor Summary
Constructor and Description
Properties()
Method Summary
Modifier and
Type
String
Method Detail
2393
String
void
load(Reader in)
void
Enumeration<?>
propertyNames()
Deprecated.
This method ignores any IOException thrown while writing -- use
store(java.io.OutputStream, java.lang.String) instead for better
exception handling.
void
Object
void
void
using ISO-8859-1.
Returns those property names (keys) in this Properties object for which
both key and value are strings.
Field Detail
defaults
protected Properties defaults
The default values for keys not found in this Properties instance.
Constructor Detail
Properties
public Properties()
Method Summary
2394
Method Detail
getProperty
public String getProperty(String name)
Searches for the property with the specified name. If the property is not found, the
default Properties are checked. If the property is not found in the default Properties,
null is returned.
Parameters:
name - the name of the property to find.
Returns:
the named property value, or null if it can't be found.
getProperty
public String getProperty(String name,
String defaultValue)
Searches for the property with the specified name. If the property is not found, it looks
in the default Properties. If the property is not found in the default Properties, it
returns the specified default.
Parameters:
name - the name of the property to find.
defaultValue - the default value.
Returns:
the named property value.
load
public void load(InputStream in)
throws IOException
load
public void load(Reader in)
throws IOException
Loads properties from the specified Reader. The properties file is interpreted
according to the following rules:
Empty lines are ignored.
Lines starting with either a "#" or a "!" are comment lines and are ignored.
A backslash at the end of the line escapes the following newline character
("\r", "\n", "\r\n"). If there's whitespace after the backslash it will just escape
that whitespace instead of concatenating the lines. This does not apply to
comment lines.
A property line consists of the key, the space between the key and the value,
and the value. The key goes up to the first whitespace, "=" or ":" that is not
escaped. The space between the key and the value contains either one
whitespace, one "=" or one ":" and any amount of additional whitespace
before and after that character. The value starts with the first character after
the space between the key and the value.
Constructor Detail
2395
Since:
1.6
propertyNames
public Enumeration<?> propertyNames()
Returns those property names (keys) in this Properties object for which both key and
value are strings.
Returns:
a set of keys in the property list
Since:
1.6
save
@Deprecated
public void save(OutputStream out,
String comment)
Deprecated. This method ignores any IOException thrown while writing -- use
store(java.io.OutputStream, java.lang.String) instead for better exception
handling.
Saves the mappings in this Properties to the specified OutputStream, putting the
specified comment at the beginning. The output from this method is suitable for being
read by the load(InputStream) method.
Parameters:
out - the OutputStream to write to.
comment - the comment to add at the beginning.
Throws:
ClassCastException - if the key or value of a mapping is not a String.
setProperty
public Object setProperty(String name,
String value)
Maps the specified key to the specified value. If the key already exists, the old value
is replaced. The key and value cannot be null.
Parameters:
name - the key.
value - the value.
Returns:
the old value mapped to the key, or null.
store
public void store(OutputStream out,
String comment)
throws IOException
Method Detail
2396
Stores the mappings in this Properties object to out, putting the specified comment
at the beginning.
Parameters:
writer - the Writer
comment - an optional comment to be written, or null
Throws:
IOException
ClassCastException
Since:
1.6
Method Detail
2397
Class Preferences
java.lang.Object
com.codename1.io.Preferences
public class
extends Object
Simple map like class to store application and Codename One preference settings.
Method Summary
Modifier and Type
static void
static void
static boolean
static double
static float
static int
static long
static String
static void
static void
static void
static void
static void
static void
Method Detail
set
public static void set(String pref,
String s)
Class Preferences
2398
Method Detail
2399
Returns:
the default value or the value
get
public static int get(String pref,
int def)
Method Detail
2400
Class Oauth2
java.lang.Object
com.codename1.io.Oauth2
public class
extends Object
This is a utility class that allows Oauth2 authentication This utility uses the Codename One XHTML
Component to display the authentication pages. http://tools.ietf.org/pdf/draft-ietf-oauth-v2-12.pdf
Field Summary
Modifier and Type Field and Description
static String
TOKEN
Constructor Summary
Constructor and Description
Oauth2(String oauth2URL, String clientId, String redirectURI)
Simple constructor
Oauth2(String oauth2URL, String clientId, String redirectURI, String scope)
Simple constructor
Oauth2(String oauth2URL, String clientId, String redirectURI, String scope,
String tokenRequestURL, String clientSecret)
Simple constructor
Oauth2(String oauth2URL, String clientId, String redirectURI, String scope,
String tokenRequestURL, String clientSecret, Hashtable additionalParams)
Simple constructor
Method Summary
Modifier and
Type
Deprecated.
use createAuthComponent or showAuthentication which work
asynchronously and adapt better to different platforms
String
Component
createAuthComponent(ActionListener al)
static
String
getExpires()
static
boolean
isBackToParent()
static void
void
Class Oauth2
2401
Detail
TOKEN
public static final String TOKEN
See Also:
Constant Field Values
Constructor Detail
Oauth2
public Oauth2(String oauth2URL,
String clientId,
String redirectURI)
Simple constructor
Parameters:
oauth2URL - the authentication url of the service
clientId - the client id that would like to use the
redirectURI - the redirect uri
service
Oauth2
public Oauth2(String
String
String
String
oauth2URL,
clientId,
redirectURI,
scope)
Simple constructor
Parameters:
oauth2URL - the authentication url of the service
clientId - the client id that would like to use the
redirectURI - the redirect uri
scope - the authentication scope
service
Oauth2
public Oauth2(String
String
String
String
String
String
oauth2URL,
clientId,
redirectURI,
scope,
tokenRequestURL,
clientSecret)
Simple constructor
Parameters:
oauth2URL - the authentication url of the service
clientId - the client id that would like to use the
redirectURI - the redirect uri
scope - the authentication scope
clientSecret - the client secret
service
Oauth2
public Oauth2(String oauth2URL,
String clientId,
String redirectURI,
String scope,
String tokenRequestURL,
String clientSecret,
Hashtable additionalParams)
Simple constructor
Parameters:
oauth2URL - the authentication url of the service
clientId - the client id that would like to use the
redirectURI - the redirect uri
scope - the authentication scope
Field Detail
service
2402
request
Method Detail
isBackToParent
public static boolean isBackToParent()
This method creates a component which can authenticate. You will receive either the
authentication key or an Exception object within the ActionListener callback method.
Parameters:
al - a listener that will receive at its source either a token for the service or an
exception in case of a failure
Returns:
a component that should be displayed to the user in order to perform the
authentication
showAuthentication
public void showAuthentication(ActionListener al)
Constructor Detail
2403
Class NetworkManager
java.lang.Object
com.codename1.io.NetworkManager
public class
extends Object
Main entry point for managing the connection requests, this is essentially a threaded queue that
makes sure to route all connections via the network thread while sending the callbacks through the
Codename One EDT.
The sample code below fetches a page of data from the nestoria housing listing API.
You can see instructions on how to display the data in the InfiniteScrollAdapter class.
int pageNumber = 1;
java.util.List<Map<String, Object>> fetchPropertyData(String text) {
try {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("http://api.nestoria.co.uk/api");
r.addArgument("pretty", "0");
r.addArgument("action", "search_listings");
r.addArgument("encoding", "json");
r.addArgument("listing_type", "buy");
r.addArgument("page", "" + pageNumber);
pageNumber++;
r.addArgument("country", "uk");
r.addArgument("place_name", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getRes
Map<String, Object> response = (Map<String, Object>)result.get("response");
return (java.util.List<Map<String, Object>>)response.get("listings");
} catch(Exception err) {
Log.e(err);
return null;
}
}
Field Summary
Modifier and Type
static int
static int
static int
static int
static int
static int
Method Summary
Modifier and
Type
void
Method Detail
Adds a header to the global default headers, this header will be implicitly
added to all requests going out from this point onwards.
2404
void
void
void
Identical to add to queue but waits until the request is processed in the
queue, this is useful for completely synchronous operations.
assignToThread(Class requestType, int offset)
void
Enumeration
String[]
String
int
static String
String
static
NetworkManager
int
int
boolean
boolean
Returns the user displayable name for the given access point
getAPType(String id)
void
void
void
static void
void
Kills the given request and waits until the request is killed if it is being
processed by one of the threads.
removeErrorListener(ActionListener e)
void
void
void
void
Method Summary
Deprecated.
This method is for internal use only
shutdownSync()
Shuts down the network thread and waits for shutdown to complete
2405
void
Field Detail
ACCESS_POINT_TYPE_UNKNOWN
public static final int ACCESS_POINT_TYPE_UNKNOWN
Indicates a corporate routing server access point type (e.g. BIS etc.)
See Also:
Constant Field Values
Method Detail
getAutoDetectURL
public static String getAutoDetectURL()
2406
Thread count should never be changed when the network is running since it will have
no effect. Increasing the thread count can bring many race conditions and problems
to the surface, furthermore MIDP doesn't require support for more than one network
thread hence increasing the thread count might fail.
Parameters:
threadCount - the threadCount to set
start
public void start()
There is no need to invoke this method since the network manager is started
implicitly. It is useful only if you explicitly stop the network manager. Invoking this
method otherwise will just do nothing.
shutdown
public void shutdown()
Shuts down the network thread and waits for shutdown to complete
getInstance
public static NetworkManager getInstance()
Adds a header to the global default headers, this header will be implicitly added to all
requests going out from this point onwards. The main use case for this is for
authentication information communication via the header.
Parameters:
key - the key of the header
value - the value of the header
addToQueueAndWait
public void addToQueueAndWait(ConnectionRequest request)
Identical to add to queue but waits until the request is processed in the queue, this is
useful for completely synchronous operations.
Parameters:
Method Detail
2407
addToQueue
public void addToQueue(ConnectionRequest request)
Kills the given request and waits until the request is killed if it is being processed by
one of the threads. This method must not be invoked from a network thread!
Parameters:
request setTimeout
public void setTimeout(int t)
Sets the timeout in milliseconds for network connections, a timeout may be "faked"
for platforms that don't support the notion of a timeout such as MIDP
Parameters:
t - the timeout duration
getTimeout
public int getTimeout()
Adds a generic listener to a network error that is invoked before the exception is
propagated. Notice that this doesn't apply to server error codes! Consume the event
in order to prevent it from propagating further.
Parameters:
e - callback will be invoked with the Exception as the source object
removeErrorListener
public void removeErrorListener(ActionListener e)
Method Detail
2408
Returns the user displayable name for the given access point
Parameters:
id - the id of the access point
Returns:
the name of the access point
getCurrentAccessPoint
public String getCurrentAccessPoint()
Method Detail
2409
Class NetworkEvent
java.lang.Object
com.codename1.ui.events.ActionEvent
com.codename1.io.NetworkEvent
public class
extends ActionEvent
Event containing more meta data for network events which may be error events or an update for
progress indication code.
Field Summary
Modifier and Type
static int
static int
static int
static int
Constructor Summary
Constructor and Description
NetworkEvent(ConnectionRequest source, Exception error)
Constructs a network status update event used to update progress indicators and application
logic of the current state in the NetworkManager
NetworkEvent(ConnectionRequest request, int responseCode, String message)
Constructs a callback event from a connection request with some arbitrary associated meta
data
Method Summary
Modifier and Type
ConnectionRequest
Exception
Class NetworkEvent
2410
Returns the length of the download event or the upload event in case it
is known.
String
getMessage()
Object
getMetaData()
getProgressPercentage()
int
getProgressType()
int
int
int
void
setError(Exception error)
Field Detail
PROGRESS_TYPE_INITIALIZING
public static final int PROGRESS_TYPE_INITIALIZING
Method Summary
2411
Detail
NetworkEvent
public NetworkEvent(ConnectionRequest source,
Exception error)
Constructs a network status update event used to update progress indicators and
application logic of the current state in the NetworkManager
Parameters:
request - the connection request indicating progress
progressType NetworkEvent
public NetworkEvent(ConnectionRequest request,
Object metaData)
Constructs a callback event from a connection request with some arbitrary associated
meta data
Parameters:
request - the connection request
metaData - the data associated with the event
Method Detail
getConnectionRequest
public ConnectionRequest getConnectionRequest()
Returns:
the error
setError
public void setError(Exception error)
Parameters:
error
Constructor Detail
2412
Returns the length of the download event or the upload event in case it is known. -1
is returned when the value is unknown.
Returns:
the length length in bytes or -1
getSentReceived
public int getSentReceived()
Returns the amount of data received up to this event or sent up to this event
(depending on the event type).
Returns:
the receieved or sent value
getProgressPercentage
public int getProgressPercentage()
Returns:
the metaData
getMessage
public String getMessage()
Returns:
the message
Method Detail
2413
Class MultipartRequest
java.lang.Object
com.codename1.io.ConnectionRequest
com.codename1.io.MultipartRequest
All Implemented Interfaces:
IOProgressListener
public class
extends ConnectionRequest
A multipart post request allows a developer to submit large binary data files to the server in a multipart
mime post request. This is a standard method for large binary file uploads to webservers and data
services. The demo code below demonstrates uploading to the filestack.com API.
public void pictureUpload(final Callback<String> resultURL) {
String picture = Capture.capturePhoto(1024, -1);
if(picture!=null){
String filestack = "https://www.filestackapi.com/api/store/S3?key=MY_KEY&filename=myPicture.jpg";
MultipartRequest request = new MultipartRequest() {
protected void readResponse(InputStream input) throws IOException {
JSONParser jp = new JSONParser();
Map<String, Object> result = jp.parseJSON(new InputStreamReader(input, "UTF-8"));
String url = (String)result.get("url");
if(url == null) {
resultURL.onError(null, null, 1, result.toString());
return;
}
resultURL.onSucess(url);
}
};
request.setUrl(filestack);
try {
request.addData("fileUpload", picture, "image/jpeg");
request.setFilename("fileUpload", "myPicture.jpg");
NetworkManager.getInstance().addToQueue(request);
} catch(IOException err) {
err.printStackTrace();
}
}
}
Field Summary
Constructor Summary
Constructor and Description
MultipartRequest()
Initialize variables
Method Summary
Modifier
and Type
void
Class MultipartRequest
2414
Add an argument to the request response without encoding it, this is useful for
arguments which are already encoded
void
void
Adds a binary argument to the arguments, notice the input stream will be read
only during submission
void
void
protected
void
protected
long
buildRequestBody(OutputStream os)
Invoked when send body is true, by default sends the request arguments
based on "POST" conventions
calculateContentLength()
getBoundary()
String
Returns the boundary string which is normally generated based on system time
getContentLength()
int
protected
void
initConnection(Object connection)
boolean
boolean
void
Sets the boundary string, normally you don't need this method.
setCanFlushStream(boolean flush)
static void
Sending large files requires flushing the writer once in a while to prevent Out
Of Memory Errors, Some J2ME implementation are not able to flush the
streams causing the upload to fail.
setFilename(String arg, String filename)
void
void
Method Summary
2415
Constructor Detail
MultipartRequest
public MultipartRequest()
Initialize variables
Method Detail
getBoundary
public String getBoundary()
Returns the boundary string which is normally generated based on system time
Returns:
the multipart boundary string
setBoundary
public void setBoundary(String boundary)
Sets the boundary string, normally you don't need this method. Its useful to
workaround server issues only. Notice that this method must be invoked before
adding any elements.
Parameters:
boundary - the boundary string
initConnection
protected void initConnection(Object connection)
2416
Throws:
IOException
addData
public void addData(String name,
InputStream data,
long dataSize,
String mimeType)
Adds a binary argument to the arguments, notice the input stream will be read only
during submission
Parameters:
name - the name of the data
data - the data stream
dataSize - the byte size of the data stream, if the data stream is a file the file
size can be obtained using the
FileSystemStorage.getInstance().getLength(file) method
mimeType - the mime type for the content
setFilename
public void setFilename(String arg,
String filename)
Add an argument to the request response without encoding it, this is useful for
arguments which are already encoded
Overrides:
addArgumentNoEncoding in class ConnectionRequest
Parameters:
key - the key of the argument
value - the value for the argument
addArgument
public void addArgument(String name,
String value)
buildRequestBody
protected void buildRequestBody(OutputStream os)
throws IOException
Invoked when send body is true, by default sends the request arguments based on
"POST" conventions
Overrides:
buildRequestBody in class ConnectionRequest
Parameters:
os - output stream of the body
Throws:
IOException
Method Detail
2417
By default redirect responses (302 etc.) are handled manually in multipart requests
Returns:
the autoRedirect
setManualRedirect
public void setManualRedirect(boolean autoRedirect)
By default redirect responses (302 etc.) are handled manually in multipart requests,
set this to false to handle the redirect. Notice that a redirect converts a post to a get.
Parameters:
autoRedirect - the autoRedirect to set
setCanFlushStream
public static void setCanFlushStream(boolean flush)
Sending large files requires flushing the writer once in a while to prevent Out Of
Memory Errors, Some J2ME implementation are not able to flush the streams
causing the upload to fail. This method can indicate to the upload to not use the
flushing mechanism.
Method Detail
2418
Class Log
java.lang.Object
com.codename1.io.Log
public class
extends Object
Pluggable logging framework that allows a developer to log into storage using the file connector API.
It is highly recommended to use this class coupled with Netbeans preprocessing tags to reduce its
overhead completely in runtime.
Field Summary
Modifier and
Type
Constant indicating the logging level Debug is the default and the lowest
level followed by info, warning and error
static int
ERROR
Constant indicating the logging level Debug is the default and the lowest
level followed by info, warning and error
static int
INFO
Constant indicating the logging level Debug is the default and the lowest
level followed by info, warning and error
static int
REPORTING_DEBUG
Indicates that log reporting to the cloud should occur regardless of whether
an error occurred
static int
REPORTING_NONE
static int
Indicates that log reporting to the cloud should occur only if an error
occurred
static int
WARNING
Constant indicating the logging level Debug is the default and the lowest
level followed by info, warning and error
static int
Constructor Summary
Modifier Constructor and Description
protected
Log()
Method Summary
Modifier
and Type
static void
protected
Writer
Class Log
Binds pro based crash protection logic that will send out an email in case of an
exception thrown on the EDT
createWriter()
Default method for creating the output writer into which we write, this method
creates a simple log file using the file connector
2419
e(Throwable t)
String
static Log
getInstance()
static int
Returns the logging level for printing log details, the lower the value the more
verbose would the printouts be
getLogContent()
static
String
Returns the contents of the log as a single long string to be displayed by the
application any way it sees fit
getReportingLevel()
static int
Indicates the level of log reporting, this allows developers to send device logs
to the cloud thus tracking crashes or functionality in the device.
protected
String
getThreadAndTimeStamp()
static long
static void
boolean
Returns a server generated unique device id that is cached locally and is only
valid per application.
install(Log newInstance)
Indicates whether GCF's file writing should be used to generate the log file
logThrowable(Throwable t)
protected
void
static void
static void
protected
void
static void
Logs an exception to the log, by default print is called with the exception
details, on supported devices the stack trace is also physically written to the
log
p(String text)
Default println method invokes the print instance method, uses DEBUG level
p(String text, int level)
Default println method invokes the print instance method, uses given level
print(String text, int level)
Default log implementation prints to the console and the file connector if
applicable.
sendLog()
Sends the current log to the cloud regardless of the reporting level
setFileURL(String fileURL)
void
void
Indicates whether GCF's file writing should be used to generate the log file
setLevel(int level)
static void
Sets the logging level for printing log details, the lower the value the more
verbose would the printouts be
setReportingLevel(int level)
static void
Indicates the level of log reporting, this allows developers to send device logs
to the cloud thus tracking crashes or functionality in the device.
showLog()
static void
Deprecated.
this method is an outdated method that's no longer supported
trackFileSystem()
void
Method Summary
2420
Detail
DEBUG
public static final int DEBUG
Constant indicating the logging level Debug is the default and the lowest level
followed by info, warning and error
See Also:
Constant Field Values
INFO
public static final int INFO
Constant indicating the logging level Debug is the default and the lowest level
followed by info, warning and error
See Also:
Constant Field Values
WARNING
public static final int WARNING
Constant indicating the logging level Debug is the default and the lowest level
followed by info, warning and error
See Also:
Constant Field Values
ERROR
public static final int ERROR
Constant indicating the logging level Debug is the default and the lowest level
followed by info, warning and error
See Also:
Constant Field Values
REPORTING_NONE
public static int REPORTING_NONE
Indicates that log reporting to the cloud should occur regardless of whether an error
occurred
REPORTING_PRODUCTION
public static int REPORTING_PRODUCTION
Indicates that log reporting to the cloud should occur only if an error occurred
Constructor Detail
Log
protected Log()
Method Detail
Field Detail
2421
Indicates the level of log reporting, this allows developers to send device logs to the
cloud thus tracking crashes or functionality in the device.
Parameters:
level - one of REPORTING_NONE, REPORTING_DEBUG,
REPORTING_PRODUCTION
getReportingLevel
public static int getReportingLevel()
Indicates the level of log reporting, this allows developers to send device logs to the
cloud thus tracking crashes or functionality in the device.
Returns:
one of REPORTING_NONE, REPORTING_DEBUG,
REPORTING_PRODUCTION
getUniqueDeviceId
public static long getUniqueDeviceId()
Returns a server generated unique device id that is cached locally and is only valid
per application. Notice that this device id is specific to your application and to a
specific install, it is guaranteed to be completely unique or -1 if unavailable (which
can be due to a network error). Warning: this method might block while accessing the
server!s
Returns:
a unique device id
sendLog
public static void sendLog()
Sends the current log to the cloud regardless of the reporting level
install
public static void install(Log newInstance)
Default println method invokes the print instance method, uses DEBUG level
Parameters:
text - the text to print
p
public static void p(String text,
int level)
Default println method invokes the print instance method, uses given level
Parameters:
text - the text to print
level - one of DEBUG, INFO, WARNING, ERROR
e
public static void e(Throwable t)
Method Detail
2422
Logs an exception to the log, by default print is called with the exception details, on
supported devices the stack trace is also physically written to the log
Parameters:
t print
protected void print(String text,
int level)
Default log implementation prints to the console and the file connector if applicable.
Also prepends the thread information and time before
Parameters:
text - the text to print
level - one of DEBUG, INFO, WARNING, ERROR
createWriter
protected Writer createWriter()
throws IOException
Default method for creating the output writer into which we write, this method creates
a simple log file using the file connector
Returns:
writer object
Throws:
IOException - when thrown by the connector
getThreadAndTimeStamp
protected String getThreadAndTimeStamp()
Sets the logging level for printing log details, the lower the value the more verbose
would the printouts be
Parameters:
level - one of DEBUG, INFO, WARNING, ERROR
getLevel
public static int getLevel()
Returns the logging level for printing log details, the lower the value the more verbose
would the printouts be
Returns:
one of DEBUG, INFO, WARNING, ERROR
getLogContent
public static String getLogContent()
Returns the contents of the log as a single long string to be displayed by the
application any way it sees fit
Returns:
string containing the whole log
showLog
public static void showLog()
Method Detail
2423
Indicates whether GCF's file writing should be used to generate the log file
Returns:
the fileWriteEnabled
setFileWriteEnabled
public void setFileWriteEnabled(boolean fileWriteEnabled)
Indicates whether GCF's file writing should be used to generate the log file
Parameters:
fileWriteEnabled - the fileWriteEnabled to set
getFileURL
public String getFileURL()
Binds pro based crash protection logic that will send out an email in case of an
exception thrown on the EDT
Parameters:
consumeError - true will hide the error from the user, false will leave the builtin
logic that defaults to showing an error dialog to the user
Method Detail
2424
Class JSONParser
java.lang.Object
com.codename1.io.JSONParser
All Implemented Interfaces:
JSONParseCallback
public class
extends Object
implements JSONParseCallback
Fast and dirty parser for JSON content on the web, it essentially returns a Map object containing the
object fields mapped to their values. If the value is a nested object a nested Map/List is returned. The
sample code below fetches a page of data from the nestoria housing listing API as a list of Map
elements. You can see instructions on how to display the data in the InfiniteScrollAdapter class.
int pageNumber = 1;
java.util.List<Map<String, Object>> fetchPropertyData(String text) {
try {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("http://api.nestoria.co.uk/api");
r.addArgument("pretty", "0");
r.addArgument("action", "search_listings");
r.addArgument("encoding", "json");
r.addArgument("listing_type", "buy");
r.addArgument("page", "" + pageNumber);
pageNumber++;
r.addArgument("country", "uk");
r.addArgument("place_name", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getRes
Map<String, Object> response = (Map<String, Object>)result.get("response");
return (java.util.List<Map<String, Object>>)response.get("listings");
} catch(Exception err) {
Log.e(err);
return null;
}
}
Constructor Summary
Constructor and Description
JSONParser()
Method Summary
Modifier and Type
void
void
boolean
static boolean
Indicates that the parser will generate long objects and not just
doubles for numeric values
keyValue(String key, String value)
void
void
Class JSONParser
2425
void
Hashtable<String,Object>
Deprecated.
use the new parseJSON instead
parse(Reader i, JSONParseCallback callback)
static void
Static method! Parses the given input stream and fires the data
into the given callback.
parseJSON(Reader i)
Map<String,Object>
Parses the given input stream into this object and returns the
parse tree
setUseLongs(boolean aUseLongsDefault)
static void
Indicates that the parser will generate long objects and not just
doubles for numeric values
startArray(String arrayName)
void
void
void
Constructor Detail
JSONParser
public JSONParser()
Method Detail
isUseLongs
public static boolean isUseLongs()
Indicates that the parser will generate long objects and not just doubles for numeric
values
Returns:
the useLongsDefault
setUseLongs
public static void setUseLongs(boolean aUseLongsDefault)
Indicates that the parser will generate long objects and not just doubles for numeric
values
Parameters:
aUseLongsDefault - the useLongsDefault to set
parse
public static void parse(Reader i,
JSONParseCallback callback)
throws IOException
Static method! Parses the given input stream and fires the data into the given
callback.
Parameters:
i - the reader
Method Summary
2426
Throws:
IOException
parseJSON
public Map<String,Object> parseJSON(Reader i)
throws IOException
Parses the given input stream into this object and returns the parse tree
Parameters:
i - the reader
Returns:
the parse tree as a hashtable
Throws:
IOException - if thrown by the stream
parse
public Hashtable<String,Object> parse(Reader i)
throws IOException
Submits a token from the JSON data as a java string, this token is always a string
value
Specified by:
stringToken in interface JSONParseCallback
Method Detail
2427
This method is called when a string key/value pair is detected within the json it is
essentially redundant when following string/numeric token.
Specified by:
keyValue in interface JSONParseCallback
Parameters:
key - the key
value - a string value
isAlive
public boolean isAlive()
Method Detail
2428
Interface JSONParseCallback
All Known Implementing Classes:
JSONParser
public interface
The event based parser allows parsing without creating an object tree by receiving callbacks to this
class.
Method Summary
Modifier
and Type
void
void
boolean
isAlive()
void
void
void
void
void
This method is called when a string key/value pair is detected within the json it
is essentially redundant when following string/numeric token.
longToken(long tok)
void
Submits a token from the JSON data as a java string, this token is always a
string value
Method Detail
startBlock
void startBlock(String blockName)
Interface JSONParseCallback
2429
Submits a token from the JSON data as a java string, this token is always a string
value
numericToken
void numericToken(double tok)
This method is called when a string key/value pair is detected within the json it is
essentially redundant when following string/numeric token.
Parameters:
key - the key
value - a string value
isAlive
boolean isAlive()
Method Detail
2430
Interface IOProgressListener
All Known Implementing Classes:
AdsService, CachedDataService, ConnectionRequest, GZConnectionRequest,
ImageDownloadService, InnerActive, MultipartRequest, RSSService, TwitterRESTService
public interface
Method Summary
Modifier and
Type
Indicates the number of bytes that were read/written to/from the source
stream
void
Method Detail
ioStreamUpdate
void ioStreamUpdate(Object source,
int bytes)
Indicates the number of bytes that were read/written to/from the source stream
Parameters:
source - the source stream which can be either an input stream or an output
stream
bytes - the number of bytes read or written
Interface IOProgressListener
2431
Class FileSystemStorage
java.lang.Object
com.codename1.io.FileSystemStorage
public class
extends Object
Unlike networking, the file system storage mostly tries to emulate java.io.File with some simplifications
for mobile devices.
A lot of API's rely on FileSystemStorage as its the API native code usually uses consistently. E.g. in
this sample below the FileSystemStorage is used to save a screenshot image for sharing on social
media:
Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);
Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");
Field Summary
Modifier
and Type
static int
Represents the type for the get root type method, this type generally
represents the main phone memory
ROOT_TYPE_SDCARD
static int
Represents the type for the get root type method, this type generally
represents an SD card although due to variability in phone standards an SD
card might be detected incorrectly.
ROOT_TYPE_UNKNOWN
static int
Returned for different types of root for which there is no specific knowledge
one way or the other.
Method Summary
Modifier and Type
void
void
boolean
String
char
Method Detail
2432
getInstance()
Returns the time that the file denoted by this abstract pathname
was last modified.
long
getLength(String file)
long
long
String[]
Returns the filesystem roots from which the structure of the file
system can be traversed
getRootSizeBytes(String root)
long
int
boolean
boolean
isDirectory(String file)
String[]
Lists the files within the given directory, returns relative file names
and not full file names.
mkdir(String directory)
void
InputStream
OutputStream
OutputStream
openInputStream(String file)
void
void
Field Detail
ROOT_TYPE_MAINSTORAGE
public static final int ROOT_TYPE_MAINSTORAGE
Represents the type for the get root type method, this type generally represents the
main phone memory
See Also:
Constant Field Values
ROOT_TYPE_SDCARD
public static final int ROOT_TYPE_SDCARD
Represents the type for the get root type method, this type generally represents an
SD card although due to variability in phone standards an SD card might be detected
incorrectly. E.g. newer Nokia devices such as N97 have a large storage area that is
Method Summary
2433
Returned for different types of root for which there is no specific knowledge one way
or the other.
See Also:
Constant Field Values
Method Detail
getInstance
public static FileSystemStorage getInstance()
Returns the filesystem roots from which the structure of the file system can be
traversed
Returns:
the roots of the filesystem
getRootType
public int getRootType(String root)
Lists the files within the given directory, returns relative file names and not full file
names.
Parameters:
directory - the directory in which files should be listed
Returns:
array of file names
Throws:
IOException
getRootSizeBytes
public long getRootSizeBytes(String root)
Field Detail
2434
Deletes the specific file or empty directory, if the platform supports a delete on exit
this method will activate it. Regardless it will retry deleting (with delay) several times
to allow streams time to close.
Parameters:
file - file to delete
retryCount - the number of times to retry
exists
public boolean exists(String file)
Method Detail
2435
Returns the time that the file denoted by this abstract pathname was last modified.
Returns:
A long value representing the time the file was last modified, measured in
milliseconds
isDirectory
public boolean isDirectory(String file)
openInputStream
public InputStream openInputStream(String file)
throws IOException
openOutputStream
public OutputStream openOutputStream(String file,
int offset)
throws IOException
Method Detail
2436
getAppHomePath
public String getAppHomePath()
This will return the application home directory. On some platforms such as Android
this path may be visible only to the application itself, other apps won't have
permission to access this path
Returns:
a writable directory that represent the application home directory
Method Detail
2437
Interface Externalizable
All Known Implementing Classes:
AccessToken, CachedData, CloudObject, Cookie
public interface
Similar to the Java SE externalizable interface this interface allows an object to declare itself as
externalizable for serialization. However, due to the lack of reflection and use of obfuscation these
objects must be registered with the Util class. Notice that all externalizable objects must have a
default public constructor.
Method Summary
Modifier
and Type
void
getObjectId()
The object id must be unique, it is used to identify the object when loaded even
when it is obfuscated.
String
getVersion()
Returns the version for the current persistance code, the version will be pased
to internalized thus allowing the internalize method to recognize classes
persisted in older revisions
int
void
Loads the object from the input stream and allows deserialization
Method Detail
getVersion
int getVersion()
Returns the version for the current persistance code, the version will be pased to
internalized thus allowing the internalize method to recognize classes persisted in
older revisions
Returns:
version number for the persistant code
externalize
void externalize(DataOutputStream out)
throws IOException
Allows us to store an object state, this method must be implemented in order to save
the state of an object
Parameters:
out - the stream into which the object must be serialized
Throws:
IOException - the method may throw an exception
internalize
void internalize(int version,
DataInputStream in)
throws IOException
Interface Externalizable
2438
The object id must be unique, it is used to identify the object when loaded even when
it is obfuscated.
Returns:
a unique id
Method Detail
2439
Class Cookie
java.lang.Object
com.codename1.io.Cookie
All Implemented Interfaces:
Externalizable
public class
extends Object
implements Externalizable
Field Summary
Modifier and Type Field and Description
static String
STORAGE_NAME
Constructor Summary
Constructor and Description
Cookie()
Method Summary
Modifier
and Type
static
void
void
String
getDomain()
long
getExpires()
String
getName()
getObjectId()
String
The object id must be unique, it is used to identify the object when loaded even
when it is obfuscated.
String
getPath()
String
getValue()
getVersion()
int
void
Class Cookie
Returns the version for the current persistance code, the version will be pased
to internalized thus allowing the internalize method to recognize classes
persisted in older revisions
internalize(int version, DataInputStream in)
Loads the object from the input stream and allows deserialization
static
boolean
isAutoStored()
boolean
isHttpOnly()
boolean
isSecure()
2440
setAutoStored(boolean autoStored)
void
setDomain(String domain)
void
setExpires(long expires)
void
setHttpOnly(boolean httpOnly)
void
setName(String name)
void
setPath(String path)
void
setSecure(boolean secure)
void
setValue(String value)
String
toString()
Field Detail
STORAGE_NAME
public static String STORAGE_NAME
Constructor Detail
Cookie
public Cookie()
Method Detail
getName
public String getName()
Returns:
the name
setName
public void setName(String name)
Parameters:
name
setSecure
public void setSecure(boolean secure)
isSecure
public boolean isSecure()
setHttpOnly
public void setHttpOnly(boolean httpOnly)
isHttpOnly
public boolean isHttpOnly()
setPath
public void setPath(String path)
Method Summary
2441
getValue
public String getValue()
Returns:
the value
setValue
public void setValue(String value)
Parameters:
value
getDomain
public String getDomain()
Returns:
the domain
setDomain
public void setDomain(String domain)
Parameters:
domain
getExpires
public long getExpires()
Returns:
the expires
setExpires
public void setExpires(long expires)
Parameters:
expires
getVersion
public int getVersion()
Returns the version for the current persistance code, the version will be pased to
internalized thus allowing the internalize method to recognize classes persisted in
older revisions
Specified by:
getVersion in interface Externalizable
Returns:
version number for the persistant code
externalize
public void externalize(DataOutputStream out)
throws IOException
Allows us to store an object state, this method must be implemented in order to save
the state of an object
Specified by:
externalize in interface Externalizable
Parameters:
out - the stream into which the object must be serialized
Throws:
IOException - the method may throw an exception
Method Detail
2442
Loads the object from the input stream and allows deserialization
Specified by:
internalize in interface Externalizable
Parameters:
version - the version the class returned during the externalization processs
in - the input stream used to load the class
Throws:
IOException - the method may throw an exception
getObjectId
public String getObjectId()
The object id must be unique, it is used to identify the object when loaded even when
it is obfuscated.
Specified by:
getObjectId in interface Externalizable
Returns:
a unique id
toString
public String toString()
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
setAutoStored
public static void setAutoStored(boolean autoStored)
Method Detail
2443
Class ConnectionRequest
java.lang.Object
com.codename1.io.ConnectionRequest
All Implemented Interfaces:
IOProgressListener
Direct Known Subclasses:
AdsService, CachedDataService, GZConnectionRequest, ImageDownloadService,
MultipartRequest, RSSService, TwitterRESTService
public class
extends Object
implements IOProgressListener
This class represents a connection object in the form of a request response typically common for
HTTP/HTTPS connections. A connection request is added to the NetworkManager for processing in a
queue on one of the network threads.
The sample code below fetches a page of data from the nestoria housing listing API.
You can see instructions on how to display the data in the InfiniteScrollAdapter class.
int pageNumber = 1;
java.util.List<Map<String, Object>> fetchPropertyData(String text) {
try {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("http://api.nestoria.co.uk/api");
r.addArgument("pretty", "0");
r.addArgument("action", "search_listings");
r.addArgument("encoding", "json");
r.addArgument("listing_type", "buy");
r.addArgument("page", "" + pageNumber);
pageNumber++;
r.addArgument("country", "uk");
r.addArgument("place_name", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getRes
Map<String, Object> response = (Map<String, Object>)result.get("response");
return (java.util.List<Map<String, Object>>)response.get("listings");
} catch(Exception err) {
Log.e(err);
return null;
}
}
Field Summary
Modifier
and Type
static byte
A critical priority request will "push" through the queue to the highest point
regardless of anything else and ignoring anything that is not in itself of critical
priority.
PRIORITY_HIGH
static byte
A high priority request is the second highest level, it will act exactly like a
critical priority with one difference.
PRIORITY_LOW
static byte
static byte
static byte
Class ConnectionRequest
Low priority requests are mostly background tasks that should still be
accomplished though
PRIORITY_NORMAL
2444
Summary
Method Summary
Modifier and Type
void
void
Deprecated.
use the version that accepts a string instead
addArgument(String key, String value)
void
void
void
void
void
void
protected void
protected void
protected void
protected String
boolean
static
Map<String,Object>
protected void
int
String
static String
static String
getDefaultUserAgent()
String
getDestinationFile()
Constructor Summary
2445
When set to a none null string saves the response to storage under
this file name
getDisposeOnCompletion()
Dialog
protected String
Returns the HTTP header field for the given connection, this method
is only guaranteed to work when invoked from the readHeaders
method.
getHeaderFieldNames(Object connection)
protected String[]
Returns the HTTP header field names for the given connection, this
method is only guaranteed to work when invoked from the
readHeaders method.
getHeaders(Object connection, String header)
protected String[]
String
byte
Returns the HTTP header field for the given connection, this method
is only guaranteed to work when invoked from the readHeaders
method.
getHttpMethod()
int
String
Returns the response code for this request, this is only relevant after
the request completed and might contain a temporary (e.g.
getResponseContentType()
byte[]
This method will return a valid value for only some of the responses
and only after the response was processed
getResposeCode()
int
Deprecated.
misspelled method name please use getResponseCode
getShowOnInit()
Dialog
This dialog will be shown when this request enters the network
queue
getSilentRetryCount()
int
int
String
getUrl()
String
getUserAgent()
getYield()
protected int
protected void
Handles a server response code that is not 200 and not a redirect
(unless redirect handling is disabled)
handleException(Exception err)
protected void
protected void
protected void
Method Summary
2446
hashCode()
protected boolean
protected void
protected String
void
boolean
isCookiesEnabled()
static boolean
isCookiesEnabledDefault()
static boolean
isDefaultFollowRedirects()
isDuplicateSupported()
boolean
boolean
boolean
isFollowRedirects()
protected boolean
isKilled()
isPausable()
protected boolean
Return true from this method if this connection can be paused and
resumed later on.
protected boolean
isPaused()
boolean
boolean
isPost()
Returns true for a post operation and false for a get operation
isReadRequest()
isReadResponseForErrors()
boolean
boolean
boolean
void
boolean
When set to true the read response code will happen even for error
codes such as 400 and 500
isRedirecting()
boolean
protected void
protected void
protected void
protected void
readResponse(InputStream input)
Method Summary
2447
removeAllArguments()
boolean
void
void
void
static void
void
setCookiesEnabled(boolean cookiesEnabled)
static void
setCookiesEnabledDefault(boolean aCookiesEnabledDefault)
static void
setDefaultFollowRedirects(boolean aDefaultFollowRedirects)
static void
setDefaultUserAgent(String aDefaultUserAgent)
setDestinationFile(String destinationFile)
void
When set to a none null string saves the response to file system
under this file name
setDestinationStorage(String destinationStorage)
void
When set to a none null string saves the response to storage under
this file name
setDisposeOnCompletion(Dialog disposeOnCompletion)
void
void
void
void
void
protected void
setKilled(boolean killed)
protected void
setPaused(boolean paused)
setPost(boolean post)
void
void
void
Set to true for a post operation and false for a get operation, this will
implicitly set the method to post/get respectively (which you can
change back by setting the method).
setPriority(byte priority)
void
Method Summary
When set to true the read response code will happen even for error
codes such as 400 and 500
2448
This dialog will be shown when this request enters the network
queue
void
setSilentRetryCount(int silentRetryCount)
void
setTimeout(int timeout)
void
void
setUrl(String url)
static void
setUseNativeCookieStore(boolean b)
void
setUserAgent(String userAgent)
void
setWriteRequest(boolean writeRequest)
shouldAutoCloseResponse()
protected boolean
protected boolean
protected boolean
protected boolean
protected void
Validates that the request has the required information before being
added to the queue e.g.
Field Detail
PRIORITY_CRITICAL
public static final byte PRIORITY_CRITICAL
A critical priority request will "push" through the queue to the highest point regardless
of anything else and ignoring anything that is not in itself of critical priority. A critical
priority will stop any none critical connection in progress
See Also:
Constant Field Values
PRIORITY_HIGH
public static final byte PRIORITY_HIGH
A high priority request is the second highest level, it will act exactly like a critical
priority with one difference. It doesn't block another incoming high priority request.
E.g. if a high priority request
See Also:
Constant Field Values
2449
Low priority requests are mostly background tasks that should still be accomplished
though
See Also:
Constant Field Values
PRIORITY_REDUNDANT
public static final byte PRIORITY_REDUNDANT
Constructor Detail
ConnectionRequest
public ConnectionRequest()
Method Detail
getCookieHeader
public static String getCookieHeader()
Returns:
the cookiesEnabledDefault
setCookiesEnabledDefault
public static void setCookiesEnabledDefault(boolean aCookiesEnabledDefault)
Parameters:
aCookiesEnabledDefault
isDefaultFollowRedirects
public static boolean isDefaultFollowRedirects()
Returns:
the defaultFollowRedirects
Field Detail
2450
Parameters:
aDefaultFollowRedirects
getResponseData
public byte[] getResponseData()
This method will return a valid value for only some of the responses and only after the
response was processed
Returns:
null or the actual data returned
setHttpMethod
public void setHttpMethod(String httpMethod)
Method Detail
2451
Returns the response code for this request, this is only relevant after the request
completed and might contain a temporary (e.g. redirect) code while the request is in
progress
Returns:
the response code
getResposeCode
public int getResposeCode()
This mimics the behavior of browsers that convert post operations to get operations
when redirecting a request.
Returns:
defaults to true, this case be modified by subclasses
readHeaders
protected void readHeaders(Object connection)
throws IOException
Allows reading the headers from the connection by calling the getHeader() method.
Parameters:
connection - used when invoking getHeader
Throws:
IOException - thrown on failure
readErrorCodeHeaders
protected void readErrorCodeHeaders(Object connection)
throws IOException
Allows reading the headers from the connection by calling the getHeader() method
when a response that isn't 200 OK is sent.
Parameters:
connection - used when invoking getHeader
Throws:
IOException - thrown on failure
getHeader
protected String getHeader(Object connection,
String header)
throws IOException
Returns the HTTP header field for the given connection, this method is only
guaranteed to work when invoked from the readHeaders method.
Parameters:
connection - the connection to the network
header - the name of the header
Returns:
the value of the header
Throws:
IOException - thrown on failure
Method Detail
2452
Returns the HTTP header field for the given connection, this method is only
guaranteed to work when invoked from the readHeaders method. Unlike the
getHeader method this version works when the same header name is declared
multiple times.
Parameters:
connection - the connection to the network
header - the name of the header
Returns:
the value of the header
Throws:
IOException - thrown on failure
getHeaderFieldNames
protected String[] getHeaderFieldNames(Object connection)
throws IOException
Returns the HTTP header field names for the given connection, this method is only
guaranteed to work when invoked from the readHeaders method.
Parameters:
connection - the connection to the network
Returns:
the names of the headers
Throws:
IOException - thrown on failure
getYield
protected int getYield()
Returns the amount of time to yield for other processes, this is an implicit method that
automatically generates values for lower priority connections
Returns:
yield duration or -1 for no yield
shouldAutoCloseResponse
protected boolean shouldAutoCloseResponse()
Method Detail
2453
Handles a server response code that is not 200 and not a redirect (unless redirect
handling is disabled)
Parameters:
code - the response code from the server
message - the response message from the server
retry
public void retry()
Callback for the server response with the input stream from the server. This method
is invoked on the network thread
Parameters:
input - the input stream containing the response
Throws:
IOException - when a read input occurs
postResponse
protected void postResponse()
A callback method that's invoked on the EDT after the readResponse() method has
finished, this is the place where developers should change their Codename One user
interface to avoid race conditions that might be triggered by modifications within
readResponse. Notice this method is only invoked on a successful response and will
not be invoked in case of a failure.
createRequestURL
protected String createRequestURL()
Invoked when send body is true, by default sends the request arguments based on
"POST" conventions
Parameters:
os - output stream of the body
Throws:
IOException
Method Detail
2454
Returns whether when writing a post body the platform expects something in the form
of string.getBytes("UTF-8") or new OutputStreamWriter(os, "UTF-8").
kill
public void kill()
Returns true if the request is paused or killed, developers should call this method
periodically to test whether they should quit the current IO operation immediately
Returns:
true if the request is paused or killed
isPausable
protected boolean isPausable()
Return true from this method if this connection can be paused and resumed later on.
A pausable network operation receives a "pause" invocation and is expected to stop
network operations as soon as possible. It will later on receive a resume() call and
optionally start downloading again.
Returns:
false by default.
pause
public boolean pause()
Invoked to pause this opeation, this method will only be invoked if isPausable()
returns true (its false by default). After this method is invoked current network
operations should be stoped as soon as possible for this class.
Returns:
This method can return false to indicate that there is no need to resume this
method since the operation has already been completed or made redundant
resume
public boolean resume()
Called when a previously paused operation now has the networking time to resume.
Assuming this method returns true, the network request will be resent to the server
and the operation can resume.
Returns:
This method can return false to indicate that there is no need to resume this
method since the operation has already been completed or made redundant
isPost
public boolean isPost()
Returns true for a post operation and false for a get operation
Returns:
the post
setPost
public void setPost(boolean post)
Set to true for a post operation and false for a get operation, this will implicitly set the
method to post/get respectively (which you can change back by setting the method).
The main importance of this method is how arguments are added to the request
(within the body or in the URL) and so it is important to invoke this method before any
argument was added.
Throws:
IllegalStateException - if invoked after an addArgument call
Method Detail
2455
Add an argument to the request response without encoding it, this is useful for
arguments which are already encoded
Parameters:
key - the key of the argument
value - the value for the argument
addArgument
public void addArgument(String key,
String value)
Add an argument to the request response as an array of elements, this will trigger
multiple request entries with the same key
Parameters:
key - the key of the argument
value - the value for the argument
addArguments
public void addArguments(String key,
String... value)
Add an argument to the request response as an array of elements, this will trigger
multiple request entries with the same key
Parameters:
key - the key of the argument
value - the value for the argument
getContentType
public String getContentType()
Returns:
the contentType
Method Detail
2456
Parameters:
contentType
isWriteRequest
public boolean isWriteRequest()
Returns:
the writeRequest
setWriteRequest
public void setWriteRequest(boolean writeRequest)
Parameters:
writeRequest
isReadRequest
public boolean isReadRequest()
Returns:
the readRequest
setReadRequest
public void setReadRequest(boolean readRequest)
Parameters:
readRequest
isPaused
protected boolean isPaused()
Returns:
the paused
setPaused
protected void setPaused(boolean paused)
Parameters:
paused
isKilled
protected boolean isKilled()
Returns:
the killed
setKilled
protected void setKilled(boolean killed)
Parameters:
killed
getPriority
public byte getPriority()
Method Detail
2457
getUserAgent
public String getUserAgent()
Returns:
the userAgent
setUserAgent
public void setUserAgent(String userAgent)
Parameters:
userAgent - the userAgent to set
getDefaultUserAgent
public static String getDefaultUserAgent()
Returns:
the defaultUserAgent
setDefaultUserAgent
public static void setDefaultUserAgent(String aDefaultUserAgent)
Parameters:
aDefaultUserAgent
isFollowRedirects
public boolean isFollowRedirects()
Returns:
the followRedirects
setFollowRedirects
public void setFollowRedirects(boolean followRedirects)
Parameters:
followRedirects
getTimeout
public int getTimeout()
Indicates the number of bytes that were read/written to/from the source stream
Specified by:
ioStreamUpdate in interface IOProgressListener
Parameters:
Method Detail
2458
getUrl
public String getUrl()
Returns:
the url
setUrl
public void setUrl(String url)
Parameters:
url - the url to set
addResponseListener
public void addResponseListener(ActionListener a)
Method Detail
2459
Indicates whether this connection request supports duplicate entries in the request
queue
Parameters:
duplicateSupported - the duplicateSupported to set
hashCode
public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of
hashtables such as those provided by java.util.Hashtable. The general contract of
hashCode is: Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application. If two objects are equal
according to the equals(Object) method, then calling the hashCode method on each
of the two objects must produce the same integer result. It is not required that if two
objects are unequal according to the equals(java.lang.Object) method, then calling
the hashCode method on each of the two objects must produce distinct integer
results. However, the programmer should be aware that producing distinct integer
results for unequal objects may improve the performance of hashtables. As much as
is reasonably practical, the hashCode method defined by class Object does return
distinct integers for distinct objects. (This is typically implemented by converting the
internal address of the object into an integer, but this implementation technique is not
required by the JavaTM programming language.)
Overrides:
hashCode in class Object
equals
public boolean equals(Object o)
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Object
validate
protected void validate()
Validates that the request has the required information before being added to the
queue e.g. checks if the URL is null. This method should throw an
IllegalStateException for a case where one of the values required for this connection
request is missing. This method can be overriden by subclasses to add additional
tests. It is usefull to do tests here since the exception will be thrown immediately
when invoking addToQueue which is more intuitive to debug than the alternative.
Method Detail
2460
A dialog that will be seamlessly disposed once the given request has been completed
Returns:
the disposeOnCompletion
setDisposeOnCompletion
public void setDisposeOnCompletion(Dialog disposeOnCompletion)
A dialog that will be seamlessly disposed once the given request has been completed
Parameters:
disposeOnCompletion - the disposeOnCompletion to set
getShowOnInit
public Dialog getShowOnInit()
This dialog will be shown when this request enters the network queue
Returns:
the showOnInit
setShowOnInit
public void setShowOnInit(Dialog showOnInit)
This dialog will be shown when this request enters the network queue
Parameters:
showOnInit - the showOnInit to set
getSilentRetryCount
public int getSilentRetryCount()
Indicates the number of times to silently retry a connection that failed before
prompting
Returns:
the silentRetryCount
setSilentRetryCount
public void setSilentRetryCount(int silentRetryCount)
Indicates the number of times to silently retry a connection that failed before
prompting
Parameters:
silentRetryCount - the silentRetryCount to set
isFailSilently
public boolean isFailSilently()
Method Detail
2461
When set to true the read response code will happen even for error codes such as
400 and 500
Returns:
the readResponseForErrors
setReadResponseForErrors
public void setReadResponseForErrors(boolean readResponseForErrors)
When set to true the read response code will happen even for error codes such as
400 and 500
Parameters:
readResponseForErrors - the readResponseForErrors to set
getResponseContentType
public String getResponseContentType()
When set to a none null string saves the response to file system under this file name
Returns:
the destinationFile
setDestinationFile
public void setDestinationFile(String destinationFile)
When set to a none null string saves the response to file system under this file name
Parameters:
destinationFile - the destinationFile to set
getDestinationStorage
public String getDestinationStorage()
When set to a none null string saves the response to storage under this file name
Returns:
the destinationStorage
setDestinationStorage
public void setDestinationStorage(String destinationStorage)
When set to a none null string saves the response to storage under this file name
Parameters:
destinationStorage - the destinationStorage to set
isCookiesEnabled
public boolean isCookiesEnabled()
Returns:
the cookiesEnabled
Method Detail
2462
Parameters:
cookiesEnabled - the cookiesEnabled to set
setChunkedStreamingMode
public void setChunkedStreamingMode(int chunklen)
This method is used to enable streaming of a HTTP request body without internal
buffering, when the content length is not known in advance. In this mode, chunked
transfer encoding is used to send the request body. Note, not all HTTP servers
support this mode. This mode is supported on Android and the Desktop ports.
Parameters:
chunklen - The number of bytes to write in each chunk. If chunklen is zero a
default value will be used.
fetchJSON
public static Map<String,Object> fetchJSON(String url)
throws IOException
Method Detail
2463
Class CharArrayReader
java.lang.Object
java.io.Reader
com.codename1.io.CharArrayReader
All Implemented Interfaces:
AutoCloseable
public class
extends Reader
Field Summary
Modifier and Type
protected char[]
protected int
protected int
protected int
Constructor Summary
Constructor and Description
CharArrayReader(char[] buf)
Method Summary
Modifier and
Type
void
void
boolean
Indicates whether this reader supports the mark() and reset() methods.
read()
int
Class CharArrayReader
Reads a single character from this reader and returns it as an integer with
the two higher-order bytes set to 0.
2464
int
boolean
and stores
ready()
void
long
Field Detail
buf
protected char[] buf
Constructor Detail
CharArrayReader
public CharArrayReader(char[] buf)
Constructs a CharArrayReader on the char array buf. The size of the reader is set to
the length of the buffer and the object to read from is set to buf.
Parameters:
buf - the char array from which to read.
CharArrayReader
public CharArrayReader(char[] buf,
int offset,
int length)
Constructs a CharArrayReader on the char array buf. The size of the reader is set to
length and the start position from which to read the buffer is set to offset.
Parameters:
buf - the char array from which to read.
offset - the index of the first character in buf to read.
Method Summary
2465
Throws:
IllegalArgumentException greater than the size of buf .
Method Detail
close
public void close()
This method closes this CharArrayReader. Once it is closed, you can no longer read
from it. Only the first invocation of this method has any effect.
Specified by:
close in interface AutoCloseable
Specified by:
close in class Reader
mark
public void mark(int readLimit)
throws IOException
Sets a mark position in this reader. The parameter readLimit is ignored for
CharArrayReaders. Calling reset() will reposition the reader back to the marked
position provided the mark has not been invalidated.
Overrides:
mark in class Reader
Parameters:
readLimit - ignored for CharArrayReaders.
Throws:
IOException - if this reader is closed.
markSupported
public boolean markSupported()
Indicates whether this reader supports the mark() and reset() methods.
Overrides:
markSupported in class Reader
Returns:
true for CharArrayReader.
See Also:
mark(int), reset()
read
public int read()
throws IOException
Reads a single character from this reader and returns it as an integer with the two
higher-order bytes set to 0. Returns -1 if no more characters are available from this
reader.
Overrides:
read in class Reader
Returns:
the character read as an int or -1 if the end of the reader has been reached.
Throws:
IOException - if this reader is closed.
read
public int read(char[] buffer,
int offset,
int len)
throws IOException
Reads at most count characters from this CharArrayReader and stores them at
offset in the character array buf. Returns the number of characters actually read or
-1 if the end of reader was encountered.
Constructor Detail
2466
in class Reader
Parameters:
buffer
offset
reader.
len - the maximum number of characters to read.
Returns:
number of characters read or -1 if the end of the reader has been reached.
Throws:
IndexOutOfBoundsException - if offset < 0 or len < 0, or if offset + len is
bigger than the size of buffer.
IOException - if this reader is closed.
ready
public boolean ready()
throws IOException
Indicates whether this reader is ready to be read without blocking. Returns true if the
next read will not block. Returns false if this reader may or may not block when read
is called. The implementation in CharArrayReader always returns true even when it
has been closed.
Overrides:
ready in class Reader
Returns:
true if this reader will not block when read is called, false if unknown or
blocking will occur.
Throws:
IOException - if this reader is closed.
reset
public void reset()
throws IOException
Resets this reader's position to the last mark() location. Invocations of read() and
skip() will occur from this new location. If this reader has not been marked, it is reset
to the beginning of the string.
Overrides:
reset in class Reader
Throws:
IOException - if this reader is closed.
skip
public long skip(long n)
throws IOException
Skips count number of characters in this reader. Subsequent read()s will not return
these characters unless reset() is used. This method does nothing and returns 0 if n
is negative.
Overrides:
skip in class Reader
Parameters:
n - the number of characters to skip.
Returns:
the number of characters actually skipped.
Throws:
IOException - if this reader is closed.
Method Detail
2467
Class CacheMap
java.lang.Object
com.codename1.io.CacheMap
public class
extends Object
A cache map is essentially a hashtable that indexes entries based on age and is limited to a fixed
size. Hence when an entry is placed into the cache map and the cache size needs to increase, the
least referenced entry is removed. A cache hit is made both on fetching and putting, hence frequently
fetched elements will never be removed from a sufficiently large cache. Cache can work purely in
memory or swap data into storage based on user definitions. Notice that this class isn't threadsafe.
Constructor Summary
Constructor and Description
CacheMap()
Default constructor
CacheMap(String prefix)
Method Summary
Modifier
and Type
void
void
void
void
Object
String
int
Indicates the size of the memory cache after which the cache won't grow further
Size is indicated by number of elements stored and not by KB or similar
benchmark!
getKeysInCache()
Vector
Returns the keys for all the objects currently in cache, this is useful to traverse
all the objects and refresh them without actually deleting the cache and fetching
them from scratch.
Important this vector is a copy of a current state, keys might not exist anymore
or might change, others might be added in the interim.
getStorageCacheSize()
int
boolean
Class CacheMap
Indicates the size of the storage cache after which the cache won't grow further
Size is indicated by number of elements stored and not by KB or similar
benchmark!
isAlwaysStore()
2468
void
When set to true indicates that all entries should be persisted to storage for a
constantly persisting cache
void
setCachePrefix(String cachePrefix)
void
Indicates the size of the memory cache after which the cache won't grow further
Size is indicated by number of elements stored and not by KB or similar
benchmark!
void
setStorageCacheSize(int storageCacheSize)
Indicates the size of the storage cache after which the cache won't grow further
Size is indicated by number of elements stored and not by KB or similar
benchmark!
void
Constructor Detail
CacheMap
public CacheMap()
Default constructor
CacheMap
public CacheMap(String prefix)
Method Detail
getCacheSize
public int getCacheSize()
Indicates the size of the memory cache after which the cache won't grow further Size
is indicated by number of elements stored and not by KB or similar benchmark!
Returns:
the cacheSize
setCacheSize
public void setCacheSize(int cacheSize)
Indicates the size of the memory cache after which the cache won't grow further Size
is indicated by number of elements stored and not by KB or similar benchmark!
Parameters:
cacheSize - the cacheSize to set
put
public void put(Object key,
Object value)
Method Summary
2469
Returns the keys for all the objects currently in cache, this is useful to traverse all the
objects and refresh them without actually deleting the cache and fetching them from
scratch.
Important this vector is a copy of a current state, keys might not exist anymore or
might change, others might be added in the interim.
Returns:
a vector containing a snapshot of the current elements within the cache.
clearStorageCache
public void clearStorageCache()
Indicates the size of the storage cache after which the cache won't grow further Size
is indicated by number of elements stored and not by KB or similar benchmark!
Returns:
the storageCacheSize
setStorageCacheSize
public void setStorageCacheSize(int storageCacheSize)
Indicates the size of the storage cache after which the cache won't grow further Size
is indicated by number of elements stored and not by KB or similar benchmark!
Parameters:
storageCacheSize - the storageCacheSize to set
getCachePrefix
public String getCachePrefix()
Method Detail
2470
When set to true indicates that all entries should be persisted to storage for a
constantly persisting cache
Returns:
the alwaysStore
setAlwaysStore
public void setAlwaysStore(boolean alwaysStore)
When set to true indicates that all entries should be persisted to storage for a
constantly persisting cache
Parameters:
alwaysStore - the alwaysStore to set
Method Detail
2471
Class CSVParser
java.lang.Object
com.codename1.io.CSVParser
public class
extends Object
Simple CSV parser very useful for importing data into applications quickly from a CSV source
Constructor Summary
Constructor and Description
CSVParser()
Method Summary
Modifier and
Type
String[][]
Parses input from the given stream and returns the tokens broken into
rows and columns
parse(InputStream r, String encoding)
String[][]
Parses input from the given stream and returns the tokens broken into
rows and columns
parse(Reader r)
String[][]
Parses input from the given reader and returns the tokens broken into
rows and columns
Constructor Detail
CSVParser
public CSVParser()
Class CSVParser
2472
Detail
parse
public String[][] parse(InputStream r)
throws IOException
Parses input from the given stream and returns the tokens broken into rows and
columns
Parameters:
r - the input stream
Returns:
array of rows and columns
Throws:
IOException
parse
public String[][] parse(InputStream r,
String encoding)
throws IOException
Parses input from the given stream and returns the tokens broken into rows and
columns
Parameters:
r - the input stream
encoding - the encoding of the stream
Returns:
array of rows and columns
Throws:
IOException
parse
public String[][] parse(Reader r)
throws IOException
Parses input from the given reader and returns the tokens broken into rows and
columns
Parameters:
r - the reader stream
Returns:
array of rows and columns
Throws:
IOException
Method Detail
2473
Class BufferedOutputStream
java.lang.Object
java.io.OutputStream
com.codename1.io.BufferedOutputStream
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
TarOutputStream
public class
extends OutputStream
Based on the buffered output stream from the JDK with some minor tweaks to allow external classes
to monitor stream status and progress.
Field Summary
Modifier and Type
protected byte[]
protected int
Constructor Summary
Constructor and Description
BufferedOutputStream(OutputStream out)
Creates a new buffered output stream to write data to the specified underlying output
stream.
BufferedOutputStream(OutputStream out, int size)
Creates a new buffered output stream to write data to the specified underlying output stream
with the specified buffer size.
BufferedOutputStream(OutputStream out, int size, String name)
Creates a new buffered output stream to write data to the specified underlying output stream
with the specified buffer size.
BufferedOutputStream(OutputStream out, String name)
Creates a new buffered output stream to write data to the specified underlying output
stream.
Method Summary
Modifier
and Type
void
void
void
Object
Closes this output stream and releases any system resources associated with
the stream.
flush()
If applicable this member represents the connection object for the stream
Class BufferedOutputStream
2474
getDefaultBufferSize()
long
String
int
void
If applicable this member represents the connection object for the stream
static void
setDefaultBufferSize(int aDefaultBufferSize)
void
void
void
void
Field Detail
buf
protected byte[] buf
The number of valid bytes in the buffer. This value is always in the range 0 through
buf.length; elements buf[0] through buf[count-1] contain valid byte data.
Constructor Detail
BufferedOutputStream
public BufferedOutputStream(OutputStream out)
Creates a new buffered output stream to write data to the specified underlying output
stream.
Parameters:
out - the underlying output stream.
BufferedOutputStream
public BufferedOutputStream(OutputStream out,
String name)
Creates a new buffered output stream to write data to the specified underlying output
stream.
Parameters:
out - the underlying output stream.
name - the name of the stream used for debugging/logging purposes
Method Summary
2475
Creates a new buffered output stream to write data to the specified underlying output
stream with the specified buffer size.
Parameters:
out - the underlying output stream.
size - the buffer size.
Throws:
IllegalArgumentException - if size <= 0.
BufferedOutputStream
public BufferedOutputStream(OutputStream out,
int size,
String name)
Creates a new buffered output stream to write data to the specified underlying output
stream with the specified buffer size.
Parameters:
out - the underlying output stream.
size - the buffer size.
name - the name of the stream used for debugging/logging purposes
Throws:
IllegalArgumentException - if size <= 0.
Method Detail
getName
public String getName()
write
public void write(int b)
throws IOException
Writes len bytes from the specified byte array starting at offset off to this buffered
output stream.
Constructor Detail
2476
Flushes this buffered output stream. This forces any buffered output bytes to be
written out to the underlying output stream.
Overrides:
flush in class OutputStream
Throws:
IOException - if an I/O error occurs.
getLastActivityTime
public long getLastActivityTime()
Method Detail
2477
Closes this output stream and releases any system resources associated with the
stream.
The close method of FilterOutputStream calls its flush method, and then calls the
close method of its underlying output stream.
Specified by:
close
in interface AutoCloseable
Overrides:
close
in class OutputStream
Throws:
IOException
getConnection
public Object getConnection()
If applicable this member represents the connection object for the stream
Returns:
the connection
setConnection
public void setConnection(Object connection)
If applicable this member represents the connection object for the stream
Parameters:
connection - the connection to set
Method Detail
2478
Class BufferedInputStream
java.lang.Object
java.io.InputStream
com.codename1.io.BufferedInputStream
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
TarInputStream
public class
extends InputStream
Based on the buffered input stream from the JDK with some minor tweaks to allow external classes to
monitor stream status and progress.
Constructor Summary
Constructor and Description
BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves
Method Summary
Modifier and
Type
int
Returns an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next invocation of a method for
this input stream.
close()
void
Object
static int
InputStream
long
String
int
Class BufferedInputStream
Closes this input stream and releases any system resources associated with
the stream.
getConnection()
If applicable this member represents the connection object for the stream
getDefaultBufferSize()
Returns the total amount of bytes read from this stream so far
2479
Allows setting a yield duration for this stream which is useful for background
operations to release CPU
boolean
isDisableBuffering()
boolean
isPrintInput()
Prints out all the data that passes through this stream to the console.
mark(int readlimit)
void
boolean
markSupported()
Tests if this input stream supports the mark and reset methods.
read()
int
Reads some number of bytes from the input stream and stores them into the
buffer array b.
int
Reads bytes from this byte-input stream into the specified byte array, starting
at the given offset.
int
reset()
void
void
If applicable this member represents the connection object for the stream
static void
void
setDefaultBufferSize(int aDefaultBufferSize)
void
Prints out all the data that passes through this stream to the console.
setProgressListener(IOProgressListener progressListener)
void
Allows setting a yield duration for this stream which is useful for background
operations to release CPU
void
skip(long n)
long
void
Stop reading from the stream, invoking this will cause the read() to return -1
Constructor Detail
BufferedInputStream
public BufferedInputStream(InputStream in)
Creates a BufferedInputStream and saves its argument, the input stream in, for later
use. An internal buffer array is created and stored in buf.
Parameters:
in - the underlying input stream.
BufferedInputStream
public BufferedInputStream(InputStream in,
String name)
Creates a BufferedInputStream and saves its argument, the input stream in, for later
use. An internal buffer array is created and stored in buf.
Parameters:
Method Summary
2480
input stream.
the stream
BufferedInputStream
public BufferedInputStream(InputStream in,
int size)
Creates a BufferedInputStream with the specified buffer size, and saves its
argument, the input stream in, for later use. An internal buffer array of length size is
created and stored in buf.
Parameters:
in - the underlying input stream.
size - the buffer size.
Throws:
IllegalArgumentException - if size <= 0.
BufferedInputStream
public BufferedInputStream(InputStream in,
int size,
String name)
Creates a BufferedInputStream with the specified buffer size, and saves its
argument, the input stream in, for later use. An internal buffer array of length size is
created and stored in buf.
Parameters:
in - the underlying input stream.
size - the buffer size.
name - the name of the stream
Throws:
IllegalArgumentException - if size <= 0.
Method Detail
getName
public String getName()
Constructor Detail
2481
Returns an estimate of the number of bytes that can be read (or skipped over) from
this input stream without blocking by the next invocation of a method for this input
stream. The next invocation might be the same thread or another thread. A single
read or skip of this many bytes will not block, but may read or skip fewer bytes.
This method returns the sum of the number of bytes remaining to be read in the
buffer (count - pos) and the result of calling the in.available().
Overrides:
available in class InputStream
Returns:
an estimate of the number of bytes that can be read (or skipped over) from
this input stream without blocking.
Throws:
IOException - if this input stream has been closed by invoking its close()
method, or an I/O error occurs.
mark
public void mark(int readlimit)
Method Detail
2482
in class InputStream
Parameters:
- the maximum limit of bytes that can be read before the mark
position becomes invalid.
readlimit
reset
public void reset()
throws IOException
in class InputStream
Throws:
- if this stream has not been marked or, if the mark has been
invalidated, or the stream has been closed by invoking its close() method, or
an I/O error occurs.
markSupported
IOException
Tests if this input stream supports the mark and reset methods. The markSupported
method of BufferedInputStream returns true.
Overrides:
markSupported in class InputStream
Returns:
a boolean indicating if this stream type supports the mark and reset methods.
See Also:
InputStream.mark(int), InputStream.reset()
close
public void close()
throws IOException
Closes this input stream and releases any system resources associated with the
stream. Once the stream has been closed, further read(), available(), reset(), or skip()
invocations will throw an IOException. Closing a previously closed stream has no
effect.
Specified by:
close in interface AutoCloseable
Overrides:
close in class InputStream
Throws:
IOException - if an I/O error occurs.
getLastActivityTime
public long getLastActivityTime()
Returns the total amount of bytes read from this stream so far
Returns:
the total amount of bytes read from this stream so far
setProgressListener
public void setProgressListener(IOProgressListener progressListener)
Method Detail
2483
read
public int read(byte[] b)
throws IOException
Reads some number of bytes from the input stream and stores them into the buffer
array b. The number of bytes actually read is returned as an integer. This method
blocks until input data is available, end of file is detected, or an exception is thrown. If
b is null, a NullPointerException is thrown. If the length of b is zero, then no bytes are
read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no
byte is available because the stream is at end of file, the value -1 is returned;
otherwise, at least one byte is read and stored into b. The first byte read is stored into
element b[0], the next one into b[1], and so on. The number of bytes read is, at most,
equal to the length of b. Let k be the number of bytes actually read; these bytes will
be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1]
unaffected. If the first byte cannot be read for any reason other than end of file, then
an IOException is thrown. In particular, an IOException is thrown if the input stream
has been closed. The read(b) method for class InputStream has the same effect as:
read(b, 0, b.length)
Overrides:
read in class InputStream
Throws:
IOException
getDefaultBufferSize
public static int getDefaultBufferSize()
If applicable this member represents the connection object for the stream
Returns:
the connection
setConnection
public void setConnection(Object connection)
If applicable this member represents the connection object for the stream
Parameters:
connection - the connection to set
isDisableBuffering
public boolean isDisableBuffering()
Returns:
the disableBuffering
setDisableBuffering
public void setDisableBuffering(boolean disableBuffering)
Parameters:
disableBuffering
Method Detail
2484
Prints out all the data that passes through this stream to the console. This is a very
useful debugging tool.
Returns:
the printInput
setPrintInput
public void setPrintInput(boolean printInput)
Prints out all the data that passes through this stream to the console. This is a very
useful debugging tool.
Parameters:
printInput - the printInput to set
getYield
public int getYield()
Allows setting a yield duration for this stream which is useful for background
operations to release CPU
Returns:
the yield
setYield
public void setYield(int yield)
Allows setting a yield duration for this stream which is useful for background
operations to release CPU
Parameters:
yield - the yield to set
stop
public void stop()
Stop reading from the stream, invoking this will cause the read() to return -1
Method Detail
2485
Class AccessToken
java.lang.Object
com.codename1.io.AccessToken
All Implemented Interfaces:
Externalizable
public class
extends Object
implements Externalizable
Constructor Summary
Constructor and Description
AccessToken(String token, String expires)
Method Summary
Modifier
and Type
void
String
getExpires()
Simple getter
getObjectId()
String
String
The object id must be unique, it is used to identify the object when loaded even
when it is obfuscated.
getToken()
Simple getter
getVersion()
Returns the version for the current persistance code, the version will be pased
to internalized thus allowing the internalize method to recognize classes
persisted in older revisions
int
void
Loads the object from the input stream and allows deserialization
Constructor Detail
AccessToken
public AccessToken(String token,
String expires)
Class AccessToken
2486
expires date
Method Detail
getToken
public String getToken()
Simple getter
Returns:
the token string
getExpires
public String getExpires()
Simple getter
Returns:
the expires date
getVersion
public int getVersion()
Constructor Detail
2487
Method Detail
2488
Class LikeButton
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.Button
com.codename1.facebook.ui.LikeButton
All Implemented Interfaces:
Animation, ActionListener, StyleListener
public class
extends Button
implements ActionListener
Generic "Like" button that enables us to submit a like to facebook, to get the post id required for the
like functionality you will need to use a tool such as:
https://developers.facebook.com/tools/explorer/?method=GET&path=me%2Fposts You can ask it to
list your posts and then seek the correct id within the returned JSON
Field Summary
Constructor Summary
Constructor and Description
LikeButton()
Default constructor
LikeButton(String postId)
Method Summary
Modifier
and
Type
void
String
getAppId()
String
getClientSecret()
String[] getPermissions()
String
getPostId()
String[] getPropertyNames()
Class LikeButton
2489
A component may expose mutable property names for a UI designer to manipulate, this AP
usage internally by the GUI builder code
getPropertyTypeNames()
String[]
Class[]
Object
This method is here to workaround an XMLVM array type bug where property types aren't id
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListMod
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI builder
String
getRedirectURI()
void
setAppId(String appId)
void
setClientSecret(String clientSecret)
void
setPermissions(String[] permissions)
void
setPostId(String postId)
String
void
Sets a new value to the given property, returns an error message if failed and null if success
setRedirectURI(String redirectURI)
Method Summary
2490
Constructor Detail
LikeButton
public LikeButton(String postId)
Default constructor
Method Detail
actionPerformed
public void actionPerformed(ActionEvent evt)
Returns:
the postId
2491
Parameters:
postId - the postId to set
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Label
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Label
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Label
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Label
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
2492
Returns:
the appId
setAppId
public void setAppId(String appId)
Parameters:
appId - the appId to set
getRedirectURI
public String getRedirectURI()
Returns:
the redirectURI
setRedirectURI
public void setRedirectURI(String redirectURI)
Parameters:
redirectURI
getClientSecret
public String getClientSecret()
Returns:
the clientSecret
setClientSecret
public void setClientSecret(String clientSecret)
Parameters:
clientSecret
getPermissions
public String[] getPermissions()
Returns:
the permissions
setPermissions
public void setPermissions(String[] permissions)
Parameters:
permissions
Method Detail
2493
Class User
java.lang.Object
com.codename1.facebook.FBObject
com.codename1.facebook.User
public class
extends FBObject
Constructor Summary
Constructor and Description
User()
Empty Contructor
User(Hashtable props)
Method Summary
Modifier and Type
void
String
getAbout()
String
getBio()
String
getBirthday()
String
getEmail()
String
getFirst_name()
String
getGender()
FBObject
getHometown()
String
getLast_name()
String
getLast_updated()
String
getLink()
String
getLocale()
FBObject
getLocation()
String
getQuotes()
String
getRelationship_status()
long
getTimezone()
String
String
getUsername()
Class User
2494
Constructor Detail
User
public User()
Empty Contructor
User
public User(Hashtable props)
Method Detail
getFirst_name
public String getFirst_name()
Returns:
the first_name
getLast_name
public String getLast_name()
Returns:
the last_name
getLink
public String getLink()
Returns:
the link
getAbout
public String getAbout()
Returns:
the about
getBirthday
public String getBirthday()
Returns:
the birthday
getEmail
public String getEmail()
Returns:
the email
getWebsite
public String getWebsite()
Returns:
the website
getBio
public String getBio()
Returns:
2495
Returns:
the quotes
getGender
public String getGender()
Returns:
the gender
getRelationship_status
public String getRelationship_status()
Returns:
the relationship_status
getTimezone
public long getTimezone()
Returns:
the timezone
getLast_updated
public String getLast_updated()
Returns:
the last_updated
getLocale
public String getLocale()
Returns:
the locale
getUsername
public String getUsername()
Method Detail
2496
Class Post
java.lang.Object
com.codename1.facebook.FBObject
com.codename1.facebook.Post
public class
extends FBObject
Constructor Summary
Constructor and Description
Post()
Empty Contructor
Post(Hashtable props)
Method Summary
Modifier and Type
void
String
String
User
String
String
String
String
String
String
Vector
String
String
Class Post
Deprecated.
use getName() instead
getLinkUrl()
2497
Constructor Detail
Post
public Post()
Empty Contructor
Post
public Post(Hashtable props)
Method Detail
getFrom
public User getFrom()
2498
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
copy
public void copy(Hashtable props)
Method Detail
2499
Class Photo
java.lang.Object
com.codename1.facebook.FBObject
com.codename1.facebook.Photo
public class
extends FBObject
Constructor Summary
Constructor and Description
Photo()
Empty Contructor
Photo(Hashtable props)
Method Summary
Modifier and Type
void
Vector
String
getComments()
Gets the comments on this Photos, where each entry is a Post Object
getCreated_time()
Get created_time
getFrom()
User
Get from
getHeight()
int
Get height
String
Vector
String
String
getIconUrl()
Get iconUrl
getImages()
Get link
getPictureUrl()
Get pictureUrl
getPosition()
int
Get position
String
String
getSourceUrl()
Get sourceUrl
getUpdated_time()
Get updated_time
getWidth()
int
Get width
Class Photo
2500
Constructor Detail
Photo
public Photo()
Empty Contructor
Photo
public Photo(Hashtable props)
Method Detail
getCreated_time
public String getCreated_time()
Get created_time
Returns:
created_time
getFrom
public User getFrom()
Get from
Returns:
from
getHeight
public int getHeight()
Get height
Returns:
height
getIconUrl
public String getIconUrl()
Get iconUrl
Returns:
iconUrl
getLink
public String getLink()
Get link
Returns:
link
getPictureUrl
public String getPictureUrl()
Get pictureUrl
Returns:
pictureUrl
2501
Get position
Returns:
position
getSourceUrl
public String getSourceUrl()
Get sourceUrl
Returns:
sourceUrl
getUpdated_time
public String getUpdated_time()
Get updated_time
Returns:
updated_time
getWidth
public int getWidth()
Get width
Returns:
width
getImages
public Vector getImages()
Gets the comments on this Photos, where each entry is a Post Object
Returns:
a Vector of Post Objects
copy
public void copy(Hashtable props)
Method Detail
2502
Class Page
java.lang.Object
com.codename1.facebook.FBObject
com.codename1.facebook.Page
public class
extends FBObject
Constructor Summary
Constructor and Description
Page()
Empty Contructor
Page(Hashtable props)
Method Summary
Modifier and Type
void
String
String
String
String
String
getAbout()
Simple Getter
getCategory()
Simple Getter
getCoverId()
Simple Getter
getCoverLink()
Simple Getter
getFounded()
Simple Getter
getLikesCount()
int
Simple Getter
String
String
String
getLink()
Simple Getter
getUsername()
Simple Getter
getWebsite()
Simple Getter
Class Page
2503
Detail
Page
public Page()
Empty Contructor
Page
public Page(Hashtable props)
Method Detail
getAbout
public String getAbout()
Simple Getter
getCategory
public String getCategory()
Simple Getter
getCoverId
public String getCoverId()
Simple Getter
getCoverLink
public String getCoverLink()
Simple Getter
getFounded
public String getFounded()
Simple Getter
getLikesCount
public int getLikesCount()
Simple Getter
getLink
public String getLink()
Simple Getter
getUsername
public String getUsername()
Simple Getter
getWebsite
public String getWebsite()
Simple Getter
copy
public void copy(Hashtable props)
Constructor Detail
2504
Parameters:
props
Method Detail
2505
Class FaceBookAccess
java.lang.Object
com.codename1.facebook.FaceBookAccess
public class
extends Object
Method Summary
Modifier and Type
void
static void
void
Component
void
void
Some simple queries for public data can work just fine with anonymous
login without requiring the whole OAuth process, they still need a
facebook application though
cleanTempStorage()
createOAuth()
createObjectsModel(DefaultListModel hashtablesModel,
Class fbObjectClass)
static
DefaultListModel
void
Album
void
Gets a Album from a albumId This is a sync method it will block until a
response it returned
getAlbumPhotos(String albumId, DefaultListModel photos,
int offset, int limit, ActionListener callback)
getApiVersion()
Returns the api version used, if empty the non version-ed is used
getFaceBookObject(String faceBookId, ActionListener callback)
void
void
void
Class FaceBookAccess
This method returns immediately and will call the callback when it
returns with the FaceBook Object data.
getFaceBookObject(String faceBookId, ActionListener callback,
boolean needToken, boolean async)
This method returns immediately and will call the callback when it
returns with the FaceBook Object data.
getFaceBookObjectItems(String faceBookId,
String itemsConnection, DefaultListModel feed,
2506
void
void
Gets the user news feed, the data is being stored in the given
DefaultListModel.
getNewsFeed(String userId, DefaultListModel feed, int limit,
ActionListener callback)
Gets the user news feed, the data is being stored in the given
DefaultListModel.
getPage(String pageId)
Page
Photo
void
void
Gets a Photo from a photoId This is a sync method it will block until a
response it returned
getPhoto(String photoId, Photo photo, ActionListener callback)
void
Gets the picture of the given facebook object id and stores it in the
given List in the offset index This assumes the GenericListCellRenderer
style of list which relies on a hashtable based model approach.
getPicture(String id, Label label, Dimension toScale,
boolean tempStorage)
Post
void
void
Gets a Post from a postId This is a sync method it will block until a
response it returned
getPost(String postId, Post post, ActionListener callback)
Returns the Facebook authorization token that can be used for API
access
getUser(String userId)
User
void
void
Gets a User from a user id This is a sync method it will block until a
response it returned
getUser(String userId, User user, ActionListener callback)
Method Summary
2507
void
Gets the user notifications (this method uses the legacy rest api see
http://developers.facebook.com/docs/reference/rest/)
void
void
void
void
void
Gets users requested details ((this method uses the legacy rest api see
http://developers.facebook.com/docs/reference/rest/))
getWallFeed(String userId, DefaultListModel feed,
ActionListener callback)
Gets the user wall feed, the data is being stored in the given
DefaultListModel.
getWallFeed(String userId, DefaultListModel feed, int limit,
ActionListener callback)
Gets the user wall feed, the data is being stored in the given
DefaultListModel.
getWallPosts(String userId, DefaultListModel feed,
ActionListener callback)
Gets the user wall feed, the data is being stored in the given
DefaultListModel.
getWallPosts(String userId, DefaultListModel feed, int limit,
ActionListener callback)
Gets the user wall posts, the data is being stored in the given
DefaultListModel.
isAuthenticated()
boolean
void
static void
void
void
void
postLike(String postId)
removeResponseCodeListener(ActionListener a)
void
Method Summary
2508
Sets the Facebook api version being used, by default the api calls the
non version-ed version of the API.
setClientId(String clientId)
static void
static void
static void
void
static void
static void
Sets the token to the FaceBookAccess class, this is useful if the token
has not yet expired, get the expiration of the token with
Oauth2.getExpires()
showAuthentication(ActionListener al)
void
Method Detail
getInstance
public static FaceBookAccess getInstance()
createAuthComponent
public Component createAuthComponent(ActionListener al)
This method creates a component which can authenticate. You will receive either the
authentication key or an Exception object within the ActionListener callback method.
Parameters:
al - a listener that will receive at its source either a token for the service or an
exception in case of a failure
Returns:
a component that should be displayed to the user in order to perform the
authentication
showAuthentication
public void showAuthentication(ActionListener al)
2509
This method returns true if the user is authenticated to the facebook service.
Returns:
true if authenticated
setProgress
public void setProgress(Slider slider)
This method returns immediately and will call the callback when it returns with the
FaceBook Object data.
Parameters:
faceBookId - the object id that we would like to query
callback - the callback that should be updated when the data arrives
Throws:
IOException
getFaceBookObject
public void getFaceBookObject(String faceBookId,
ActionListener callback,
boolean needToken,
boolean async)
throws IOException
This method returns immediately and will call the callback when it returns with the
FaceBook Object data.
Parameters:
faceBookId - the object id that we would like to query
callback - the callback that should be updated when the data arrives
needToken - if true authentication is being checked
Throws:
IOException
getFaceBookObjectItems
public void getFaceBookObjectItems(String faceBookId,
String itemsConnection,
DefaultListModel feed,
Hashtable params,
ActionListener callback)
throws IOException
getUser
public void getUser(String userId,
User user,
ActionListener callback)
throws IOException
Method Detail
2510
getUser
public User getUser(String userId)
throws IOException
Gets a User from a user id This is a sync method it will block until a response it
returned
Parameters:
userId - the user id or null to get details on the authenticated user
Returns:
the User requested
Throws:
IOException
getPage
public Page getPage(String pageId)
throws IOException
Gets a Page from a pageId/name This is a sync method it will block until a response
it returned
Parameters:
pageId - the pageId
Returns:
the Page requested
Throws:
IOException
getPost
public void getPost(String postId,
Post post,
ActionListener callback)
throws IOException
getPost
public Post getPost(String postId,
boolean needAuth)
throws IOException
Gets a Post from a postId This is a sync method it will block until a response it
returned
Parameters:
postId - the post id
needAuth - if this object is public needAuth can be false and no authentication
will be performed
Returns:
the Post requested
Throws:
IOException
getPhoto
public void getPhoto(String photoId,
Photo photo,
ActionListener callback)
throws IOException
Method Detail
2511
getPhoto
public Photo getPhoto(String photoId,
boolean needAuth)
throws IOException
Gets a Photo from a photoId This is a sync method it will block until a response it
returned
Parameters:
the - photoId
needAuth - if this object is public needAuth can be false and no authentication
will be performed
Returns:
the Photo requested
Throws:
IOException
getAlbum
public void getAlbum(String albumId,
Album album,
ActionListener callback)
throws IOException
getAlbum
public Album getAlbum(String albumId,
boolean needAuth)
throws IOException
Gets a Album from a albumId This is a sync method it will block until a response it
returned
Parameters:
the - albumId
needAuth - if this object is public needAuth can be false and no authentication
will be performed
Returns:
the Album requested
Throws:
IOException
getNewsFeed
public void getNewsFeed(String userId,
DefaultListModel feed,
ActionListener callback)
throws IOException
Gets the user news feed, the data is being stored in the given DefaultListModel. By
default this method will return last 13 news entries.
Parameters:
userId - the userid we would like to query
feed - the response to fill
callback - the callback that should be updated when the data arrives
Throws:
IOException
Method Detail
2512
Gets the user news feed, the data is being stored in the given DefaultListModel.
Parameters:
userId - the userid we would like to query
feed - the response to fill
limit - the number of items to return
callback - the callback that should be updated when the data arrives
Throws:
IOException
getWallFeed
public void getWallFeed(String userId,
DefaultListModel feed,
ActionListener callback)
throws IOException
Gets the user wall feed, the data is being stored in the given DefaultListModel. By
default this method will return last 13 news entries.
Parameters:
userId - the userid we would like to query
feed - the response fo fill
callback - the callback that should be updated when the data arrives
Throws:
IOException
getWallFeed
public void getWallFeed(String userId,
DefaultListModel feed,
int limit,
ActionListener callback)
throws IOException
Gets the user wall feed, the data is being stored in the given DefaultListModel.
Parameters:
userId - the userid we would like to query
feed - the response to fill
limit - the number of items to return
callback - the callback that should be updated when the data arrives
Throws:
IOException
getWallPosts
public void getWallPosts(String userId,
DefaultListModel feed,
ActionListener callback)
throws IOException
Gets the user wall feed, the data is being stored in the given DefaultListModel. By
default this method will return last 13 news entries.
Parameters:
userId - the userid we would like to query
feed - the response fo fill
callback - the callback that should be updated when the data arrives
Throws:
IOException
getWallPosts
public void getWallPosts(String userId,
DefaultListModel feed,
int limit,
ActionListener callback)
throws IOException
Method Detail
2513
getPicture
public void getPicture(String id,
Label label,
Dimension toScale,
boolean tempStorage)
throws IOException
getPicture
public void getPicture(String id,
ActionListener callback,
Dimension toScale,
boolean tempStorage)
throws IOException
getPictureAndWait
public EncodedImage getPictureAndWait(String id,
Dimension toScale)
Method Detail
2514
Gets the picture of the given facebook object id and stores it in the given List in the
offset index This assumes the GenericListCellRenderer style of list which relies on a
hashtable based model approach.
Parameters:
id - the object id to query
targetList - the list that should be updated when the data arrives
targetOffset - the offset within the list to insert the image
targetKey - the key for the hashtable in the target offset
toScale - the scale of the image to put in the List or null
tempStorage - if true place the image in a temp storage
Throws:
IOException
getPhotoThumbnail
public void getPhotoThumbnail(String photoId,
ActionListener callback,
boolean tempStorage)
throws IOException
getPhotoThumbnail
public void getPhotoThumbnail(String photoId,
Label label,
Dimension toScale,
boolean tempStorage)
throws IOException
getUserFriends
public void getUserFriends(String userId,
DefaultListModel friends,
ActionListener callback)
throws IOException
getUserAlbums
public void getUserAlbums(String userId,
DefaultListModel albums,
ActionListener callback)
throws IOException
Method Detail
2515
Throws:
IOException
getAlbumPhotos
public void getAlbumPhotos(String albumId,
DefaultListModel photos,
int offset,
int limit,
ActionListener callback)
throws IOException
getPostComments
public void getPostComments(String postId,
DefaultListModel comments,
ActionListener callback)
throws IOException
getUserInboxThreads
public void getUserInboxThreads(String userId,
DefaultListModel threads,
int limit,
ActionListener callback)
throws IOException
postOnWall
public void postOnWall(String userId,
String message)
throws IOException
Method Detail
2516
postComment
public void postComment(String postId,
String message)
throws IOException
createNote
public void createNote(String userId,
String subject,
String message)
throws IOException
postOnWall
public void postOnWall(String userId,
String message,
ActionListener callback)
throws IOException
postOnWall
public void postOnWall(String userId,
String message,
String name,
String link,
String description,
String picture,
String caption,
ActionListener callback)
throws IOException
Method Detail
2517
postLike
public void postLike(String postId,
ActionListener callback)
throws IOException
postComment
public void postComment(String postId,
String message,
ActionListener callback)
throws IOException
createNote
public void createNote(String userId,
String subject,
String message,
ActionListener callback)
throws IOException
getUserNotifications
public void getUserNotifications(String userId,
String startTime,
boolean includeRead,
DefaultListModel notifications,
ActionListener callback)
throws IOException
Gets the user notifications (this method uses the legacy rest api see
http://developers.facebook.com/docs/reference/rest/)
Parameters:
userId - the user id
startTime - Indicates the earliest time to return a notification. This equates to
the updated_time field in the notification FQL table. If not specified, this call
returns all available notifications.
includeRead - Indicates whether to include notifications that have already
been read. By default, notifications a user has read are not included.
notifications - store notifications results into the given model, each entry is
an Hashtable Object contaning the Object data
callback - the callback that should be updated when the data arrives
Throws:
IOException
getUsersDetails
public void getUsersDetails(String[] usersIds,
String[] fields,
ActionListener callback)
throws IOException
Method Detail
2518
getUserEvents
public void getUserEvents(String userId,
DefaultListModel events,
ActionListener callback)
throws IOException
search
public void search(String objectType,
String query,
DefaultListModel results,
ActionListener callback)
throws IOException
killCurrentRequest
public void killCurrentRequest()
Method Detail
2519
cleanTempStorage
public void cleanTempStorage()
The client id (appid) which asks to connect (this is generated when an app is created
see: https://developers.facebook.com/apps)
Parameters:
clientId setClientSecret
public static void setClientSecret(String clientSecret)
Sets the token to the FaceBookAccess class, this is useful if the token has not yet
expired, get the expiration of the token with Oauth2.getExpires()
Parameters:
tok - the token of the
getToken
public static String getToken()
Returns the Facebook authorization token that can be used for API access
Returns:
the token
Method Detail
2520
Some simple queries for public data can work just fine with anonymous login without
requiring the whole OAuth process, they still need a facebook application though
Parameters:
appid - the id of the application
clientSecret - the client secret for the application
getApiVersion
public static String getApiVersion()
Returns the api version used, if empty the non version-ed is used
setApiVersion
public static void setApiVersion(String apiVersion)
Sets the Facebook api version being used, by default the api calls the non version-ed
version of the API.
Parameters:
apiVersion - valid values are "1.0", "2.0", "2.1"
Method Detail
2521
Class FBObject
java.lang.Object
com.codename1.facebook.FBObject
Direct Known Subclasses:
Album, Page, Photo, Post, User
public class
extends Object
Constructor Summary
Constructor and Description
FBObject()
Empty Contructor
FBObject(Hashtable props)
Method Summary
Modifier and Type
void
boolean
equals(Object obj)
String
Simple getter
getName()
String
Simple getter
hashCode()
int
void
Simple setter
Constructor Detail
FBObject
public FBObject()
Empty Contructor
FBObject
public FBObject(Hashtable props)
Class FBObject
2522
Method Detail
setId
public void setId(String id)
Simple setter
Parameters:
id - the Object Id, each facebook element had an id
getId
public String getId()
Simple getter
Returns:
the facebook object id
getName
public String getName()
Simple getter
Returns:
the FB Object name
copy
public void copy(Hashtable props)
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Object
hashCode
public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of
hashtables such as those provided by java.util.Hashtable. The general contract of
hashCode is: Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application. If two objects are equal
according to the equals(Object) method, then calling the hashCode method on each
of the two objects must produce the same integer result. It is not required that if two
objects are unequal according to the equals(java.lang.Object) method, then calling
the hashCode method on each of the two objects must produce distinct integer
Constructor Detail
2523
Method Detail
2524
Class Album
java.lang.Object
com.codename1.facebook.FBObject
com.codename1.facebook.Album
public class
extends FBObject
Constructor Summary
Constructor and Description
Album()
Empty Contructor
Album(Hashtable props)
Method Summary
Modifier and Type
void
int
String
String
String
getCover_photo()
Gets created_time
getDescription()
Gets description
getFrom()
User
String
String
String
String
String
getLink()
Class Album
2525
Detail
Album
public Album()
Empty Contructor
Album
public Album(Hashtable props)
Method Detail
getCount
public int getCount()
Gets created_time
Returns:
created_time
getDescription
public String getDescription()
Gets description
Returns:
description
getFrom
public User getFrom()
Constructor Detail
2526
getPrivacy
public String getPrivacy()
Method Detail
2527
Interface Row
public interface
Method Summary
Modifier and Type
getBlob(int index)
byte[]
double
float
int
long
short
String
Method Detail
getBlob
byte[] getBlob(int index)
throws IOException
getDouble
double getDouble(int index)
throws IOException
getFloat
float getFloat(int index)
throws IOException
Interface Row
2528
getInteger
int getInteger(int index)
throws IOException
getLong
long getLong(int index)
throws IOException
getShort
short getShort(int index)
throws IOException
getString
String getString(int index)
throws IOException
Method Detail
2529
Class Database
java.lang.Object
com.codename1.db.Database
This is a Database SQLite class, this class allows developers to connect to a database and preform
sql queries on the data. The Database class abstracts the underlying SQLite of the device if available.
Supported platforms for this feature are: IOS, Android, BB OS5+ and the Desktop Simulator (which
supports only cursor forward navigation). The SQLite should be used for very large data handling, for
small storage refer to Storage which is more portable.
Constructor Summary
Constructor and Description
Database()
Method Summary
Modifier and
Type
abstract void
abstract void
abstract void
static void
abstract void
void
abstract void
Starts a transaction
close()
Deletes database
execute(String sql)
abstract Cursor
This method should be called with SELECT type statements that return
row set.
executeQuery(String sql, String[] params)
abstract Cursor
static boolean
This method should be called with SELECT type statements that return
row set.
exists(String databaseName)
static String
static Database
abstract void
Class Database
Returns the file path of the Database if exists and if supported on the
platform.
openOrCreate(String databaseName)
2530
Constructor Detail
Database
public Database()
Method Detail
openOrCreate
public static Database openOrCreate(String databaseName)
throws IOException
Deletes database
Parameters:
databaseName
Throws:
IOException
getDatabasePath
public static String getDatabasePath(String databaseName)
Returns the file path of the Database if exists and if supported on the platform.
Returns:
the file path of the database
beginTransaction
public abstract void beginTransaction()
throws IOException
Starts a transaction
Throws:
IOException
commitTransaction
public abstract void commitTransaction()
throws IOException
2531
execute
public abstract void execute(String sql)
throws IOException
Execute an update query. Used for INSERT, UPDATE, DELETE and similar sql
statements.
Parameters:
sql - the sql to execute
Throws:
IOException
execute
public abstract void execute(String sql,
String[] params)
throws IOException
Execute an update query with params. Used for INSERT, UPDATE, DELETE and
similar sql statements. The sql can be constructed with '?' and the params will be
binded to the query
Parameters:
sql - the sql to execute
params - to bind to the query where the '?' exists
Throws:
IOException
execute
public void execute(String sql,
Object[] params)
throws IOException
Execute an update query with params. Used for INSERT, UPDATE, DELETE and
similar sql statements. The sql can be constructed with '?' and the params will be
binded to the query
Parameters:
sql - the sql to execute
params - to bind to the query where the '?' exists, supported object types are
String, byte[], Double, Long and null
Throws:
IOException
executeQuery
public abstract Cursor executeQuery(String sql,
String[] params)
throws IOException
This method should be called with SELECT type statements that return row set.
Parameters:
sql - the sql to execute
params - to bind to the query where the '?' exists
Returns:
Method Detail
2532
executeQuery
public abstract Cursor executeQuery(String sql)
throws IOException
This method should be called with SELECT type statements that return row set.
Parameters:
sql - the sql to execute
Returns:
a cursor to iterate over the results
Throws:
IOException
Method Detail
2533
Interface Cursor
public interface
Method Summary
Modifier and Type
close()
void
boolean
int
int
String
int
Row
boolean
boolean
boolean
boolean
Method Detail
first
boolean first()
throws IOException
Move the cursor to the first row. If cursor provides forward-only navigation and is
positioned after the first row then calling first() method would throw a IOException.
Returns:
true if succeeded
Throws:
IOException
last
boolean last()
throws IOException
Interface Cursor
2534
next
boolean next()
throws IOException
Moves the cursor to the next row. Calling next() method the first time will position
cursor on the first.
Returns:
true if succeeded
Throws:
IOException
prev
boolean prev()
throws IOException
Moves the cursor to the previous row. If cursor is forward type then calling prev()
would throw a IOException.
Returns:
true if succeeded
Throws:
IOException
getColumnIndex
int getColumnIndex(String columnName)
throws IOException
Returns the zero-based index for a given column name. Note that columns meta
information is available only after navigation to the first row
Parameters:
columnName - the name of the column.
Returns:
the index of the column
Throws:
IOException
getColumnName
String getColumnName(int columnIndex)
throws IOException
Returns the column name at a given zero-based column index. Note that columns
meta information is available only after navigation to the first row
Parameters:
columnIndex - the index of the column
Returns:
the name of the column
Throws:
IOException
getColumnCount
int getColumnCount()
throws IOException
getPosition
int getPosition()
throws IOException
Method Detail
2535
close
void close()
throws IOException
getRow
Row getRow()
throws IOException
Method Detail
2536
Class ContactsModel
java.lang.Object
com.codename1.ui.list.DefaultListModel
com.codename1.contacts.ContactsModel
All Implemented Interfaces:
ListModel
public class
extends DefaultListModel
This Contacts model is responsible for querying Contacts from the device and to cache the data for
faster usage
Constructor Summary
Constructor and Description
ContactsModel(String[] ids)
Method Summary
Modifier and Type
void
Object
getItemAt(int index)
void
void
Constructor Detail
ContactsModel
public ContactsModel(String[] ids)
Class ContactsModel
2537
Detail
setPlaceHolderImage
public void setPlaceHolderImage(Image placeHolder)
Adds the specified item to the end of this list. An optional operation for mutable lists, it
can throw an unsupported operation exception if a list model is not mutable.
Specified by:
addItem in interface ListModel
Overrides:
addItem in class DefaultListModel
Parameters:
item - the item to be added
removeItem
public void removeItem(int index)
Method Detail
2538
Class ContactsManager
java.lang.Object
com.codename1.contacts.ContactsManager
public class
extends Object
This class uses as the Contacts manager of the device, it enables the possibility To get the Contacts
that are available on the device.
Constructor Summary
Constructor and Description
ContactsManager()
Method Summary
Modifier and
Type
static
String
static
boolean
deleteContact(String id)
static
String[]
getAllContacts()
Contact[]
Deprecated.
this method was incorrectly introduced use getContacts instead
static
String[]
getAllContactsWithNumbers()
static
Contact
getContactById(String id)
static
Contact
static
Contact[]
This method returns a Contact by the contact id and fills it's data according to
the given flags
getContacts(boolean withNumbers, boolean includesFullName,
boolean includesPicture, boolean includesNumbers,
boolean includesEmail, boolean includeAddress)
Notice: this method might be very slow and should be invoked on a separate
thread! It might have platform specific optimizations over getAllContacts
followed by looping over individual contacts but that isn't guaranteed.
isAllContactsFast()
static
boolean
boolean
Class ContactsManager
Deprecated.
this method was incorrectly introduced and isn't static use isAllContactsFast
instead
2539
Constructor Detail
ContactsManager
public ContactsManager()
Method Detail
getAllContacts
public static String[] getAllContacts()
This method returns a Contact by the contact id and fills it's data according to the
given flags
Parameters:
id - of the Contact
includesFullName - if true try to fetch the full name of the Contact(not just
display name)
includesPicture - if true try to fetch the Contact Picture if exists
includesNumbers - if true try to fetch all Contact numbers
includesEmail - if ture try to fetch all Contact Emails
includeAddress - if ture try to fetch all Contact Addresses
Returns:
a Contact Object
createContact
public static String createContact(String
String
String
String
String
String
firstName,
familyName,
workPhone,
homePhone,
mobilePhone,
email)
2540
withNumbers,
includesFullName,
includesPicture,
includesNumbers,
includesEmail,
includeAddress)
Deprecated. this method was incorrectly introduced and isn't static use
isAllContactsFast instead
Indicates if the getAllContacts is platform optimized, notice that the method might still
take seconds or more to run so you should still use a separate thread!
Returns:
true if getAllContacts will perform faster that just getting each contact
getContacts
public static Contact[] getContacts(boolean
boolean
boolean
boolean
boolean
boolean
withNumbers,
includesFullName,
includesPicture,
includesNumbers,
includesEmail,
includeAddress)
Notice: this method might be very slow and should be invoked on a separate thread!
It might have platform specific optimizations over getAllContacts followed by looping
over individual contacts but that isn't guaranteed. See isGetAllContactsFast for
information.
Parameters:
withNumbers - if true returns only contacts that has a number
Method Detail
2541
display name)
includesPicture - if true try to fetch the Contact Picture if
includesNumbers - if true try to fetch all Contact numbers
includesEmail - if true try to fetch all Contact Emails
includeAddress - if true try to fetch all Contact Addresses
exists
Returns:
array of the contacts
isAllContactsFast
public static boolean isAllContactsFast()
Indicates if the getAllContacts is platform optimized, notice that the method might still
take seconds or more to run so you should still use a separate thread!
Returns:
true if getAllContacts will perform faster that just getting each contact
Method Detail
2542
Class Contact
java.lang.Object
com.codename1.contacts.Contact
public class
extends Object
This class represents a Contact information from the device Address Book
Constructor Summary
Constructor and Description
Contact()
Empty Constructor
Method Summary
Modifier
and Type
Hashtable
long
String
Gets the Contact Addresses, the Hashtable contains key/value pairs where the
key is a String which represents the type of the Address, types can be: "home",
"work", "other" the value is an Address Object.
getBirthday()
Hashtable
String
String
String
String
Gets the Contact Emails, the Hashtable contains key/value pairs where the key
is a String which represents the type of the Email, types can be: "home",
"mobile", "work", "other" the value is String of the email.
getFamilyName()
Hashtable
Image
Gets the Contact phone numbers, the Hashtable contains key/value pairs
where the key is a String which represents the type of the phone number, types
can be: "home", "mobile", "work", "fax", "other" the value is String of the phone
number.
getPhoto()
String
Gets the primary email of this Contact, notice this can be null even though the
Contact has emails declared
getPrimaryPhoneNumber()
String
Class Contact
Gets the primary phone number of this Contact, notice this can be null even
though the Contact has phone numbers declared
2543
getUrls()
void
void
void
void
void
void
void
void
void
void
void
void
void
Constructor Detail
Contact
public Contact()
Empty Constructor
Method Detail
getAddresses
public Hashtable getAddresses()
Gets the Contact Addresses, the Hashtable contains key/value pairs where the key is
a String which represents the type of the Address, types can be: "home", "work",
"other" the value is an Address Object.
Returns:
Hashtable of available addresses
getBirthday
public long getBirthday()
Method Summary
2544
Gets the Contact Emails, the Hashtable contains key/value pairs where the key is a
String which represents the type of the Email, types can be: "home", "mobile", "work",
"other" the value is String of the email.
Returns:
Hashtable of available emails
getId
public String getId()
Gets the Contact phone numbers, the Hashtable contains key/value pairs where the
key is a String which represents the type of the phone number, types can be: "home",
"mobile", "work", "fax", "other" the value is String of the phone number.
Returns:
Hashtable of available phone numbers
getPhoto
public Image getPhoto()
Gets the primary email of this Contact, notice this can be null even though the
Contact has emails declared
Returns:
the Contact primary email or null if not declared
Method Detail
2545
Gets the primary phone number of this Contact, notice this can be null even though
the Contact has phone numbers declared
Returns:
the Contact primary phone number or null if not declared
setAddresses
public void setAddresses(Hashtable addresses)
Method Detail
2546
Method Detail
2547
Class Address
java.lang.Object
com.codename1.contacts.Address
public class
extends Object
Constructor Summary
Constructor and Description
Address()
Empty Constructor
Method Summary
Modifier and Type
String
String
String
String
String
void
void
void
void
void
Constructor Detail
Address
public Address()
Empty Constructor
Class Address
2548
Detail
getCountry
public String getCountry()
Method Detail
2549
Class WebBrowser
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.WebBrowser
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
Field Summary
Constructor Summary
Constructor and Description
WebBrowser()
Default constructor
Method Summary
Modifier and Type
static String
void
This method creates a data URI which allows developers creating HTML
into the HTML by appending them as a URI.
destroy()
BrowserNavigationCallback
Component
String
String[]
Class WebBrowser
2550
Class[]
Object
String
String
This method is here to workaround an XMLVM array type bug where pro
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Imag
getPropertyTypes()
Matches the property names method (see that method for further details
getPropertyValue(String name)
Returns the current value of the property name, this method is used by t
getTitle()
void
void
This is a callback method, this method is called after the url has been loa
onStart(String url)
void
This is a callback method, this method is called before the url has been l
reload()
void
setBrowserNavigationCallback(BrowserNavigationCallback callback)
Set the browser navigation callback which allows handling a case where
Java code.
void
void
String
Sets a new value to the given property, returns an error message if failed
setURL(String url)
void
Sets the page URL, jar: URL's must be supported by the implementation
stop()
void
Method Summary
2551
Constructor Detail
WebBrowser
public WebBrowser()
Default constructor
Method Detail
createDataURI
public static String createDataURI(byte[] data,
String mime)
This method creates a data URI which allows developers creating HTML for local use
to embed local images into the HTML by appending them as a URI. E.g. instead of
referencing a file or URL just load the image data and place the contents of this string
into the src attribute.
This is the easiest way to get an HTML with local images to work on all mobile
platforms.
2552
- data of an image
- the mime type of the image e.g. image/png
Returns:
a data URL that can be placed into the img src attribute in HTML e.g.
data:image/png;base64,encodedData
onStart
public void onStart(String url)
This is a callback method, this method is called before the url has been loaded
Parameters:
url onLoad
public void onLoad(String url)
This is a callback method, this method is called after the url has been loaded
Parameters:
url setBrowserNavigationCallback
public void setBrowserNavigationCallback(BrowserNavigationCallback callback)
Set the browser navigation callback which allows handling a case where a URL
invocation can be delegated to Java code. This allows binding Java side functionality
to JavaScript functionality in the same way PhoneGap/Cordova work
Parameters:
callback - the callback interface
getBrowserNavigationCallback
public BrowserNavigationCallback getBrowserNavigationCallback()
The browser navigation callback interface allows handling a case where a URL
invocation can be delegated to Java code. This allows binding Java side functionality
to JavaScript functionality in the same way PhoneGap/Cordova work
Returns:
the callback interface
onError
public void onError(String message,
int errorCode)
Method Detail
2553
Sets the page URL, jar: URL's must be supported by the implementation
Parameters:
url - the URL
reload
public void reload()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
Method Detail
2554
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
2555
Class ToastBar
java.lang.Object
com.codename1.components.ToastBar
public class
extends Object
An API to present status messages to the user in an unobtrusive manner. This is useful if there are
background tasks that need to display information to the user. E.g. If a network request fails, of let the
user know that "Jobs are being synchronized".
Example Usage
Status status = ToastBar.getInstance().createStatus();
status.setMessage("Hello world");
status.show();
//... Some time later you must clear the status
status.clear();Status status = ToastBar.getInstance().createStatus();
status.setMessage("Hello world");
status.setShowProgressIndicator(true);
status.show();
// ... Some time later you must clear it
status.clear();Status status = ToastBar.getInstance().createStatus();
status.setMessage("Hello world");
status.showDelayed(300); // Wait 300 ms to show the status
// ... Some time later, clear the status... this may be before it shows at all
status.clear();Status status = ToastBar.getInstance().createStatus();
status.setMessage("Hello world");
status.setExpires(3000); // only show the status for 3 seconds, then have it automatically clear
status.show();
Advanced Usage
See the StatusBarDemo
Screenshots
Status With Progress Bar
Class ToastBar
2556
Video Demo
Note: the video above refers to the ToastBar based on its development name of StatusBar. This was
changed to avoid confusion with the iOS StatusBar.
2557
Nested
Class Summary
class
Method Summary
Modifier and Type
ToastBar.Status
String
Gets the default UIID to be used for the style of the ToastBar text.
getDefaultUIID()
Gets the default UIID to be used for the style of the ToastBar
component.
String
static ToastBar
getInstance()
void
text.
setDefaultUIID(String defaultUIID)
Sets the defaults UIID to be used for the style of the ToastBar
component.
void
setVisible(boolean visible)
Shows or hides the ToastBar.
void
Method Detail
getInstance
public static ToastBar getInstance()
Gets the default UIID to be used for the style of the ToastBar component. By default
this is "ToastBarComponent".
Returns:
the defaultUIID
setDefaultUIID
public void setDefaultUIID(String defaultUIID)
Sets the defaults UIID to be used for the style of the ToastBar component. By default
this is "ToastBarComponent"
Parameters:
defaultUIID - the defaultUIID to set
2558
Gets the default UIID to be used for the style of the ToastBar text. By default this is
"ToastBarMessage"
Returns:
the defaultMessageUIID
setDefaultMessageUIID
public void setDefaultMessageUIID(String defaultMessageUIID)
Sets the default UIID to be used for the style of the ToastBar text. By default this is
"ToastBarMessage"
Parameters:
defaultMessageUIID - the defaultMessageUIID to set
createStatus
public ToastBar.Status createStatus()
Method Detail
2559
Class ToastBar.Status
java.lang.Object
com.codename1.components.ToastBar.Status
Enclosing class:
ToastBar
public class
extends Object
Method Summary
Modifier
and Type
void
Image
String
String
int
Gets the icon (may be null) that is displayed with this status.
getMessage()
Gets the UIID to use for styling the text of this status message.
getProgress()
String
Gets the UIID that should be used for styling the status component while this
status is displayed.
boolean
isShowProgressIndicator()
setExpires(int millis)
void
void
void
void
Directs the status to be cleared (if it isn't already cleared() after a given number
of milliseconds.
setIcon(Image icon)
Sets the UIID to use for styling the text of this status message.
setProgress(int progress)
void
Sets the progress (1..100) that should be displayed in the progress bar for this
status.
setShowProgressIndicator(boolean showProgressIndicator)
void
Sets whether this status message should include an infinite progress indicator
(e.g.
setUiid(String uiid)
void
void
Sets the UIID that should be used for styling the status component while this
status is displayed.
show()
void
Class ToastBar.Status
2560
Method Detail
setExpires
public void setExpires(int millis)
Directs the status to be cleared (if it isn't already cleared() after a given number of
milliseconds.
Parameters:
millis - The maximum number of milliseconds that the status message
should be displayed for. Helpful for error messages that only need to be
displayed for a few seconds.
setMessage
public void setMessage(String message)
Sets the progress (1..100) that should be displayed in the progress bar for this status.
(Not tested or used yet).
Parameters:
progress show
public void show()
Shows this status message. Call this method after making any changes to the status
that you want to have displayed. This will always cause any currently-displayed
status to be replaced by this status.
If you don't want to show the status immediately, but rather to wait some delay, you
can use the showDelayed(int) method instead.
See Also:
showDelayed(int)
showDelayed
public void showDelayed(int millis)
2561
Clears this status message. This any pending "showDelayed" requests for this status.
getMessage
public String getMessage()
Returns the progress of this status. A value of -1 indicates that the progress bar
should not be shown. Values between 0 and 100 inclusive will be rendered on a
progress bar (slider) in the status component.
Returns:
the progress
getIcon
public Image getIcon()
Gets the icon (may be null) that is displayed with this status.
Returns:
the icon
setIcon
public void setIcon(Image icon)
Sets the icon that is to be displayed with this status. Set this to null to not show an
icon.
Parameters:
icon - the icon to set
isShowProgressIndicator
public boolean isShowProgressIndicator()
Returns:
the showProgressIndicator
setShowProgressIndicator
public void setShowProgressIndicator(boolean showProgressIndicator)
Sets whether this status message should include an infinite progress indicator (e.g.
spinning beach ball).
Parameters:
showProgressIndicator - the showProgressIndicator to set
getMessageUIID
public String getMessageUIID()
Gets the UIID to use for styling the text of this status message.
Returns:
the messageUIID
setMessageUIID
public void setMessageUIID(String messageUIID)
Sets the UIID to use for styling the text of this status message.
Parameters:
messageUIID - the messageUIID to set
Method Detail
2562
Gets the UIID that should be used for styling the status component while this status is
displayed.
Returns:
the uiid
setUiid
public void setUiid(String uiid)
Sets the UIID that should be used for styling the status component while this status is
displayed.
Parameters:
uiid - the uiid to set
Method Detail
2563
Class StorageImageAsync
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.EncodedImage
com.codename1.components.StorageImageAsync
public class
extends EncodedImage
Asynchronous storage image that loads in the background and not during the paint cycle effectively
not blocking the EDT drawing speed.
Method Summary
Modifier and Type
boolean
static
StorageImageAsync
Returns the byte array data backing the image allowing the image
to be stored and discarded completely from RAM.
byte[]
getInternal()
protected Image
boolean
protected void
Method Detail
Class StorageImageAsync
2564
A subclass might choose to load asynchroniously and reset the cache when the
image is ready.
Overrides:
resetCache in class EncodedImage
getInternal
protected Image getInternal()
Returns the actual image represented by the encoded image, this image will be
cached in a weak/soft reference internally. This method is useful to detect when the
system actually created an image instance. You shouldn't invoke this method
manually!
Overrides:
getInternal in class EncodedImage
Returns:
drawable image instance
getImageData
public byte[] getImageData()
Returns the byte array data backing the image allowing the image to be stored and
discarded completely from RAM.
Overrides:
getImageData in class EncodedImage
Returns:
byte array used to create the image, e.g. encoded PNG, JPEG etc.
animate
public boolean animate()
Overrides:
animate
in class Image
isAnimation
public boolean isAnimation()
Creates an encoded image that maps to a storage file thus allowing to seamlessly
cache images as needed. This only works reasonably well for very small files.
Parameters:
fileName - the name of the storage file
placeholder - an image that must be of the same size as the EncodedImage
Returns:
image that will load the file seamlessly
Method Detail
2565
Class StorageImage
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.EncodedImage
com.codename1.components.StorageImage
public class
extends EncodedImage
An encoded image that stores the actual data of the encoded image in storage.
Method Summary
Modifier and
Type
static
StorageImage
static
StorageImage
static
StorageImage
static
StorageImage
static
StorageImage
byte[]
Returns the byte array data backing the image allowing the image to be
stored and discarded completely from RAM.
Class StorageImage
2566
Method Detail
getImageData
public byte[] getImageData()
Returns the byte array data backing the image allowing the image to be stored and
discarded completely from RAM.
Overrides:
getImageData in class EncodedImage
Returns:
byte array used to create the image, e.g. encoded PNG, JPEG etc.
create
public static StorageImage create(String fileName,
byte[] data,
int width,
int height)
Creates an encoded image that maps to a storage file thus allowing to seamlessly
cache images as needed. This only works reasonably well for very small files.
Parameters:
fileName - the name of the storage file
data - the data
width - the width of the file or -1 if unknown (notice that this will improve
performance)
height - the height of the file or -1 if unknown (notice that this will improve
performance)
Returns:
image that will load the file seamlessly or null if the storage failed
create
public static StorageImage create(String fileName,
byte[] data,
int width,
int height,
boolean keep)
Creates an encoded image that maps to a storage file thus allowing to seamlessly
cache images as needed. This only works reasonably well for very small files.
Parameters:
fileName - the name of the storage file
data - the data
width - the width of the file or -1 if unknown (notice that this will improve
performance)
height - the height of the file or -1 if unknown (notice that this will improve
performance)
keep - if set to true keeps the file in RAM once loaded
Returns:
image that will load the file seamlessly or null if the storage failed
create
public static StorageImage create(String fileName,
InputStream data,
int width,
int height)
throws IOException
Creates an encoded image that maps to a storage file thus allowing to seamlessly
cache images as needed. This only works reasonably well for very small files.
Parameters:
fileName - the name of the storage file
data - the stream to cache
width - the width of the file or -1 if unknown (notice that this will improve
performance)
height - the height of the file or -1 if unknown (notice that this will improve
performance)
Method Detail
2567
Returns:
image that will load the file seamlessly
Throws:
IOException
create
public static StorageImage create(String fileName,
int width,
int height)
Creates an encoded image that maps to a storage file thus allowing to seamlessly
cache images as needed. This only works reasonably well for very small files.
Parameters:
fileName - the name of the storage file
width - the width of the file or -1 if unknown (notice that this will improve
performance)
height - the height of the file or -1 if unknown (notice that this will improve
performance)
Returns:
image that will load the file seamlessly
create
public static StorageImage create(String fileName,
int width,
int height,
boolean keep)
Creates an encoded image that maps to a storage file thus allowing to seamlessly
cache images as needed. This only works reasonably well for very small files.
Parameters:
fileName - the name of the storage file
width - the width of the file or -1 if unknown (notice that this will improve
performance)
height - the height of the file or -1 if unknown (notice that this will improve
performance)
keep - if set to true keeps the file in RAM once loaded
Returns:
image that will load the file seamlessly
Method Detail
2568
Class SpanLabel
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.SpanLabel
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
A multi line label component that can be easily localized, this is simply based on a text area combined
with a label.
SpanLabel d = new SpanLabel("Default SpanLabel that can seamlessly line break when the text is really long.");
d.setIcon(icon);
SpanLabel l = new SpanLabel("NORTH Positioned Icon SpanLabel that can seamlessly line break when the text is really lo
l.setIcon(icon);
l.setIconPosition(BorderLayout.NORTH);
SpanLabel r = new SpanLabel("SOUTH Positioned Icon SpanLabel that can seamlessly line break when the text is really lo
r.setIcon(icon);
r.setIconPosition(BorderLayout.SOUTH);
SpanLabel c = new SpanLabel("EAST Positioned Icon SpanLabel that can seamlessly line break when the text is really lon
c.setIcon(icon);
c.setIconPosition(BorderLayout.EAST);
hi.add(d).add(l).add(r).add(c);
Field Summary
Class SpanLabel
2569
Constructor Summary
Constructor and Description
SpanLabel()
Default constructor will be useful when adding this to the GUI builder
SpanLabel(String txt)
Method Summary
Modifier
and
Type
Image
String
String
String[]
A component may expose mutable property names for a UI designer to manipulate, this AP
usage internally by the GUI builder code
getPropertyTypeNames()
String[]
Class[]
Object
String
int
Style
String
Style
void
void
void
String
void
This method is here to workaround an XMLVM array type bug where property types aren't id
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListMod
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI builder
getText()
Returns the alignment of the whole text block and not the text within it!
getTextSelectedStyle()
Sets a new value to the given property, returns an error message if failed and null if success
setText(String t)
void
Indicates the alignment of the whole text block, this is different from setting the alignment of
block since the UIID might have a border or other design element that won't be affected by
2570
void
void
void
Method Summary
2571
Constructor Detail
SpanLabel
public SpanLabel()
Default constructor will be useful when adding this to the GUI builder
SpanLabel
public SpanLabel(String txt,
String textUiid)
Method Detail
setTextUIID
public void setTextUIID(String uiid)
2572
Indicates the alignment of the whole text block, this is different from setting the
alignment of the text within the block since the UIID might have a border or other
design element that won't be affected by such alignment. The default is none (-1)
which means no alignment takes place and the text block takes the whole width.
Parameters:
align - valid values are Component.LEFT, Component.RIGHT,
Component.CENTER. Anything else will stretch the text block
getTextBlockAlign
public int getTextBlockAlign()
Returns the alignment of the whole text block and not the text within it!
Returns:
-1 for unaligned otherwise one of Component.LEFT/RIGHT/CENTER
Method Detail
2573
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
Method Detail
2574
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
2575
Class SpanButton
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.SpanButton
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
A complex button similar to MultiButton that breaks lines automatically and looks like a regular button
(more or less). Unlike the multi button the span button has the UIID style of a button.
SpanButton sb = new SpanButton("SpanButton is a composite component (lead component) that looks/acts like a Button but
sb.setIcon(icon);
hi.add(sb);
Field Summary
Constructor Summary
Constructor and Description
SpanButton()
Default constructor will be useful when adding this to the GUI builder
SpanButton(String txt)
Method Summary
Modifier
and
Type
void
Command
Class SpanButton
2576
Image
String
String
String[]
A component may expose mutable property names for a UI designer to manipulate, this AP
usage internally by the GUI builder code
getPropertyTypeNames()
String[]
Class[]
Object
String
String
This method is here to workaround an XMLVM array type bug where property types aren't id
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListMod
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI builder
getText()
void
void
void
void
void
String
Sets a new value to the given property, returns an error message if failed and null if success
setText(String t)
void
void
Method Summary
2577
Constructor Detail
SpanButton
public SpanButton()
Default constructor will be useful when adding this to the GUI builder
SpanButton
public SpanButton(String txt,
String textUiid)
2578
SpanButton
public SpanButton(String txt)
Method Detail
setTextUIID
public void setTextUIID(String uiid)
Constructor Detail
2579
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
Method Detail
2580
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
2581
Class SliderBridge
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.Slider
com.codename1.components.SliderBridge
All Implemented Interfaces:
Animation, StyleListener
public class
extends Slider
Field Summary
Constructor Summary
Constructor and Description
SliderBridge()
Default constuctor
SliderBridge(ConnectionRequest source)
Displays progress only for the source object, every other object in the queue before
completion will produce an infinite progress.
SliderBridge(ConnectionRequest[] sources)
Method Summary
Modifier and Type
static void
static void
Class SliderBridge
2582
2583
Constructor
Detail
SliderBridge
public SliderBridge()
Default constuctor
SliderBridge
public SliderBridge(ConnectionRequest source)
Displays progress only for the source object, every other object in the queue before
completion will produce an infinite progress. After 100% the progress will no longer
move.
Parameters:
source - the request whose progress should be followed
SliderBridge
public SliderBridge(ConnectionRequest[] sources)
Method Detail
bindProgress
public static void bindProgress(ConnectionRequest source,
Slider s)
Constructor Detail
2584
Class ShareButton
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.Button
com.codename1.components.ShareButton
All Implemented Interfaces:
Animation, ActionListener, StyleListener
public class
extends Button
implements ActionListener
The share button allows sharing a String or an image either thru the defined sharing services or thru
the native OS sharing support. On Android & iOS the native sharing API is invoked for this class.
The code below demonstrates image sharing, notice that an image must be stored using the
FileSystemStorage API and shouldn't use a different API like Storage!
Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);
Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");
Method Detail
2585
Field Summary
Constructor Summary
Constructor and Description
ShareButton()
Default constructor
Class ShareButton
2586
Method Summary
Modifier
and Type
void
void
String
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
String
Returns the current value of the property name, this method is used by the
GUI builder
getTextToShare()
void
String
Sets a new value to the given property, returns an error message if failed and
null if successful.
setTextToShare(String textToShare)
void
Method Summary
2587
Constructor Detail
ShareButton
public ShareButton()
Default constructor
Method Detail
setTextToShare
public void setTextToShare(String textToShare)
2588
Sets the image to share. Notice some sharing services cannot share image and a
text, therefore if setTextToShare(...) is also used, the sharing service gives image
sharing higher priority.
Parameters:
imagePath - the full file path
imageMimeType - the image mime type e.g. image/png, image/jpeg
getImagePathToShare
public String getImagePathToShare()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Label
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Label
Parameters:
name - the name of the property
Returns:
the value of said property
Method Detail
2589
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Label
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
2590
Class ScaleImageLabel
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.components.ScaleImageLabel
All Implemented Interfaces:
Animation, StyleListener
public class
extends Label
Label that simplifies the usage of scale to fill/fit. This is effectively equivalent to just setting the style
image on a label but more convenient for some special circumstances. One major difference is that
preferred size equals the image in this case.
The default UIID for this component is "Label".
TableLayout tl = new TableLayout(2, 2);
Form hi = new Form("ScaleImageButton/Label", tl);
Style s = UIManager.getInstance().getComponentStyle("Button");
Image icon = FontImage.createMaterial(FontImage.MATERIAL_WARNING, s);
ScaleImageLabel fillLabel = new ScaleImageLabel(icon);
fillLabel.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
ScaleImageButton fillButton = new ScaleImageButton(icon);
fillButton.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
hi.add(tl.createConstraint().widthPercentage(20), new ScaleImageButton(icon)).
add(tl.createConstraint().widthPercentage(80), new ScaleImageLabel(icon)).
add(fillLabel).
add(fillButton);
hi.show();
Field Summary
Constructor Summary
Constructor and Description
ScaleImageLabel()
Default constructor
Class ScaleImageLabel
2591
Method Summary
Modifier and
Type
protected
Dimension
byte
Image
void
setIcon(Image i)
void
void
Scale image label doesn't support text this method is overriden to do nothing
setUIID(String id)
void
Constructor Summary
2592
Constructor Detail
ScaleImageLabel
public ScaleImageLabel()
Default constructor
ScaleImageLabel
public ScaleImageLabel(Image i)
Method Detail
setBackgroundType
public void setBackgroundType(byte behavior)
2593
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Label
Returns:
the calculated preferred size based on component content
setIcon
public void setIcon(Image i)
Scale image label doesn't support text this method is overriden to do nothing
Overrides:
setText in class Label
Parameters:
text - the string that the label presents.
setUIID
public void setUIID(String id)
This method sets the Component the Unique identifier. This method should be used
before a component has been initialized Overriden to prevent the setUIID from
replacing the code
Overrides:
setUIID in class Component
Parameters:
id - UIID unique identifier for component type
Method Detail
2594
Class ScaleImageButton
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Label
com.codename1.ui.Button
com.codename1.components.ScaleImageButton
All Implemented Interfaces:
Animation, StyleListener
public class
extends Button
Button that simplifies the usage of scale to fill/fit. This is effectively equivalent to just setting the style
image on a button but more convenient for some special circumstances. One major difference is that
preferred size equals the image in this case.
The UIID of this class is ScaleImageButton, the original Button UIID isn't preserved since it might
cause an issue with the border.
TableLayout tl = new TableLayout(2, 2);
Form hi = new Form("ScaleImageButton/Label", tl);
Style s = UIManager.getInstance().getComponentStyle("Button");
Image icon = FontImage.createMaterial(FontImage.MATERIAL_WARNING, s);
ScaleImageLabel fillLabel = new ScaleImageLabel(icon);
fillLabel.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
ScaleImageButton fillButton = new ScaleImageButton(icon);
fillButton.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
hi.add(tl.createConstraint().widthPercentage(20), new ScaleImageButton(icon)).
add(tl.createConstraint().widthPercentage(80), new ScaleImageLabel(icon)).
add(fillLabel).
add(fillButton);
hi.show();
Field Summary
Class ScaleImageButton
2595
Summary
Default constructor
ScaleImageButton(Image i)
Method Summary
Modifier and
Type
protected
Dimension
byte
Image
Image
Returns the icon for the button based on its current state
setBackgroundType(byte behavior)
void
setIcon(Image i)
void
void
Scale image label doesn't support text this method is overriden to do nothing
setUIID(String id)
void
Constructor Summary
2596
Constructor Detail
ScaleImageButton
public ScaleImageButton()
Default constructor
ScaleImageButton
public ScaleImageButton(Image i)
2597
Method Detail
setBackgroundType
public void setBackgroundType(byte behavior)
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Button
Returns:
the calculated preferred size based on component content
setUIID
public void setUIID(String id)
This method sets the Component the Unique identifier. This method should be used
before a component has been initialized Overriden to prevent the setUIID from
replacing the code
Overrides:
setUIID in class Component
Parameters:
id - UIID unique identifier for component type
setIcon
public void setIcon(Image i)
Scale image label doesn't support text this method is overriden to do nothing
Method Detail
2598
Overrides:
setText
in class Label
Parameters:
text - the string that the label presents.
getIconFromState
public Image getIconFromState()
Returns the icon for the button based on its current state Overriden to return getIcon
always.
Overrides:
getIconFromState in class Button
Returns:
the button icon based on its current state
Method Detail
2599
Class ReplaceableImage
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.EncodedImage
com.codename1.components.ReplaceableImage
public class
extends EncodedImage
Allows the image data to be replaced at runtime when a different image is available. The only
limitation is that the image width/height must be identical and opacity status can't change (an opaque
image can't be made translucent and visa versa).
Method Summary
Modifier and Type
boolean
static
ReplaceableImage
Returns the byte array data backing the image allowing the image to
be stored and discarded completely from RAM.
byte[]
boolean
boolean
isAnimation()
Replaces the current image with the new image which must match
the dimensions etc.
void
Method Detail
Class ReplaceableImage
2600
Returns the byte array data backing the image allowing the image to be stored and
discarded completely from RAM.
Overrides:
getImageData in class EncodedImage
Returns:
byte array used to create the image, e.g. encoded PNG, JPEG etc.
replace
public void replace(EncodedImage newImage)
Replaces the current image with the new image which must match the dimensions
etc. of the previous image.
Parameters:
newImage - the image to apply
create
public static ReplaceableImage create(EncodedImage placeholder)
Creates an encoded image that can later be replaced with a different image
Parameters:
placeholder - a temporary image
Returns:
image that will be replaceable later on
animate
public boolean animate()
Overrides:
animate
in class Image
isAnimation
public boolean isAnimation()
Method Detail
2601
Class RSSReader
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.List
com.codename1.components.RSSReader
All Implemented Interfaces:
Animation, StyleListener
public class
extends List
A List implementing an RSS reader that automatically populates itself with content from the RSS
chanel. When clicking an article it displays the HTML content of said article in a new Form.
Field Summary
Constructor Summary
Constructor and Description
RSSReader()
Method Summary
Modifier
and Type
Image
int
String
Places a limit on the number of RSS entries requested from the server
getProgressTitle()
getPropertyNames()
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
Container
Class RSSReader
Returns the current value of the property name, this method is used by the
GUI builder
getTargetContainer()
The form/container to which the RSS will navigate when clicking a RSS entry
2602
String
protected
void
initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready
for action" component state
isAddBackToTaget()
boolean
boolean
isBlockList()
sendRequest()
void
void
void
setBlockList(boolean blockList)
void
setIconPlaceholder(Image iconPlaceholder)
setLimit(int limit)
void
Places a limit on the number of RSS entries requested from the server
static void
static void
void
setMoreDescription(String d)
Sets a new value to the given property, returns an error message if failed and
null if successful.
String
setTargetContainer(Container targetContainer)
void
The form/container to which the RSS will navigate when clicking a RSS entry
setURL(String url)
void
protected
void
showRSSEntry(Hashtable h)
Method Summary
2603
Constructor Detail
RSSReader
public RSSReader()
Method Detail
2604
Send the request to the server, will only work once. This is called implicitly when the
list is initialized
initComponent
protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
getURL
public String getURL()
Returns:
the iconPlaceholder
setIconPlaceholder
public void setIconPlaceholder(Image iconPlaceholder)
Parameters:
iconPlaceholder
showRSSEntry
protected void showRSSEntry(Hashtable h)
Places a limit on the number of RSS entries requested from the server
Returns:
Method Detail
2605
Places a limit on the number of RSS entries requested from the server
Parameters:
limit - the limit to set
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
isBlockList
public boolean isBlockList()
Returns:
the blockList
setBlockList
public void setBlockList(boolean blockList)
Parameters:
blockList
Method Detail
2606
Returns:
the progressTitle
setProgressTitle
public void setProgressTitle(String progressTitle)
Parameters:
progressTitle
getTargetContainer
public Container getTargetContainer()
The form/container to which the RSS will navigate when clicking a RSS entry
Returns:
the targetContainer
setTargetContainer
public void setTargetContainer(Container targetContainer)
The form/container to which the RSS will navigate when clicking a RSS entry
Parameters:
targetContainer - the targetContainer to set
isAddBackToTaget
public boolean isAddBackToTaget()
Indicates whether a back command should be added implicitly to the target container
Returns:
the addBackToTaget
setAddBackToTaget
public void setAddBackToTaget(boolean addBackToTaget)
Indicates whether a back command should be added implicitly to the target container
Parameters:
addBackToTaget - the addBackToTaget to set
Method Detail
2607
Class Progress
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.Form
com.codename1.ui.Dialog
com.codename1.components.Progress
All Implemented Interfaces:
Animation, ActionListener, StyleListener, Iterable<Component>
public class
extends Dialog
implements ActionListener
Field Summary
Constructor Summary
Constructor and Description
Progress(String title, ConnectionRequest request)
Method Summary
Modifier
and Type
protected
void
void
void
Class Progress
2608
isAutoShow()
void
void
setDisposeOnCompletion(boolean disposeOnCompletion)
Method Summary
2609
Constructor Detail
Progress
public Progress(String title,
ConnectionRequest request)
2610
Progress
public Progress(String title,
ConnectionRequest request,
boolean showPercentage)
Method Detail
actionCommand
protected void actionCommand(Command cmd)
Invoked to allow subclasses of form to handle a command from one point rather than
implementing many command instances
Overrides:
actionCommand in class Dialog
Parameters:
cmd - the action command
dispose
public void dispose()
Closes the current form and returns to the previous form, releasing the EDT in the
process
Overrides:
dispose in class Dialog
isDisposeOnCompletion
public boolean isDisposeOnCompletion()
Returns:
the disposeOnCompletion
setDisposeOnCompletion
public void setDisposeOnCompletion(boolean disposeOnCompletion)
Parameters:
disposeOnCompletion
actionPerformed
public void actionPerformed(ActionEvent evt)
Constructor Detail
2611
Method Detail
2612
Class OnOffSwitch
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.OnOffSwitch
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
The on/off switch is a checkbox of sort (although it derives container) that represents its state as a
switch each of which has a short label associated with it. It has two types: Android and iOS. The types
differ in the way that they are rendered. The Android type (the default) is just a button with a label that
can be moved/dragged between the two states. The iOS version is more elaborate due to the look of
that platform.
Field Summary
Constructor Summary
Constructor and Description
OnOffSwitch()
Class OnOffSwitch
2613
Method Summary
Modifier and
Type
void
protected
Dimension
protected
void
Adds a listener to the switch which will cause an event to dispatch on click
calcPreferredSize()
Vector
Deprecated.
use the version that returns a collection
getComponentState()
Object
Collection
String
String
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
Image
Image
Image
protected
void
boolean
protected
boolean
boolean
Returns the current value of the property name, this method is used by the
GUI builder
getSwitchMaskImage()
Gets the image that is used for the "Off" state of the switch.
getSwitchOnImage()
Gets the image that is used for the "On" state of the switch.
initComponent()
void
void
void
Constructor Summary
If this Component is focused, the pointer dragged event will call this method
pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method
2614
void
If this Component is focused, the pointer released event will call this method
removeActionListener(ActionListener l)
void
protected
void
resetFocusable()
If getComponentState returned a value the setter can update the value and
restore the prior state.
void
setNoTextMode(boolean noTextMode)
void
void
void
String
Sets a new value to the given property, returns an error message if failed and
null if successful.
setSwitchMaskImage(Image switchMaskImage)
void
Sets the image that should be used for the "On" state.
setSwitchOffImage(Image switchOffImage)
void
Sets the image that should be used for the "Off" state.
setSwitchOnImage(Image switchOnImage)
void
Sets the image that should be used for the "Off" state.
setValue(boolean value)
void
Method Summary
2615
Constructor Detail
OnOffSwitch
public OnOffSwitch()
Default constructor
Method Detail
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Container
Returns:
the calculated preferred size based on component content
resetFocusable
protected void resetFocusable()
2616
Adds a listener to the switch which will cause an event to dispatch on click
Parameters:
l - implementation of the action listener interface
removeActionListener
public void removeActionListener(ActionListener l)
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
deinitialize
protected void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
Method Detail
2617
If this Component is focused, the pointer pressed event will call this method
Overrides:
pointerPressed in class Container
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerDragged
public void pointerDragged(int x,
int y)
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
getOn
public String getOn()
Method Detail
2618
Some components may optionally generate a state which can then be restored using
setCompnentState(). This method is used by the UIBuilder.
Overrides:
getComponentState in class Component
Returns:
the component state or null for undefined state.
setComponentState
public void setComponentState(Object state)
If getComponentState returned a value the setter can update the value and restore
the prior state.
Overrides:
setComponentState in class Component
Parameters:
state - the non-null state
getPropertyTypes
public Class[] getPropertyTypes()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
Method Detail
2619
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
isNoTextMode
public boolean isNoTextMode()
Gets the image that is used for the "On" state of the switch.
Returns:
The image that will be used for the "On" state. If the "onOffIOSModeBool"
theme constant is false and the switchOnImage hasn't been explicitly set by
the setSwitchOnImage(com.codename1.ui.Image) method, then this will return
null.
See Also:
setSwitchOnImage(com.codename1.ui.Image), getSwitchOffImage(),
getSwitchMaskImage()
setSwitchOnImage
public void setSwitchOnImage(Image switchOnImage)
Sets the image that should be used for the "Off" state. Note: This option is only used
if the "onOffIOSModeBool" theme constant is enabled.
Note: If the "onOffIOSModeBool" theme constant is false and you set this image, you
must also set the "Off" image with setSwitchOffImage(com.codename1.ui.Image) and
the "Mask" image with setSwitchMaskImage(com.codename1.ui.Image).
Parameters:
switchOnImage
See Also:
getSwitchOnImage(), setSwitchMaskImage(com.codename1.ui.Image),
setSwitchOffImage(com.codename1.ui.Image)
getSwitchOffImage
public Image getSwitchOffImage()
Gets the image that is used for the "Off" state of the switch.
Returns:
The image that will be used for the "Off" state. If the "onOffIOSModeBool"
theme constant is false and the switchOffImage hasn't been explicitly set by
the setSwitchOffImage(com.codename1.ui.Image) method, then this will
Method Detail
2620
setSwitchOffImage
public void setSwitchOffImage(Image switchOffImage)
Sets the image that should be used for the "Off" state. Note: This option is only used
if the "onOffIOSModeBool" theme constant is enabled.
Note: If the "onOffIOSModeBool" theme constant is false and you set this image, you
must also set the "On" image with setSwitchOnImage(com.codename1.ui.Image) and
the "Mask" image with setSwitchMaskImage(com.codename1.ui.Image).
Parameters:
switchOffImage
See Also:
getSwitchOffImage(), setSwitchMaskImage(com.codename1.ui.Image),
setSwitchOnImage(com.codename1.ui.Image)
getSwitchMaskImage
public Image getSwitchMaskImage()
Gets the image that is used for the mask. Note: This option is only used if the
"onOffIOSModeBool" theme constant is enabled.
This image will generally consist of an opaque border/frame with a transparent center
such that the "on" and "off" images can be painted inside the transparent part, and
anything that is outside that center will be painted over by the frame, or clipped.
Returns:
the switchMaskImage image if the "onOffIOSModeBool" flag is set or the
mask image has been explicitly set on this OnOffSwitch using
setSwitchMaskImage(com.codename1.ui.Image)
See Also:
getSwitchOffImage(), getSwitchOffImage(),
setSwitchOnImage(com.codename1.ui.Image), getSwitchMaskImage(),
setSwitchMaskImage(com.codename1.ui.Image)
setSwitchMaskImage
public void setSwitchMaskImage(Image switchMaskImage)
Sets the image that should be used for the "On" state.
Note: If the "onOffIOSModeBool" is false and you set this mask, you must also set the
"On" image with setSwitchOnImage(com.codename1.ui.Image) and the "Off" image
with setSwitchOffImage(com.codename1.ui.Image).
Parameters:
switchMaskImage
on-off switch.
Method Detail
2621
Class MultiButton
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.MultiButton
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
A powerful button like component that allows multiple rows/and an icon to be added every row/icon
can have its own UIID. Internally the multi-button is a container with a lead component. Up to 4 rows
are supported.
MultiButton twoLinesNoIcon = new MultiButton("MultiButton");
twoLinesNoIcon.setTextLine2("Line 2");
MultiButton oneLineIconEmblem = new MultiButton("Icon + Emblem");
oneLineIconEmblem.setIcon(icon);
oneLineIconEmblem.setEmblem(emblem);
MultiButton twoLinesIconEmblem = new MultiButton("Icon + Emblem");
twoLinesIconEmblem.setIcon(icon);
twoLinesIconEmblem.setEmblem(emblem);
twoLinesIconEmblem.setTextLine2("Line 2");
MultiButton twoLinesIconEmblemHorizontal = new MultiButton("Icon + Emblem");
twoLinesIconEmblemHorizontal.setIcon(icon);
twoLinesIconEmblemHorizontal.setEmblem(emblem);
twoLinesIconEmblemHorizontal.setTextLine2("Line 2 Horizontal");
twoLinesIconEmblemHorizontal.setHorizontalLayout(true);
MultiButton twoLinesIconCheckBox = new MultiButton("CheckBox");
twoLinesIconCheckBox.setIcon(icon);
twoLinesIconCheckBox.setCheckBox(true);
twoLinesIconCheckBox.setTextLine2("Line 2");
MultiButton fourLinesIcon = new MultiButton("With Icon");
fourLinesIcon.setIcon(icon);
fourLinesIcon.setTextLine2("Line 2");
fourLinesIcon.setTextLine3("Line 3");
fourLinesIcon.setTextLine4("Line 4");
hi.add(oneLineIconEmblem).
add(twoLinesNoIcon).
add(twoLinesIconEmblem).
add(twoLinesIconEmblemHorizontal).
add(twoLinesIconCheckBox).
add(fourLinesIcon);
Class MultiButton
2622
See Also:
SpanButton
Field Summary
Constructor Summary
Constructor and Description
MultiButton()
Method Summary
Modifier
and Type
void
Command
Image
String
Field Summary
2623
getEmblemPosition()
Label
String
String
String
String
String
String
String
String
Allows us to gain direct access to the icon component so we can set it directly
without going via the other methods, this is especially useful for classes such as
the ImageDownloadService which can then update the icon seamlessly.
getIconName()
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
String
String
String
String
String
String
String
String
boolean
boolean
boolean
Method Summary
Returns the current value of the property name, this method is used by the GUI
builder
getTextLine1()
Inverts the order of the first two entries so the second line appears first.
2624
isLinesTogetherMode()
Sets the name of the emblem (important for use in generic renderers
setEmblemPosition(String t)
Sets the name of the icon (important for use in generic renderers
setIconPosition(String t)
Inverts the order of the first two entries so the second line appears first.
setLinesTogetherMode(boolean l)
Changes the layout so the lines of the button are grouped together
setMaskName(String maskName)
Sets the name of the row (important for use in generic renderers)
setNameLine2(String t)
Sets the name of the row (important for use in generic renderers
setNameLine3(String t)
Sets the name of the row (important for use in generic renderers
setNameLine4(String t)
Sets the name of the row (important for use in generic renderers
setPropertyValue(String name, Object value)
String
void
void
void
void
void
Method Summary
Sets a new value to the given property, returns an error message if failed and
null if successful.
setRadioButton(boolean b)
Toggles the selected state for the radio button/check box modes
setTextLine1(String t)
2625
void
void
void
void
void
2626
Constructor Detail
MultiButton
public MultiButton(String line1)
Method Detail
setLinesTogetherMode
public void setLinesTogetherMode(boolean l)
Changes the layout so the lines of the button are grouped together
Parameters:
l - true to group the lines together
isLinesTogetherMode
public boolean isLinesTogetherMode()
Allows us to gain direct access to the icon component so we can set it directly without
going via the other methods, this is especially useful for classes such as the
ImageDownloadService which can then update the icon seamlessly.
Returns:
the component used internally to represent the icon
setCheckBox
public void setCheckBox(boolean b)
2627
Toggles the selected state for the radio button/check box modes
Parameters:
b - true for checked false for unchecked
Method Detail
2628
Inverts the order of the first two entries so the second line appears first. This only
works in horizontal mode!
Parameters:
b - true to place the second row entry as the first entry
isInvertFirstTwoEntries
public boolean isInvertFirstTwoEntries()
Inverts the order of the first two entries so the second line appears first. This only
works in horizontal mode!
Returns:
true when the second row entry should be placed before the first entry
setTextLine1
public void setTextLine1(String t)
Sets the name of the row (important for use in generic renderers)
Parameters:
t - name to set
getNameLine1
public String getNameLine1()
Method Detail
2629
Sets the name of the row (important for use in generic renderers
Parameters:
t - name to set
getNameLine2
public String getNameLine2()
Method Detail
2630
Sets the name of the row (important for use in generic renderers
Parameters:
t - name to set
getNameLine3
public String getNameLine3()
Sets the name of the row (important for use in generic renderers
Parameters:
t - name to set
getNameLine4
public String getNameLine4()
Method Detail
2631
Method Detail
2632
Sets the name of the icon (important for use in generic renderers
Parameters:
t - name to set
getIconName
public String getIconName()
Sets the name of the emblem (important for use in generic renderers
Parameters:
t - name to set
getEmblemName
public String getEmblemName()
Method Detail
2633
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
getGroup
public String getGroup()
Method Detail
2634
Class MediaPlayer
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.MediaPlayer
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
Video playback component with control buttons for back, play/pause and forward buttons. In the
simulator those controls are implemented locally but on the device the native playback controls are
used.
final Form hi = new Form("MediaPlayer", new BorderLayout());
hi.setToolbar(new Toolbar());
Style s = UIManager.getInstance().getComponentStyle("Title");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_VIDEO_LIBRARY, s);
hi.getToolbar().addCommandToRightBar(new Command("", icon) {
{@literal @}Override
public void actionPerformed(ActionEvent evt) {
Display.getInstance().openGallery((e) -> {
if(e != null && e.getSource() != null) {
String file = (String)e.getSource();
try {
Media video = MediaManager.createMedia(file, true);
hi.removeAll();
hi.add(BorderLayout.CENTER, new MediaPlayer(video));
hi.revalidate();
} catch(IOException err) {
Log.e(err);
}
}
}, Display.GALLERY_VIDEO);
}
});
hi.show();
Class MediaPlayer
2635
Summary
Constructor Summary
Constructor and Description
MediaPlayer()
Empty constructor
MediaPlayer(Media video)
Empty constructor
Method Summary
Modifier and
Type
protected
Dimension
calcPreferredSize()
Image
getBackIcon()
String
Image
Media
Image
getPauseIcon()
Image
getPlayIcon()
getPropertyNames()
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
protected
void
boolean
boolean
void
void
void
void
Returns the current value of the property name, this method is used by the
GUI builder
initComponent()
Field Summary
2636
void
void
void
void
void
void
String
Sets a new value to the given property, returns an error message if failed
and null if successful.
Method Summary
2637
Constructor Detail
MediaPlayer
public MediaPlayer()
Empty constructor
MediaPlayer
public MediaPlayer(Media video)
Empty constructor
Method Detail
getMedia
public Media getMedia()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Container
Returns:
the calculated preferred size based on component content
2638
Method Detail
2639
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
getPlayIcon
public Image getPlayIcon()
Returns:
the playIcon
getPauseIcon
public Image getPauseIcon()
Returns:
the pauseIcon
getBackIcon
public Image getBackIcon()
Returns:
the backIcon
Method Detail
2640
Returns:
the fwdIcon
isAutoplay
public boolean isAutoplay()
Method Detail
2641
Class MasterDetail
java.lang.Object
com.codename1.components.MasterDetail
public class
extends Object
Constructor Summary
Constructor and Description
MasterDetail()
Method Summary
Modifier
and Type
Constructor Detail
MasterDetail
public MasterDetail()
Method Detail
bindTabletLandscapeMaster
public static void bindTabletLandscapeMaster(Form rootForm,
Container parentContainer,
Component landscapeUI,
Component portraitUI,
String commandTitle,
Image commandIcon)
Class MasterDetail
2642
Class InteractionDialog
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.InteractionDialog
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
Unlike a regular dialog the interaction dialog only looks like a dialog, it resides in the layered pane and
can be used to implement features where interaction with the background form is still required.
Since this code is designed for interaction all "dialogs" created thru here are modless and never
block.
InteractionDialog dlg = new InteractionDialog("Hello");
dlg.setLayout(new BorderLayout());
dlg.add(BorderLayout.CENTER, new Label("Hello Dialog"));
Button close = new Button("Close");
close.addActionListener((ee) -> dlg.dispose());
dlg.addComponent(BorderLayout.SOUTH, close);
Dimension pre = dlg.getContentPane().getPreferredSize();
dlg.show(0, 0, Display.getInstance().getDisplayWidth() - (pre.getWidth() + pre.getWidth() / 6), 0);
Field Summary
Method Detail
2643
Summary
Method Summary
Modifier
and Type
void
void
void
void
void
Container
Style
String
Layout
This method adds the Component at a specific index location in the Container
Components array.
addComponent(int index, Object constraints, Component cmp)
String
getTitle()
Label
getTitleComponent()
boolean
boolean
isAnimateShow()
void
remove all Components from container, notice that removed component might
still have a pending repaint in the queue that won't be removed.
removeComponent(Component cmp)
void
void
void
void
void
void
void
void
showPopupDialog(Component c)
Constructor Summary
2644
A popup dialog is shown with the context of a component and its selection, it is
disposed seamlessly if the back button is pressed or if the user touches
outside its bounds.
void
Method Summary
2645
Constructor Detail
InteractionDialog
public InteractionDialog()
Method Detail
getContentPane
public Container getContentPane()
addComponent
public void addComponent(Component cmp)
2646
This method adds the Component at a specific index location in the Container
Components array.
Overrides:
addComponent in class Container
Parameters:
index - location to insert the Component
cmp - the Component to add
removeAll
public void removeAll()
remove all Components from container, notice that removed component might still
have a pending repaint in the queue that won't be removed. Calling form.repaint() will
workaround such an issue.
Overrides:
removeAll in class Container
removeComponent
public void removeComponent(Component cmp)
removes a Component from the Container, notice that removed component might still
have a pending repaint in the queue that won't be removed. Calling form.repaint() will
workaround such an issue.
Overrides:
removeComponent in class Container
Parameters:
cmp - the removed component
getTitleComponent
public Label getTitleComponent()
Method Detail
2647
show
public void show(int
int
int
int
top,
bottom,
left,
right)
This method shows the form as a modal alert allowing us to produce a behavior of an
alert/dialog box. This method will block the calling thread even if the calling thread is
the EDT. Notice that this method will not release the block until dispose is called even
if show() from another form is called!
Modal dialogs Allow the forms "content" to "hang in mid air" this is especially useful
for dialogs where you would want the underlying form to "peek" from behind the form.
Parameters:
top - space in pixels between the top of the screen and the form
bottom - space in pixels between the bottom of the screen and the form
left - space in pixels between the left of the screen and the form
right - space in pixels between the right of the screen and the form
dispose
public void dispose()
isShowing
public boolean isShowing()
A popup dialog is shown with the context of a component and its selection, it is
disposed seamlessly if the back button is pressed or if the user touches outside its
bounds. It can optionally provide an arrow in the theme to point at the context
component. The popup dialog has the PopupDialog style by default.
Parameters:
c - the context component which is used to position the dialog and can also
be pointed at
Method Detail
2648
A popup dialog is shown with the context of a component and its selection, it is
disposed seamlessly if the back button is pressed or if the user touches outside its
bounds. It can optionally provide an arrow in the theme to point at the context
component. The popup dialog has the PopupDialog style by default.
Parameters:
rect - the screen rectangle to which the popup should point
setDialogUIID
public void setDialogUIID(String uiid)
Method Detail
2649
Class InfiniteScrollAdapter
java.lang.Object
com.codename1.components.InfiniteScrollAdapter
public class
extends Object
Allows adapting a scroll container to scroll indefinitely (or at least until running out of data), this
effectively works by showing an infinite progress indicator when reaching scroll end then allowing
code to fetch additional components.
The sample code shows the usage of the nestoria API to fill out an infinitely scrolling list.
Form hi = new Form("InfiniteScrollAdapter", new BoxLayout(BoxLayout.Y_AXIS));
Style s = UIManager.getInstance().getComponentStyle("MultiLine1");
FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 3), false);
InfiniteScrollAdapter.createInfiniteScroll(hi.getContentPane(), () -> {
java.util.List<Map<String, Object>> data = fetchPropertyData("Leeds");
MultiButton[] cmps = new MultiButton[data.size()];
for(int iter = 0 ; iter < cmps.length ; iter++) {
Map<String, Object> currentListing = data.get(iter);
if(currentListing == null) {
InfiniteScrollAdapter.addMoreComponents(hi.getContentPane(), new Component[0], false);
return;
}
String thumb_url = (String)currentListing.get("thumb_url");
String guid = (String)currentListing.get("guid");
String summary = (String)currentListing.get("summary");
cmps[iter] = new MultiButton(summary);
cmps[iter].setIcon(URLImage.createToStorage(placeholder, guid, thumb_url));
}
InfiniteScrollAdapter.addMoreComponents(hi.getContentPane(), cmps, true);
}, true);
int pageNumber = 1;
java.util.List<Map<String, Object>> fetchPropertyData(String text) {
try {
Class InfiniteScrollAdapter
2650
Method Summary
Modifier and Type
void
static
InfiniteScrollAdapter
static
InfiniteScrollAdapter
int
InfiniteProgress
getInfiniteProgress()
void
Method Detail
Method Summary
2651
Creates an instance of the InfiniteScrollAdapter that will invoke the fetch more
callback to fetch additional components, once that method completes its task it
should add the components via the addMoreComponents() invocation. Notice that the
container MUST be empty when invoking this method, fetchMore will be invoked
immediately and you can add your data when ready.
Parameters:
cont - the container to bind, it MUST be empty and must be scrollable on the
Y axis
fetchMore - a callback that will be invoked on the EDT to fetch more data (do
not block this method)
Returns:
an instance of this class that can be used to add components
createInfiniteScroll
public static InfiniteScrollAdapter createInfiniteScroll(Container cont,
Runnable fetchMore,
boolean fetchOnCreate)
Creates an instance of the InfiniteScrollAdapter that will invoke the fetch more
callback to fetch additional components, once that method completes its task it
should add the components via the addMoreComponents() invocation. Notice that the
container MUST be empty when invoking this method, fetchMore will be invoked
immediately and you can add your data when ready.
Parameters:
cont - the container to bind, it MUST be empty and must be scrollable on the
Y axis
fetchMore - a callback that will be invoked on the EDT to fetch more data (do
not block this method)
fetchOnCreate - if true the fetchMore callback is called upon calling this
method
Returns:
an instance of this class that can be used to add components
addMoreComponents
public static void addMoreComponents(Container cnt,
Component[] components,
boolean areThereMore)
Invoke this method to add additional components to the container, if you use
addComponent/removeComponent you will get undefined behavior. This is a
convenience method saving the need to keep the InfiniteScrollAdapter as a variable
Parameters:
cnt - container to add the components to
components - the components to add
areThereMore - whether additional components exist
addMoreComponents
public void addMoreComponents(Component[] components,
boolean areThereMore)
Invoke this method to add additional components to the container, if you use
addComponent/removeComponent you will get undefined behavior.
Parameters:
components - the components to add
areThereMore - whether additional components exist
getComponentLimit
public int getComponentLimit()
The component limit defines the number of components that should be within the
infinite scroll adapter, if more than component limit is added then the appropriate
number of components is removed from the top. This prevents running out of memory
Method Detail
2652
The component limit defines the number of components that should be within the
infinite scroll adapter, if more than component limit is added then the appropriate
number of components is removed from the top. This prevents running out of memory
or performance overhead with too many components... Notice that -1 is a special
case value for no component limit.
Parameters:
componentLimit - the componentLimit to set
getInfiniteProgress
public InfiniteProgress getInfiniteProgress()
Lets us manipulate the infinite progress object e.g. set the animation image etc.
Returns:
the infinite progress component underlying this adapter
Method Detail
2653
Class InfiniteProgress
java.lang.Object
com.codename1.ui.Component
com.codename1.components.InfiniteProgress
All Implemented Interfaces:
Animation, StyleListener
public class
extends Component
Shows a "Washing Machine" infinite progress indication animation, to customize the image you can
either use the infiniteImage theme constant or the setAnimation method. The image is rotated
automatically so don't use an animated image or anything like that as it would fail with the rotation
logic.
This class can be used in one of two ways either by embedding the component into the UI thru
something like this:
myContainer.add(new InfiniteProgress());
Field Summary
Class InfiniteProgress
2654
Constructor Summary
Constructor and Description
InfiniteProgress()
Method Summary
Modifier and
Type
boolean
protected
Dimension
protected
void
int
Image
The angle to increase (in degrees naturally) in every tick count, reduce to 1
to make the animation perfectly slow and smooth, increase to 45 to make it
fast and jumpy.
getAnimation()
getPropertyNames()
String[]
Class[]
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
int
Returns the current value of the property name, this method is used by the
GUI builder
getTickCount()
The animation rotates with EDT ticks, but not for every tick.
getTintColor()
int
protected
void
void
void
void
String
The angle to increase (in degrees naturally) in every tick count, reduce to 1
to make the animation perfectly slow and smooth, increase to 45 to make it
fast and jumpy.
setAnimation(Image animation)
Allows setting the image that will be rotated as part of this effect
setPropertyValue(String name, Object value)
Sets a new value to the given property, returns an error message if failed
2655
void
The animation rotates with EDT ticks, but not for every tick.
setTintColor(int tintColor)
void
showInifiniteBlocking()
Dialog
Shows the infinite progress over the whole screen, the blocking can be
competed by calling dispose() on the returned Dialog.
Method Summary
2656
Detail
InfiniteProgress
public InfiniteProgress()
Method Detail
showInifiniteBlocking
public Dialog showInifiniteBlocking()
Shows the infinite progress over the whole screen, the blocking can be competed by
calling dispose() on the returned Dialog.
Dialog ip = new InfiniteProgress().showInifiniteBlocking();
// do some long operation here using invokeAndBlock or do something in a separate thread and callback
// when you are done just call
ip.dispose();
Returns:
the dialog created for the blocking effect, disposing it will return to the
previous form and remove the input block.
initComponent
protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
deinitialize
protected void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
animate
public boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Component
Returns:
true if a repaint is desired or false if no repaint is necessary
calcPreferredSize
protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Component
Returns:
Constructor Detail
2657
Returns:
the animation
setAnimation
public void setAnimation(Image animation)
Allows setting the image that will be rotated as part of this effect
Parameters:
animation - the animation to set
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
Method Detail
2658
setPropertyValue
in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
getTintColor
public int getTintColor()
The tinting color of the screen when the showInifiniteBlocking method is invoked
Returns:
the tintColor
setTintColor
public void setTintColor(int tintColor)
The tinting color of the screen when the showInifiniteBlocking method is invoked
Parameters:
tintColor - the tintColor to set
getTickCount
public int getTickCount()
The animation rotates with EDT ticks, but not for every tick. To slow down the
animation increase this number and to speed it up reduce it to 1. It can't be 0 or
lower.
Returns:
the tickCount
setTickCount
public void setTickCount(int tickCount)
The animation rotates with EDT ticks, but not for every tick. To slow down the
animation increase this number and to speed it up reduce it to 1. It can't be 0 or
lower.
Parameters:
tickCount - the tickCount to set
getAngleIncrease
public int getAngleIncrease()
The angle to increase (in degrees naturally) in every tick count, reduce to 1 to make
the animation perfectly slow and smooth, increase to 45 to make it fast and jumpy. Its
probably best to use a number that divides well with 360 but that isn't a requirement.
Valid numbers are anything between 1 and 359.
Returns:
the angleIncrease
setAngleIncrease
public void setAngleIncrease(int angleIncrease)
The angle to increase (in degrees naturally) in every tick count, reduce to 1 to make
the animation perfectly slow and smooth, increase to 45 to make it fast and jumpy. Its
probably best to use a number that divides well with 360 but that isn't a requirement.
Valid numbers are anything between 1 and 359.
Parameters:
angleIncrease - the angleIncrease to set
Method Detail
2659
Class ImageViewer
java.lang.Object
com.codename1.ui.Component
com.codename1.components.ImageViewer
All Implemented Interfaces:
Animation, StyleListener
public class
extends Component
ImageViewer allows zooming/panning an image and potentially flicking between multiple images
within a list of images.
E.g. the trivial usage works like this:
Form hi = new Form("ImageViewer", new BorderLayout());
ImageViewer iv = new ImageViewer(duke);
hi.add(BorderLayout.CENTER, iv);
You can simulate pinch to zoom on the simulator by dragging the right button away from the top left
corner to zoom in and towards the top left corner to zoom out. On Mac touchpads you can drag two
fingers to achieve that.
A more elaborate usage includes flicking between multiple images e.g.:
Form hi = new Form("ImageViewer", new BorderLayout());
Image
Image
Image
Image
Class ImageViewer
2660
You can even download image URL's dynamically into the ImageViewer thanks to the usage of the
ListModel. E.g. in this model book cover images are downloaded dynamically:
Form hi = new Form("ImageViewer", new BorderLayout());
final EncodedImage placeholder = EncodedImage.createFromImage(
FontImage.createMaterial(FontImage.MATERIAL_SYNC, s).
scaled(300, 300), false);
class ImageList implements ListModel<Image> {
private int selection;
private String[] imageURLs = {
"http://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/300px-AGameOfThrones.jpg",
"http://awoiaf.westeros.org/images/thumb/3/39/AClashOfKings.jpg/300px-AClashOfKings.jpg",
"http://awoiaf.westeros.org/images/thumb/2/24/AStormOfSwords.jpg/300px-AStormOfSwords.jpg",
"http://awoiaf.westeros.org/images/thumb/a/a3/AFeastForCrows.jpg/300px-AFeastForCrows.jpg",
"http://awoiaf.westeros.org/images/7/79/ADanceWithDragons.jpg"
};
private Image[] images;
private EventDispatcher listeners = new EventDispatcher();
public ImageList() {
this.images = new EncodedImage[imageURLs.length];
}
public Image getItemAt(final int index) {
if(images[index] == null) {
images[index] = placeholder;
Util.downloadUrlToStorageInBackground(imageURLs[index], "list" + index, (e) -> {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("list" + index));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch(IOException err) {
err.printStackTrace();
}
});
}
return images[index];
}
public int getSize() {
return imageURLs.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
Class ImageViewer
2661
Field Summary
Modifier and
Type
static int
Indicates the initial position of the image in the viewer to FILL the
component size.
IMAGE_FIT
static int
Indicates the initial position of the image in the viewer to FIT to the
component size
Field Summary
2662
Summary
Default constructor
ImageViewer(Image i)
Method Summary
Modifier and
Type
boolean
protected
Dimension
void
Image
ListModel<Image>
int
int
Invoked to indicate that the component initialization is being reversed since the co
the container hierarchy.
getImage()
Returns the list model containing the images in the we can swipe through
getImageX()
Returns the x position of the image viewport which can be useful when it is being p
getImageY()
Returns the y position of the image viewport which can be useful when it is being p
getPropertyNames()
String[]
String[]
Class[]
Object
Image
This method is here to workaround an XMLVM array type bug where property type
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Objec
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI bu
getSwipePlaceholder()
This image is shown briefly during swiping while the full size image is loaded
getSwipeThreshold()
float
float
void
The swipe threshold is a number between 0 and 1 that indicates the threshold afte
moves to the next image.
getZoom()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
isCycleLeft()
boolean
By default the ImageViewer cycles from the beginning to the end of the list when g
false prevents this behaviour
isCycleRight()
boolean
boolean
void
Constructor Summary
By default the ImageViewer cycles from the end to the beginning of the list when g
to false prevents this behaviour
isEagerLock()
Eager locking effectively locks the right/left images as well as the main image, as
keyReleased(int key)
If this Component is focused, the key released event will call this method
2663
laidOut()
This is a callback method to inform the Component when it's been laidout on the p
paint(Graphics g)
This method paints the Component on the screen, it should be overriden by subcla
drawing or invoke the UI API's to let the PLAF perform the rendering.
void
paintBackground(Graphics g)
protected void
protected
boolean
void
If this Component is focused, the pointer dragged event will call this method
pointerPressed(int x, int y)
void
If this Component is focused, the pointer pressed event will call this method
pointerReleased(int x, int y)
void
If this Component is focused, the pointer released event will call this method
protected void
resetFocusable()
By default the ImageViewer cycles from the beginning to the end of the list when g
false prevents this behaviour
void
setCycleRight(boolean cycleRight)
By default the ImageViewer cycles from the end to the beginning of the list when g
to false prevents this behaviour
void
setEagerLock(boolean eagerLock)
void
Eager locking effectively locks the right/left images as well as the main image, as
setImage(Image image)
void
void
void
By providing this optional list of images you can allows swiping between multiple im
setPropertyValue(String name, Object value)
String
Sets a new value to the given property, returns an error message if failed and null
setSwipePlaceholder(Image swipePlaceholder)
void
This image is shown briefly during swiping while the full size image is loaded
setSwipeThreshold(float swipeThreshold)
The swipe threshold is a number between 0 and 1 that indicates the threshold afte
moves to the next image.
void
setZoom(float zoom)
void
protected
boolean
shouldBlockSideSwipe()
A component that might need side swipe such as the slider could block it from bei
purpose when on top of said component.
Method Summary
2664
Field Detail
IMAGE_FIT
public static final int IMAGE_FIT
Indicates the initial position of the image in the viewer to FIT to the component size
See Also:
Constant Field Values
IMAGE_FILL
public static final int IMAGE_FILL
Indicates the initial position of the image in the viewer to FILL the component size.
Notice this type might drop edges of the images in order to stretch the image to the
full size of the Component.
See Also:
Constant Field Values
Constructor Detail
ImageViewer
public ImageViewer()
Default constructor
2665
Method Detail
resetFocusable
protected void resetFocusable()
A component that might need side swipe such as the slider could block it from being
used for some other purpose when on top of said component.
Overrides:
shouldBlockSideSwipe in class Component
getPropertyTypes
public Class[] getPropertyTypes()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
getPropertyTypeNames
public String[] getPropertyTypeNames()
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
Constructor Detail
2666
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
initComponent
public void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
getImageX
public int getImageX()
Returns the x position of the image viewport which can be useful when it is being
panned by the user
Returns:
x position within the image for the top left corner
getImageY
public int getImageY()
Returns the y position of the image viewport which can be useful when it is being
panned by the user
Returns:
y position within the image for the top left corner
deinitialize
public void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
keyReleased
public void keyReleased(int key)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Component
Parameters:
key - the key code value to indicate a physical key.
pointerPressed
public void pointerPressed(int x,
int y)
If this Component is focused, the pointer pressed event will call this method
Method Detail
2667
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
pointerDragged
public void pointerDragged(int x,
int y)
If this Component is focused, the pointer dragged event will call this method
Overrides:
pointerDragged in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
laidOut
protected void laidOut()
This is a callback method to inform the Component when it's been laidout on the
parent Container
Overrides:
laidOut in class Component
pinch
protected boolean pinch(float scale)
Calculates the preferred size based on component content. This method is invoked
lazily by getPreferred size.
Overrides:
calcPreferredSize in class Component
Returns:
the calculated preferred size based on component content
animate
public boolean animate()
Method Detail
2668
By providing this optional list of images you can allows swiping between multiple
images
Parameters:
list - a list of images
getImageList
public ListModel<Image> getImageList()
Returns the list model containing the images in the we can swipe through
Returns:
the list model
getZoom
public float getZoom()
Method Detail
2669
This image is shown briefly during swiping while the full size image is loaded
Returns:
the swipePlaceholder
setSwipePlaceholder
public void setSwipePlaceholder(Image swipePlaceholder)
This image is shown briefly during swiping while the full size image is loaded
Parameters:
swipePlaceholder - the swipePlaceholder to set
isEagerLock
public boolean isEagerLock()
Eager locking effectively locks the right/left images as well as the main image, as a
result more heap is taken
Returns:
the eagerLock
setEagerLock
public void setEagerLock(boolean eagerLock)
Eager locking effectively locks the right/left images as well as the main image, as a
result more heap is taken
Parameters:
eagerLock - the eagerLock to set
isCycleLeft
public boolean isCycleLeft()
By default the ImageViewer cycles from the beginning to the end of the list when
going to the left, setting this to false prevents this behaviour
Returns:
true if it should cycle left from beginning
setCycleLeft
public void setCycleLeft(boolean cycleLeft)
By default the ImageViewer cycles from the beginning to the end of the list when
going to the left, setting this to false prevents this behaviour
Parameters:
cycleLeft - the cycle left to set
isCycleRight
public boolean isCycleRight()
By default the ImageViewer cycles from the end to the beginning of the list when
going to the right, setting this to false prevents this behaviour
Returns:
true if it should cycle right from the end
setCycleRight
public void setCycleRight(boolean cycleRight)
By default the ImageViewer cycles from the end to the beginning of the list when
going to the right, setting this to false prevents this behaviour
Method Detail
2670
The swipe threshold is a number between 0 and 1 that indicates the threshold after
which the swiped image moves to the next image. Below that number the image will
bounce back
Returns:
the threshold
setSwipeThreshold
public void setSwipeThreshold(float swipeThreshold)
The swipe threshold is a number between 0 and 1 that indicates the threshold after
which the swiped image moves to the next image. Below that number the image will
bounce back
Parameters:
swipeThreshold - the swipeThreshold to set
setImageInitialPosition
public void setImageInitialPosition(int imageInitialPosition)
Method Detail
2671
Class FloatingHint
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.FloatingHint
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Container
A floating hint is similar to a text field with a hint. However, when the text field has text in it the hint
appears above the text field instead including an animation when focus hits the text field see:
http://www.google.com/design/spec/components/text-fields.html#text-fields-floating-labels
Field Summary
Constructor Summary
Constructor and Description
FloatingHint(TextField tf)
Method Summary
Class FloatingHint
2672
Constructor Detail
FloatingHint
public FloatingHint(TextField tf)
2673
Class FileTreeModel
java.lang.Object
com.codename1.components.FileTreeModel
All Implemented Interfaces:
TreeModel
public class
extends Object
implements TreeModel
A tree model representing the file system as a whole, notice that this class returns absolute file names
which would result in an unreadable tree. To fix this you can create a Tree object and override
functionality such as the childToDisplayLabel method like this: Tree fileTree = new Tree(new
FileTreeModel(true)) { protected String childToDisplayLabel(Object child) { if (((String)
child).endsWith("/")) { return ((String) child).substring(((String)
child).lastIndexOf('/', ((String) child).length() - 2)); } return ((String)
child).substring(((String) child).lastIndexOf('/')); } };
Constructor Summary
Constructor and Description
FileTreeModel(boolean showFiles)
Method Summary
Modifier and
Type
void
Returns the child objects representing the given parent, null should return
the root objects
Vector
boolean
isLeaf(Object node)
Constructor Detail
FileTreeModel
public FileTreeModel(boolean showFiles)
Constructor Detail
2674
Detail
addExtensionFilter
public void addExtensionFilter(String extension)
Returns the child objects representing the given parent, null should return the root
objects
Specified by:
getChildren in interface TreeModel
Parameters:
parent - the parent object whose children should be returned, null would
return the tree roots
Returns:
the children of the given node within the tree
isLeaf
public boolean isLeaf(Object node)
Method Detail
2675
Class FileTree
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.ui.tree.Tree
com.codename1.components.FileTree
All Implemented Interfaces:
Animation, StyleListener, Iterable<Component>
public class
extends Tree
Field Summary
Constructor Summary
Constructor and Description
FileTree()
Default constructor
FileTree(FileTreeModel model)
Method Summary
Modifier and
Type
protected
String
Converts a tree child to a label, this method can be overriden for simple
rendering effects
Class FileTree
2676
2677
Constructor
Detail
FileTree
public FileTree()
Default constructor
FileTree
public FileTree(FileTreeModel model)
Method Detail
childToDisplayLabel
protected String childToDisplayLabel(Object child)
Constructor Detail
2678
Class FileEncodedImageAsync
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.EncodedImage
com.codename1.components.FileEncodedImageAsync
public class
extends EncodedImage
This class is identical to FileEncodedImage with the difference of using asynchronous loading for files
(and the animation framework) which will not work for all cases (e.g. renderers) but could improve
some performance/RAM aspects.
Method Summary
Modifier and Type
boolean
static
FileEncodedImageAsync
static
FileEncodedImageAsync
Deprecated.
use the version that accepts a name and a placeholderImage
create(String fileName, Image placeholder)
Returns the byte array data backing the image allowing the
image to be stored and discarded completely from RAM.
byte[]
getInternal()
protected Image
boolean
protected void
Method Detail
2679
Method Detail
resetCache
protected void resetCache()
A subclass might choose to load asynchroniously and reset the cache when the
image is ready.
Overrides:
resetCache in class EncodedImage
getInternal
protected Image getInternal()
Returns the actual image represented by the encoded image, this image will be
cached in a weak/soft reference internally. This method is useful to detect when the
system actually created an image instance. You shouldn't invoke this method
manually!
Overrides:
getInternal in class EncodedImage
Returns:
drawable image instance
getImageData
public byte[] getImageData()
Returns the byte array data backing the image allowing the image to be stored and
discarded completely from RAM.
Overrides:
getImageData in class EncodedImage
Returns:
byte array used to create the image, e.g. encoded PNG, JPEG etc.
animate
public boolean animate()
Overrides:
animate
in class Image
isAnimation
public boolean isAnimation()
2680
Creates an encoded image that maps to a local file thus allowing to seamlessly fetch
files as needed. This only works reasonably well for very small files.
Parameters:
fileName - the name of the file
placeholder - an image that will occupy the space
Returns:
image that will load the file seamlessly
Method Detail
2681
Class FileEncodedImage
java.lang.Object
com.codename1.ui.Image
com.codename1.ui.EncodedImage
com.codename1.components.FileEncodedImage
public class
extends EncodedImage
An encoded image that stores the actual data of the encoded image in a disk file or resource and
loads it only when necessary. The huge advantage is that RAM usage is practically none-existant, it is
potentially very slow in worst case scenarios and has the other drawback of requiring the width/height
in advanced to work properly.
Method Summary
Modifier and Type
static
FileEncodedImage
static
FileEncodedImage
static
FileEncodedImage
Returns the byte array data backing the image allowing the image to
be stored and discarded completely from RAM.
byte[]
Method Detail
Class FileEncodedImage
2682
Returns the byte array data backing the image allowing the image to be stored and
discarded completely from RAM.
Overrides:
getImageData in class EncodedImage
Returns:
byte array used to create the image, e.g. encoded PNG, JPEG etc.
create
public static FileEncodedImage create(String fileName,
int width,
int height)
Creates an encoded image that maps to a local file thus allowing to seamlessly fetch
files as needed. This only works reasonably well for very small files.
Parameters:
fileName - the name of the file
width - the width of the file or -1 if unknown (notice that this will improve
performance)
height - the height of the file or -1 if unknown (notice that this will improve
performance)
Returns:
image that will load the file seamlessly
create
public static FileEncodedImage create(String fileName,
InputStream i,
int width,
int height)
throws IOException
Creates an encoded image that maps to a local file thus allowing to seamlessly fetch
files as needed. This only works reasonably well for very small files. This version of
the method creates the file from an input stream
Parameters:
fileName - the name of the file
i - input stream from which to create the file
width - the width of the file or -1 if unknown (notice that this will improve
performance)
height - the height of the file or -1 if unknown (notice that this will improve
performance)
Returns:
image that will load the file seamlessly
Throws:
IOException
create
public static FileEncodedImage create(String fileName,
int width,
int height,
boolean keep)
Creates an encoded image that maps to a local file thus allowing to seamlessly fetch
files as needed. This only works reasonably well for very small files.
Parameters:
fileName - the name of the file
width - the width of the file or -1 if unknown (notice that this will improve
performance)
height - the height of the file or -1 if unknown (notice that this will improve
performance)
keep - if set to true keeps the file in RAM once loaded
Returns:
image that will load the file seamlessly
Method Detail
2683
Class Ads
java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.Ads
All Implemented Interfaces:
Animation, StyleListener, HTMLCallback, ParserCallback, Iterable<Component>
public class
extends Container
implements HTMLCallback
This is an Ads Component, this Component can displays banner/text ads on a Form. This is a generic
Ads Component that can support different type of Ads Network Services, at the Moment Codename
One supports innerActive ads, to gain an appId please refer to
http://console.inner-active.com/iamp/publisher/register?ref_id=affiliate_CodenameOne
Field Summary
Modifier
and Type
static
int
static
int
Error code denoting that an invalid attribute value was found in the CSS
ERROR_CSS_ATTRIBUTE_NOT_SUPPORTED
Error code denoting that an unsupported CSS attribute (by XHTML-MP 1.0
standards) was found in the HTML or external CSS files
ERROR_CSS_NO_BASE_URL
static
int
static
int
Error code denoting that a relative URL was referenced from a document with no
base URL (A document that was loaded via setBody/setHTML/setDOM and not
via setPage) In this case the return value of parsingError is not considered parsing continues and the resource at the URL (CSS file/image) is ignored
ERROR_CSS_NOT_FOUND
Error code denoting that a CSS file referenced from the HTML or from another
external CSS file was not found
Class Ads
2684
Constructor Summary
Constructor and Description
Ads()
Method Summary
Modifier
and Type
void
boolean
protected
void
String
Called when the user types in a TextField inside the HTMLComponent This method will be
HTMLComponent.isEventsEnabled() is true
deinitialize()
Invoked to indicate that the component initialization is being reversed since the component
the container hierarchy.
Called when one of the controls in the HTMLComponent obtained focus This method will b
HTMLComponent.isEventsEnabled() is true
focusLost(Component cmp, HTMLComponent htmlC, HTMLElement element)
void
String
String
String
String
String
String
String[]
Called when one of the controls in the HTMLComponent lost focus This method will be call
HTMLComponent.isEventsEnabled() is true
getAd()
Users age
getAppID()
Simple getter of the unique identifier of the app on the ads service network.
getAutoComplete(HTMLComponent htmlC, String actionURL, String id)
Called on form creation and enabled implementations of this method to return a value to pr
getCategory()
int
String
Returns properties about the given link to indicate to HTMLComponent how to render it No
always called NOT on the EDT thread.
getLocation()
Location string is a comma separated list of country, state/province, city For example: US,
getPropertyNames()
String[]
A component may expose mutable property names for a UI designer to manipulate, this AP
usage internally by the GUI builder code
2685
Class[]
This method is here to workaround an XMLVM array type bug where property types aren't
returns the names of the types using the following type names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListMo
getPropertyTypes()
Matches the property names method (see that method for further details).
getPropertyValue(String name)
Object
Returns the current value of the property name, this method is used by the GUI builder
getUpdateDuration()
int
void
Allows subclasses to bind functionality that relies on fully initialized and "ready for action" c
keyReleased(int code)
void
If this Component is focused, the key released event will call this method
boolean
void
boolean
parsingError(int errorId, String tag, String attribute, String value, String desc
void
If this Component is focused, the pointer released event will call this method
Called when the user selects an item in a List inside the HTMLComponent Note: Selection
the items - once the user has actually decided, an ActionEvent will be sent as well This me
only if HTMLComponent.isEventsEnabled() is true
void
setAd(String ad)
void
void
Simple setter of the unique identifier of the app on the ads service network, no need to man
createAdsService uses this.
void
setCategory(String category)
void
void
Sets Gender if applicable can be one of the following: 'F', 'f', 'M', 'm', 'Female', 'female', 'Ma
setHeight(int height)
Sets the Component height, this method is exposed for the purpose of external layout man
be invoked directly.
If a user wishes to effect the component size setPreferredSize should be used.
void
setKeywords(String[] keywords)
void
void
Location string is a comma separated list of country, state/province, city For example: US,
String
Sets a new value to the given property, returns an error message if failed and null if succes
setUpdateDuration(int updateDuration)
void
void
Method Summary
2686
Field Detail
2687
Error code denoting that an unsupported CSS attribute (by XHTML-MP 1.0
standards) was found in the HTML or external CSS files
See Also:
Constant Field Values
ERROR_CSS_ATTIBUTE_VALUE_INVALID
public static final int ERROR_CSS_ATTIBUTE_VALUE_INVALID
Error code denoting that an invalid attribute value was found in the CSS
See Also:
Constant Field Values
ERROR_CSS_NOT_FOUND
public static final int ERROR_CSS_NOT_FOUND
Error code denoting that a CSS file referenced from the HTML or from another
external CSS file was not found
See Also:
Constant Field Values
ERROR_CSS_NO_BASE_URL
public static final int ERROR_CSS_NO_BASE_URL
Error code denoting that a relative URL was referenced from a document with no
base URL (A document that was loaded via setBody/setHTML/setDOM and not via
setPage) In this case the return value of parsingError is not considered - parsing
continues and the resource at the URL (CSS file/image) is ignored
See Also:
Constant Field Values
Constructor Detail
Ads
public Ads()
Parameters:
Method Detail
Field Detail
2688
Allows subclasses to bind functionality that relies on fully initialized and "ready for
action" component state
Overrides:
initComponent in class Component
deinitialize
protected void deinitialize()
Invoked to indicate that the component initialization is being reversed since the
component was detached from the container hierarchy. This allows the component to
deregister animators and cleanup after itself. This method is the opposite of the
initComponent() method.
Overrides:
deinitialize in class Component
animate
public boolean animate()
Allows the animation to reduce "repaint" calls when it returns false. It is called once
for every frame. Frames are defined by the Display class.
Specified by:
animate in interface Animation
Overrides:
animate in class Component
Returns:
true if a repaint is desired or false if no repaint is necessary
keyReleased
public void keyReleased(int code)
If this Component is focused, the key released event will call this method
Overrides:
keyReleased in class Container
Parameters:
code - the key code value to indicate a physical key.
pointerReleased
public void pointerReleased(int x,
int y)
If this Component is focused, the pointer released event will call this method
Overrides:
pointerReleased in class Component
Parameters:
x - the pointer x coordinate
y - the pointer y coordinate
getAd
public String getAd()
Method Detail
2689
Called whenever a field is submitted to a form. This can be used to perform sanity
checks and/or to store values for auto complete.
Specified by:
fieldSubmitted in interface HTMLCallback
Parameters:
htmlC - The HTMLComponent in which this event occured
ta - The TextArea/TextField of this field
actionURL - The action URL of the form
id - The ID of the field
value - The value entered
type - The type of the field, one of the FIELD_* constants
errorMsg - The error message if any error occured (i.e. input validation error)
or null if no error occured
Returns:
The string to submit to the form (Should return value if nothing changed)
getAutoComplete
public String getAutoComplete(HTMLComponent htmlC,
String actionURL,
String id)
Method Detail
2690
Returns properties about the given link to indicate to HTMLComponent how to render
it Note that this method is always called NOT on the EDT thread.
Specified by:
getLinkProperties in interface HTMLCallback
Parameters:
htmlC - The HTMLComponent
url - The Link URL
Returns:
LINK_REGULAR or LINK_VISITED or LINK_FORBIDDEN or a mask of
those
linkClicked
public boolean linkClicked(HTMLComponent htmlC,
String url)
Called when a link is clicked. This can be used to process links that needs
additional/alternate handling than fetching an HTML.
Specified by:
linkClicked in interface HTMLCallback
Parameters:
htmlC - The HTMLComponent
url - The Link URL
Returns:
true if regular link processing should continue, false otherwise
actionPerformed
public void actionPerformed(ActionEvent evt,
HTMLComponent htmlC,
HTMLElement element)
Called when one of the controls in the HTMLComponent obtained focus This method
will be called only if HTMLComponent.isEventsEnabled() is true
Specified by:
focusGained in interface HTMLCallback
Parameters:
Method Detail
2691
event
focusLost
public void focusLost(Component cmp,
HTMLComponent htmlC,
HTMLElement element)
Called when one of the controls in the HTMLComponent lost focus This method will
be called only if HTMLComponent.isEventsEnabled() is true
Specified by:
focusLost in interface HTMLCallback
Parameters:
cmp - The component that triggered the event
htmlC - The HTMLComponent
element - The element associated with the component that triggered the
event
dataChanged
public void dataChanged(int type,
int index,
HTMLComponent htmlC,
TextField textField,
HTMLElement element)
Called when the user types in a TextField inside the HTMLComponent This method
will be called only if HTMLComponent.isEventsEnabled() is true
Specified by:
dataChanged in interface HTMLCallback
Parameters:
type - the type data change; REMOVED, ADDED or CHANGED
index - item index in a list model
htmlC - The HTMLComponent
textField - The TextField that triggerd the event
element - The element associated with the component that triggered the
event (Should be TAG_INPUT with type text/password)
parsingError
public boolean parsingError(int errorId,
String tag,
String attribute,
String value,
String description)
Called when encountering an error while parsing the XML document. When
implementing this, the developer should return true if the error should be ignored and
the document needs to be further parsed, or false to stop parsing and issue an error
to the user Note that this method is always called NOT on the EDT thread.
Specified by:
parsingError in interface ParserCallback
Parameters:
errorId - The error ID, one of the ERROR_* constants
tag - The tag in which the error occured (Can be null for non-tag related
errors)
attribute - The attribute in which the error occured (Can be null for
non-attribute related errors)
value - The value in which the error occured (Can be null for non-value
related errors)
description - A verbal description of the error
Returns:
true to continue parsing, false to stop
selectionChanged
public void selectionChanged(int oldSelected,
int newSelected,
HTMLComponent htmlC,
Method Detail
2692
Called when the user selects an item in a List inside the HTMLComponent Note:
Selection is traversing through the items - once the user has actually decided, an
ActionEvent will be sent as well This method will be called only if
HTMLComponent.isEventsEnabled() is true
Specified by:
selectionChanged in interface HTMLCallback
Parameters:
oldSelected - old selected index in list model
newSelected - new selected index in list model
htmlC - The HTMLComponent
list - The list that triggered the event (Usually a ComboBox but not always)
element - The element associated with the component that triggered the
event (Should be TAG_SELECT)
setHeight
public void setHeight(int height)
Sets the Component height, this method is exposed for the purpose of external layout
managers and should not be invoked directly.
If a user wishes to effect the component size setPreferredSize should be used.
Overrides:
setHeight in class Component
Parameters:
height - the height of the component
See Also:
Component.setPreferredSize(com.codename1.ui.geom.Dimension)
setAppID
public void setAppID(String appId)
Simple setter of the unique identifier of the app on the ads service network, no need
to manually use this the createAdsService uses this.
Parameters:
appId - unique identifier of the app, to gain an appId please refer to
http://console.inner-active.com/iamp/publisher/register?ref_id=affiliate_CodenameOne
getAppID
public String getAppID()
Simple getter of the unique identifier of the app on the ads service network.
Returns:
the app unique identifier.
setGender
public void setGender(String gender)
Sets Gender if applicable can be one of the following: 'F', 'f', 'M', 'm', 'Female',
'female', 'Male', 'male'
Parameters:
gender setKeywords
public void setKeywords(String[] keywords)
Users age
Returns:
the user age
Method Detail
2693
Location string is a comma separated list of country, state/province, city For example:
US, NY, NY
Parameters:
location getLocation
public String getLocation()
Location string is a comma separated list of country, state/province, city For example:
US, NY, NY
Returns:
getPropertyNames
public String[] getPropertyNames()
Matches the property names method (see that method for further details).
Overrides:
getPropertyTypes in class Component
Returns:
the types of the properties
Method Detail
2694
This method is here to workaround an XMLVM array type bug where property types
aren't identified properly, it returns the names of the types using the following type
names:
String,int,double,long,byte,short,char,String[],String[][],byte[],Image,Image[],Object[],ListModel,
Overrides:
getPropertyTypeNames in class Component
Returns:
Array of type names
getPropertyValue
public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI
builder
Overrides:
getPropertyValue in class Component
Parameters:
name - the name of the property
Returns:
the value of said property
setPropertyValue
public String setPropertyValue(String name,
Object value)
Sets a new value to the given property, returns an error message if failed and null if
successful. Notice that some builtin properties such as "$designMode" might be sent
to components to indicate application state.
Overrides:
setPropertyValue in class Component
Parameters:
name - the name of the property
value - new value for the property
Returns:
error message or null
Method Detail
2695
Interface ScanResult
Deprecated.
Use the cn1-codescanner cn1lib.
public interface
Method Summary
Modifier and
Type
Deprecated.
Invoked if the user canceled the scan
void
void
Deprecated.
Called upon a successful scan operation
scanError(int errorCode, String message)
Deprecated.
Invoked if an error occurred during the scanning process
void
Method Detail
scanCompleted
void scanCompleted(String contents,
String formatName,
byte[] rawBytes)
Deprecated.
Called upon a successful scan operation
Parameters:
contents - the contents of the data
formatName - the format of the scan
rawBytes - the bytes of data
scanCanceled
void scanCanceled()
Deprecated.
Invoked if the user canceled the scan
scanError
void scanError(int errorCode,
String message)
Deprecated.
Invoked if an error occurred during the scanning process
Parameters:
errorCode - code
message - descriptive message
Interface ScanResult
2696
Class CodeScanner
java.lang.Object
com.codename1.codescan.CodeScanner
Deprecated.
Use the cn1-codescanner cn1lib.
public abstract class
extends Object
Constructor Summary
Constructor and Description
CodeScanner()
Deprecated.
Method Summary
Modifier and
Type
static
CodeScanner
Deprecated.
Returns the instance of the code scanner, notice that this method is
equivalent to Display.getInstance().getCodeScanner().
scanBarCode(ScanResult callback)
abstract void
Deprecated.
Scans based on the settings in this class and returns the results
scanQRCode(ScanResult callback)
abstract void
Deprecated.
Scans based on the settings in this class and returns the results
Constructor Detail
CodeScanner
public CodeScanner()
Deprecated.
Method Detail
Method Detail
2697
Deprecated.
Returns the instance of the code scanner, notice that this method is equivalent to
Display.getInstance().getCodeScanner().
Returns:
instance of the code scanner
scanQRCode
public abstract void scanQRCode(ScanResult callback)
Deprecated.
Scans based on the settings in this class and returns the results
Parameters:
callback - scan results
scanBarCode
public abstract void scanBarCode(ScanResult callback)
Deprecated.
Scans based on the settings in this class and returns the results
Parameters:
callback - scan results
Method Detail
2698
Interface CustomProperty
All Known Implementing Classes:
CloudImageProperty
Deprecated.
the cloud storage API is no longer supported, we recommend switching to a solution such as
parse4cn1
public interface
Allows adding a custom property to cloud objects, this effectively allows to simulate missing properties
or create properties that don't represent a database entry (e.g. fullName which can be comprised of
joining the firstname and surname together).
Important: The custom property only takes effect if there is no value assigned to the given property!
Method Summary
Modifier and Type
Deprecated.
Returns a property value for the given property name
Object
Method Detail
propertyValue
Object propertyValue(CloudObject obj,
String propertyName)
Deprecated.
Returns a property value for the given property name
Parameters:
obj - the cloud object
propertyName - the name of the property
Returns:
the property value
Interface CustomProperty
2699
Class CloudStorage
java.lang.Object
com.codename1.cloud.CloudStorage
Deprecated.
this API is targeted for removal due to changes in Google App Engine API support
public class
extends Object
The cloud storage class allows developers to use the Codename One cloud based storage API as a
shared database for your application. The database will be visible only to a specific application (based
on author/package definitions).
The calls to this class only become effective as a single batch when commit is sent. The commit can
be synchronous or asynchronous.
Important due to the nature of the underlying object data store queries can only be performed against
an indexed field of which there are 10 hardcoded indexes! Basic data is case sensitive and
queries/sort will be performed in a case sensitive way! In order to work around this create a property
with an identical name that contains the field as lower or upper case in order to query/sort against.
Field Summary
Modifier and
Type
static int
Deprecated.
Return code for methods in this class indicating an empty queue
RETURN_CODE_FAIL_OBJECT_MODIFIED
static int
Deprecated.
Return code for methods in this class indicating a failure due to server side
modification of an object (e.g.
RETURN_CODE_FAIL_PERMISSION_VIOLATION
static int
Deprecated.
Return code for methods in this class indicating a failure due to exceeding
server storage quotas
RETURN_CODE_FAIL_QUOTA_EXCEEDED
static int
Deprecated.
Return code for methods in this class indicating a failure due to exceeding
server storage quotas
RETURN_CODE_FAIL_SERVER_ERROR
static int
Deprecated.
Return code for methods in this class indicating a failure due to generic
server side error
RETURN_CODE_SUCCESS
static int
Deprecated.
Return code for methods in this class indicating a successful operation
Method Summary
Modifier and
Type
int
Method Detail
Deprecated.
Commit works synchronously and returns one of the return codes above to
indicate the status.
2700
Deprecated.
A commit version that works asynchronously and returns one of the return
codes above to indicate the status.
delete(CloudObject cl)
void
void
Deprecated.
Deletes the following object from the cloud storage upon commit
deleteAllCloudFilesBefore(long timestamp, String developerAccount,
String developerPassword)
Deprecated.
this API is currently deprecated due to Googles cloud storage deprection
deleteAllCloudFilesForUser()
void
Deprecated.
this API is currently deprecated due to Googles cloud storage deprection
deleteCloudFile(String fileId)
boolean
Deprecated.
this API is currently deprecated due to Googles cloud storage deprection
fetch(String[] cloudIds)
CloudObject[]
Deprecated.
Fetches the objects from the server.
fetch(String[] cloudIds, CloudResponse<CloudObject[]> response)
void
Deprecated.
Fetches the objects from the server asynchronously.
getInstance()
static
CloudStorage
Deprecated.
Creates an instance of the cloud storage object, only one instance should
be used per application.
getUrlForCloudFileId(String fileId)
String
Deprecated.
this API is currently deprecated due to Googles cloud storage deprection
queryEquals(String type, int index, String value, int page,
int limit, int visibilityScope)
CloudObject[]
Deprecated.
Performs a query to the server finding the objects where the key value is
equal to the given value.
queryEquals(String type, int index, String value, int page,
int limit, int visibilityScope,
CloudResponse<CloudObject[]> response)
void
Deprecated.
Performs a query to the server finding the objects where the key value is
equal to the given value.
queryEqualsCount(String type, int index, String value,
int visibilityScope)
int
Deprecated.
Equivalent to the standard query but just returns the total count of entries
that will be returned
queryEqualsCount(String type, int index, String value,
int visibilityScope, CloudResponse<Integer> response)
void
Deprecated.
Equivalent to the standard query but just returns the total count of entries
that will be returned
queryEqualsKeys(String type, int index, String value, int page,
int limit, int visibilityScope)
String[]
Deprecated.
Equivalent to the standard query but just returns the keys matching the
given query
queryEqualsKeys(String type, int index, String value, int page,
int limit, int visibilityScope, CloudResponse<String[]> response)
void
Deprecated.
Equivalent to the standard query but just returns the keys matching the
given query
CloudObject[]
Method Summary
2701
Deprecated.
Performs a query to the server finding the objects where the key value is
greater than the given value.
queryGreaterThanCount(String type, int index, String value,
int visibilityScope)
int
Deprecated.
Equivalent to the standard query but just returns the total count of entries
that will be returned
queryGreaterThanCount(String type, int index, String value,
int visibilityScope, CloudResponse<Integer> response)
void
Deprecated.
Equivalent to the standard query but just returns the total count of entries
that will be returned
queryLessThan(String type, int index, String value, int page,
int limit, int visibilityScope)
CloudObject[]
Deprecated.
Performs a query to the server finding the objects where the key value is
smaller than the given value.
queryLessThan(String type, int index, String value, int page,
int limit, int visibilityScope,
CloudResponse<CloudObject[]> response)
void
Deprecated.
Performs a query to the server finding the objects where the key value is
smaller than the given value.
queryLessThanCount(String type, int index, String value,
int visibilityScope)
int
Deprecated.
Equivalent to the standard query but just returns the total count of entries
that will be returned
queryLessThanCount(String type, int index, String value,
int visibilityScope, CloudResponse<Integer> response)
void
Deprecated.
Equivalent to the standard query but just returns the total count of entries
that will be returned
querySorted(String type, int index, boolean ascending, int page,
int limit, int visibilityScope)
CloudObject[]
Deprecated.
Performs a query to the server finding the objects where the sort is equal
to the given value.
querySorted(String type, int index, boolean ascending, int page,
int limit, int visibilityScope,
CloudResponse<CloudObject[]> response)
void
Deprecated.
Performs a query to the server finding the objects where the sort is equal
to the given value.
querySortedKeys(String type, int index, boolean ascending,
int page, int limit, int visibilityScope)
String[]
Deprecated.
Performs a query to the server finding the objects where the sort is equal
to the given value and returning the cloud key of these objects.
querySortedKeys(String type, int index, boolean ascending,
int page, int limit, int visibilityScope,
CloudResponse<String[]> response)
void
Deprecated.
Performs a query to the server finding the objects where the sort is equal
to the given value and returning the cloud key of these objects.
int
refresh(CloudObject[] objects)
Deprecated.
Method Summary
2702
Deprecated.
Refresh the given objects with data from the server if they were modified
on the server (this is the asynchronous version of the method).
void
refreshAsync(CloudObject obj)
Deprecated.
Adds the given object to a set of refresh operations in which we don't
really care if the operation is successful
void
rollback()
Deprecated.
Cancels current pending changes
void
save(CloudObject object)
Deprecated.
Adds the given object to the save queue, the operation will only take place
once committed
void
Deprecated.
this API is currently deprecated due to Googles cloud storage deprection
String
String
Deprecated.
this API is currently deprecated due to Googles cloud storage deprection
Field Detail
RETURN_CODE_SUCCESS
public static final int RETURN_CODE_SUCCESS
Deprecated.
Return code for methods in this class indicating a successful operation
See Also:
Constant Field Values
RETURN_CODE_FAIL_OBJECT_MODIFIED
public static final int RETURN_CODE_FAIL_OBJECT_MODIFIED
Deprecated.
Return code for methods in this class indicating a failure due to server side
modification of an object (e.g. different user changed the object)
See Also:
Constant Field Values
RETURN_CODE_FAIL_SERVER_ERROR
public static final int RETURN_CODE_FAIL_SERVER_ERROR
Deprecated.
Return code for methods in this class indicating a failure due to generic server side
error
See Also:
Constant Field Values
RETURN_CODE_FAIL_QUOTA_EXCEEDED
public static final int RETURN_CODE_FAIL_QUOTA_EXCEEDED
Deprecated.
2703
Deprecated.
Return code for methods in this class indicating an empty queue
See Also:
Constant Field Values
RETURN_CODE_FAIL_PERMISSION_VIOLATION
public static final int RETURN_CODE_FAIL_PERMISSION_VIOLATION
Deprecated.
Return code for methods in this class indicating a failure due to exceeding server
storage quotas
See Also:
Constant Field Values
Method Detail
getInstance
public static CloudStorage getInstance()
Deprecated.
Creates an instance of the cloud storage object, only one instance should be used
per application. This method is important since it may block to complete/cleanup a
previous transaction that wasn't fully completed before exiting the application.
Returns:
the instance of the class
save
public void save(CloudObject object)
Deprecated.
Adds the given object to the save queue, the operation will only take place once
committed
Parameters:
object - the object to save into the cloud, new objects are inserted. existing
objects are updated
delete
public void delete(CloudObject cl)
Deprecated.
Deletes the following object from the cloud storage upon commit
Parameters:
cl - the cloud object to delete
refresh
public void refresh(CloudObject[] objects,
CloudResponse<Integer> response)
Deprecated.
Refresh the given objects with data from the server if they were modified on the
server (this is the asynchronous version of the method). This operation executes
immeditely without waiting for commit.
Parameters:
objects - objects to refresh
response - object for the response
Field Detail
2704
Deprecated.
Adds the given object to a set of refresh operations in which we don't really care if the
operation is successful
Parameters:
obj - the object to refresh
refresh
public int refresh(CloudObject[] objects)
Deprecated.
Refresh the given objects with data from the server if they were modified on the
server. This operation executes immeditely without waiting for commit.
Parameters:
objects - objects to refresh
Returns:
status code matching the situation, one of: RETURN_CODE_SUCCESS,
RETURN_CODE_FAIL_SERVER_ERROR
fetch
public CloudObject[] fetch(String[] cloudIds)
throws CloudException
Deprecated.
Fetches the objects from the server. This operation executes immeditely without
waiting for commit.
Parameters:
cloudIds - the object id's to fetch
Returns:
the cloud objects or null if a server error occurred
Throws:
CloudException - thrown for a server side/connection error
fetch
public void fetch(String[] cloudIds,
CloudResponse<CloudObject[]> response)
Deprecated.
Fetches the objects from the server asynchronously. This operation executes
immeditely without waiting for commit.
Parameters:
cloudIds - the object id's to fetch
response - returns the response from the server
queryEquals
public CloudObject[] queryEquals(String type,
int index,
String value,
int page,
int limit,
int visibilityScope)
throws CloudException
Deprecated.
Performs a query to the server finding the objects where the key value is equal to the
given value. This operation executes immeditely without waiting for commit.
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
page - the page of responses (allows for paging)
limit - number of responses to fetch
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
Returns:
Method Detail
2705
querySorted
public CloudObject[] querySorted(String type,
int index,
boolean ascending,
int page,
int limit,
int visibilityScope)
throws CloudException
Deprecated.
Performs a query to the server finding the objects where the sort is equal to the given
value. This operation executes immeditely without waiting for commit.
Parameters:
type - the object type
index - the index on which the sort is based
ascending - indicates if the sort order is ascending or descending
page - the page of responses (allows for paging)
limit - number of responses to fetch
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
Returns:
array of objects matching the query
Throws:
CloudException - thrown for a server side/connection error
querySortedKeys
public String[] querySortedKeys(String type,
int index,
boolean ascending,
int page,
int limit,
int visibilityScope)
throws CloudException
Deprecated.
Performs a query to the server finding the objects where the sort is equal to the given
value and returning the cloud key of these objects. This operation executes
immeditely without waiting for commit.
Parameters:
type - the object type
index - the index on which the sort is based
ascending - indicates if the sort order is ascending or descending
page - the page of responses (allows for paging)
limit - number of responses to fetch
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
Returns:
the keys for the cloud objects matching the query
Throws:
CloudException - thrown for a server side/connection error
queryEqualsKeys
public String[] queryEqualsKeys(String type,
int index,
String value,
int page,
int limit,
int visibilityScope)
throws CloudException
Deprecated.
Equivalent to the standard query but just returns the keys matching the given query
Parameters:
type - the object type
index - the index to query for the given value
Method Detail
2706
the
Deprecated.
Equivalent to the standard query but just returns the total count of entries that will be
returned
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
Returns:
the number of elements
Throws:
CloudException - thrown for a server side/connection error
queryGreaterThanCount
public int queryGreaterThanCount(String type,
int index,
String value,
int visibilityScope)
throws CloudException
Deprecated.
Equivalent to the standard query but just returns the total count of entries that will be
returned
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
Returns:
the number of elements
Throws:
CloudException - thrown for a server side/connection error
queryLessThanCount
public int queryLessThanCount(String type,
int index,
String value,
int visibilityScope)
throws CloudException
Deprecated.
Equivalent to the standard query but just returns the total count of entries that will be
returned
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
Method Detail
2707
Deprecated.
Performs a query to the server finding the objects where the key value is greater than
the given value. This operation executes immeditely without waiting for commit.
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
page - the page of responses (allows for paging)
limit - number of responses to fetch
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
Returns:
array of objects matching the query
Throws:
CloudException - thrown for a server side/connection error
queryLessThan
public CloudObject[] queryLessThan(String type,
int index,
String value,
int page,
int limit,
int visibilityScope)
throws CloudException
Deprecated.
Performs a query to the server finding the objects where the key value is smaller than
the given value. This operation executes immeditely without waiting for commit.
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
page - the page of responses (allows for paging)
limit - number of responses to fetch
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
Returns:
array of objects matching the query
Throws:
CloudException - thrown for a server side/connection error
querySorted
public void querySorted(String type,
int index,
boolean ascending,
int page,
int limit,
int visibilityScope,
CloudResponse<CloudObject[]> response)
Deprecated.
Performs a query to the server finding the objects where the sort is equal to the given
value. This operation executes immeditely without waiting for commit.
Parameters:
type - the object type
Method Detail
2708
Deprecated.
Performs a query to the server finding the objects where the key value is equal to the
given value. This operation executes immeditely without waiting for commit.
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
page - the page of responses (allows for paging)
limit - number of responses to fetch
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
queryEqualsCount
public void queryEqualsCount(String type,
int index,
String value,
int visibilityScope,
CloudResponse<Integer> response)
Deprecated.
Equivalent to the standard query but just returns the total count of entries that will be
returned
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
queryGreaterThanCount
public void queryGreaterThanCount(String type,
int index,
String value,
int visibilityScope,
CloudResponse<Integer> response)
Deprecated.
Equivalent to the standard query but just returns the total count of entries that will be
returned
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
querySortedKeys
public void querySortedKeys(String type,
int index,
boolean ascending,
int page,
int limit,
int visibilityScope,
CloudResponse<String[]> response)
Method Detail
2709
Deprecated.
Equivalent to the standard query but just returns the keys matching the given query
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
page - the page of responses (allows for paging)
limit - number of responses to fetch
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
queryLessThanCount
public void queryLessThanCount(String type,
int index,
String value,
int visibilityScope,
CloudResponse<Integer> response)
Deprecated.
Equivalent to the standard query but just returns the total count of entries that will be
returned
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
queryGreaterThan
public void queryGreaterThan(String type,
int index,
String value,
int page,
int limit,
int visibilityScope,
CloudResponse<CloudObject[]> response)
Deprecated.
Performs a query to the server finding the objects where the key value is greater than
the given value. This operation executes immeditely without waiting for commit.
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
page - the page of responses (allows for paging)
limit - number of responses to fetch
Method Detail
2710
Deprecated.
Performs a query to the server finding the objects where the key value is smaller than
the given value. This operation executes immeditely without waiting for commit.
Parameters:
type - the object type
index - the index to query for the given value
value - the value of said index to include in the response object
page - the page of responses (allows for paging)
limit - number of responses to fetch
visibilityScope - indicates the scope in which to look as one of the
CloudObject constants ACCESS_*
response - array of objects matching the query
uploadCloudFile
public String uploadCloudFile(String mimeType,
String file)
throws CloudException,
IOException
Deprecated. this API is currently deprecated due to Googles cloud storage deprection
Allows uploading of images etc. to the cloud which can later on be referenced as
URL's.
Parameters:
mimeType - the mimetype of the uploaded file
file - the URL of the local file
Returns:
an ID for the given file that can be used to delete the file or construct a URL
of the file
Throws:
CloudException - in case of a server side error
IOException - when a problem occurs with the file
uploadCloudFile
public String uploadCloudFile(String mimeType,
String filename,
InputStream data,
int dataSize)
throws CloudException,
IOException
Deprecated. this API is currently deprecated due to Googles cloud storage deprection
Allows uploading of images etc. to the cloud which can later on be referenced as
URL's.
Parameters:
mimeType - the mimetype of the uploaded file
filename - a short name for the file uploaded (not a full path)
data - input stream from which to read the file
dataSize - the size in bytes of the input stream (this is essential for file upload
to work on all devices!)
Returns:
an ID for the given file that can be used to delete the file or construct a URL
of the file
Throws:
CloudException - in case of a server side error
IOException - when a problem occurs with the file
Method Detail
2711
Deprecated. this API is currently deprecated due to Googles cloud storage deprection
Deletes a file from the cloud storage
Parameters:
fileId - the file id to delete
Returns:
true if the operation was successful
deleteAllCloudFilesForUser
public void deleteAllCloudFilesForUser()
Deprecated. this API is currently deprecated due to Googles cloud storage deprection
Deletes all the cloud files under this user, notice that this method is asynchronous
and a background server process performs the actual deletion
deleteAllCloudFilesBefore
public void deleteAllCloudFilesBefore(long timestamp,
String developerAccount,
String developerPassword)
Deprecated. this API is currently deprecated due to Googles cloud storage deprection
Deletes all the cloud files before the given time stamp for the given development
account. Notice that this method is meant for internal use and not for distributable
apps since it includes your developer account. This method works in a background
server process and returns immediately.
Parameters:
timestamp - the timestamp since epoch (as in System.currentTimemillis).
developerAccount - your developer email
developerPassword - your developer password
getUrlForCloudFileId
public String getUrlForCloudFileId(String fileId)
Deprecated. this API is currently deprecated due to Googles cloud storage deprection
Converts a file id to a URL with which the file can be downloaded, notice that the file
URL is world readable!
Parameters:
fileId - the file ID
Returns:
a URL that allows downloading the file
commit
public int commit()
Deprecated.
Commit works synchronously and returns one of the return codes above to indicate
the status.
Returns:
status code from the constants in this class
commit
public void commit(CloudResponse<Integer> response)
Deprecated.
A commit version that works asynchronously and returns one of the return codes
above to indicate the status.
Parameters:
response - response code with status code from the constants in this class
rollback
public void rollback()
Deprecated.
Cancels current pending changes
Method Detail
2712
Interface CloudResponse<T>
Deprecated.
the cloud storage API is no longer supported, we recommend switching to a solution such as
parse4cn1
public interface
Used as a callback for the asynchronous version of the cloud storage API, these methods are invoked
on the EDT!
Method Summary
Modifier and Type
Deprecated.
Invoked if there was a server error
void
onSuccess(T returnValue)
Deprecated.
Invoked to return a value from the asynchronous version of the API
void
Method Detail
onSuccess
void onSuccess(T returnValue)
Deprecated.
Invoked to return a value from the asynchronous version of the API
Parameters:
returnValue - the return value of the metho
onError
void onError(CloudException err)
Deprecated.
Invoked if there was a server error
Parameters:
err - the exception containing the error details
Interface CloudResponse<T>
2713
Class CloudPersona
java.lang.Object
com.codename1.cloud.CloudPersona
Deprecated.
the cloud storage API is no longer supported, we recommend switching to a solution such as
parse4cn1
public class
extends Object
A persona represents a user of the cloud, this is an optional feature that allows data to be limited to a
specific user on the server side.
Method Summary
Modifier and
Type
static boolean
Deprecated.
Creates an anonymous persona that will be unique in the cloud, NEVER
logout an anonymous user!
createFromToken(String token)
static void
Deprecated.
Initializes the persona based on a token, since this method assumes binary
transfer of a completed token the token isn't verified in any way and the
user is considered logged in.
createOrLogin(String login, String password)
static boolean
Deprecated.
Creates a new user if a user isn't occupying the given login already, if the
user exists performs a login operation.
getCurrentPersona()
static
CloudPersona
Deprecated.
This method returns the currently logged in persona or a blank persona
(token would be null)
getToken()
Deprecated.
Returns a unique login token that represents the current user and his
password, while this login token shouldn't be user visible (it's a password
too!) it can be transfered to a different device to give them both identical
user role and joined access.
String
logout()
Deprecated.
Logs out the current user, notice that with an anonymous user this will
effectively KILL all the data in the cloud!
void
Method Detail
Method Detail
2714
Deprecated.
This method returns the currently logged in persona or a blank persona (token would
be null)
Returns:
the current persona
getToken
public String getToken()
Deprecated.
Returns a unique login token that represents the current user and his password, while
this login token shouldn't be user visible (it's a password too!) it can be transfered to a
different device to give them both identical user role and joined access.
Returns:
a persona UID
createFromToken
public static void createFromToken(String token)
Deprecated.
Initializes the persona based on a token, since this method assumes binary transfer
of a completed token the token isn't verified in any way and the user is considered
logged in.
Parameters:
token - the token
createAnonymous
public static boolean createAnonymous()
Deprecated.
Creates an anonymous persona that will be unique in the cloud, NEVER logout an
anonymous user!
Returns:
false in case login failed e.g. due to bad network connection
createOrLogin
public static boolean createOrLogin(String login,
String password)
Deprecated.
Creates a new user if a user isn't occupying the given login already, if the user exists
performs a login operation.
Parameters:
login - a user name
password - a password
Returns:
true if the login is successful false otherwise
logout
public void logout()
Deprecated.
Logs out the current user, notice that with an anonymous user this will effectively
KILL all the data in the cloud!
Method Detail
2715
Class CloudObject
java.lang.Object
com.codename1.cloud.CloudObject
All Implemented Interfaces:
Externalizable
Deprecated.
the cloud storage API is no longer supported, we recommend switching to a solution such as
parse4cn1
public final class
extends Object
implements Externalizable
A cloud object can be persisted to the cloud or locally it is a set of key/value pairs that can be either
strings or numbers. There is a 512 character limit on string length! Notice: keys starting with CN1 are
reserved for internal usage!
Field Summary
Modifier
and Type
static int
Deprecated.
An application visible/modifiable object!
ACCESS_APPLICATION_READ_ONLY
static int
Deprecated.
An application scope readable object! Can only be modified by its creator
ACCESS_PRIVATE
static int
Deprecated.
An object that can only be viewed or modified by its creator
ACCESS_PUBLIC
static int
Deprecated.
A world visible/modifiable object!
ACCESS_PUBLIC_READ_ONLY
static int
Deprecated.
A world visible object! Can only be modified by its creator.
BINDING_AUTO_SAVE
static int
Deprecated.
Changes to the bound property will be reflected instantly into the cloud object
and the object would be saved immediately (not committed!).
BINDING_DEFERRED
static int
Deprecated.
Changes to the bound property won't be reflected into the bound cloud object
until commit binding is invoked
BINDING_IMMEDIATE
static int
Deprecated.
Changes to the bound property will be reflected instantly into the cloud object
STATUS_COMMIT_IN_PROGRESS
static int
Deprecated.
Indicates the state of the current object, an object in the process of committing
STATUS_COMMITTED
static int
static int
Class CloudObject
Deprecated.
Indicates the state of the current object, an object that is in sync with the
database as far as the client code is aware (the client code doesn't check!)
STATUS_DELETE_IN_PROGRESS
2716
Deprecated.
Indicates the state of the current object, a deleted object
static int
STATUS_MODIFIED
Deprecated.
Indicates the state of the current object, a locally modified object that wasn't
committed yet
static int
STATUS_NEW
Deprecated.
Indicates the state of the current object, a new object never persisted
static int
STATUS_REFRESH_IN_PROGRESS
Deprecated.
Indicates the state of the current object, an object in the process of refresh
static int
Constructor Summary
Constructor and Description
CloudObject()
Deprecated.
Default constructor for externalization purposes only!
CloudObject(String type)
Deprecated.
Constructor
CloudObject(String type, int permissions)
Deprecated.
Create an object with different permissions settings
Method Summary
Modifier
and Type
void
Deprecated.
Binds a property value within the given component to this cloud object, this
means that when the component changes the cloud object changes unless
deferred.
bindTree(Container ui, int defer, boolean objectLead)
void
Deprecated.
Binds a UI tree to the cloud object so its values automatically update in the
cloud object
cancelBinding()
void
Deprecated.
If deferred changes exist this method discards such values
commitBinding()
void
Deprecated.
If deferred changes exist this method applies these changes to the data
equals(Object o)
boolean
Deprecated.
Indicates whether some other object is "equal to" this one.
externalize(DataOutputStream out)
void
int
Field Summary
Deprecated.
Allows us to store an object state, this method must be implemented in order to
save the state of an object
getAccessPermissions()
2717
Deprecated.
Returns the value for the given key
getCloudId()
String
Deprecated.
The object id is a unique key that allows you to find an object that was persisted
in the store (a primary key).
getDouble(String key)
Double
Deprecated.
Returns the value for the given key
getFloat(String key)
Float
Deprecated.
Returns the value for the given key
getIndexDouble(int index)
Double
Deprecated.
Returns the index value for the given index number
getIndexLong(int index)
Long
Deprecated.
Returns the index value for the given index number
getIndexString(int index)
String
Deprecated.
Returns the index value for the given index number
getInteger(String key)
Integer
Deprecated.
Returns the value for the given key
getLastModified()
long
Deprecated.
Indicates the last modification date for the object
getLong(String key)
Long
Deprecated.
Returns the value for the given key
getObject(String key)
Object
Deprecated.
Allows us to extract an object from the cloud object without knowing its type in
advance or whether it exists
getObjectId()
String
Deprecated.
The object id must be unique, it is used to identify the object when loaded even
when it is obfuscated.
getStatus()
int
Deprecated.
Returns one of the status constants in this class
getString(String key)
String
Deprecated.
Returns the value for the given key
getType()
String
Deprecated.
Returns the type of the object
getVersion()
int
Deprecated.
Returns the version for the current persistance code, the version will be pased
to internalized thus allowing the internalize method to recognize classes
persisted in older revisions
hashCode()
int
Deprecated.
Returns a hash code value for the object.
void
Method Summary
2718
Deprecated.
Returns true if this object is owned by me or is world writeable
remove(String key)
void
Deprecated.
Delete an entry within the object
setBoolean(String key, boolean value)
void
Deprecated.
Sets a value
setBoolean(String key, Boolean value)
void
static
void
Deprecated.
Sets a value
setCustomProperty(String key, CustomProperty cp)
Deprecated.
Install a custom property on the given property name
setDouble(String key, double value)
void
Deprecated.
Sets a value
setDouble(String key, Double value)
void
Deprecated.
Sets a value
setFloat(String key, float value)
void
Deprecated.
Sets a value
setFloat(String key, Float value)
void
Deprecated.
Sets a value
setIndexDouble(int index, double value)
void
Deprecated.
Only indexed values can be queried and sorted
setIndexLong(int index, long value)
void
Deprecated.
Only indexed values can be queried and sorted
setIndexString(int index, String value)
void
Deprecated.
Only indexed values can be queried and sorted
setInteger(String key, int value)
void
Deprecated.
Sets a value
setInteger(String key, Integer value)
void
Deprecated.
Sets a value
setLong(String key, long value)
void
Deprecated.
Sets a value
setLong(String key, Long value)
void
Deprecated.
Sets a value
setString(String key, String value)
void
Deprecated.
Sets a value that can be no more than 512 characters
setType(String type)
void
Deprecated.
Set the type of the object
unbindProperty(Component cmp, String propertyName)
void
Deprecated.
Releases the binding for the specific property name
void
unbindTree(Container ui)
Method Summary
2719
Field Detail
STATUS_NEW
public static final int STATUS_NEW
Deprecated.
Indicates the state of the current object, a new object never persisted
See Also:
Constant Field Values
STATUS_COMMITTED
public static final int STATUS_COMMITTED
Deprecated.
Indicates the state of the current object, an object that is in sync with the database as
far as the client code is aware (the client code doesn't check!)
See Also:
Constant Field Values
STATUS_MODIFIED
public static final int STATUS_MODIFIED
Deprecated.
Indicates the state of the current object, a locally modified object that wasn't
committed yet
See Also:
Constant Field Values
STATUS_COMMIT_IN_PROGRESS
public static final int STATUS_COMMIT_IN_PROGRESS
Deprecated.
Indicates the state of the current object, an object in the process of committing
See Also:
Constant Field Values
STATUS_DELETE_IN_PROGRESS
public static final int STATUS_DELETE_IN_PROGRESS
Deprecated.
Indicates the state of the current object, an object that is in the process of deletion
See Also:
Constant Field Values
STATUS_DELETED
public static final int STATUS_DELETED
Deprecated.
Indicates the state of the current object, a deleted object
See Also:
Constant Field Values
STATUS_REFRESH_IN_PROGRESS
public static final int STATUS_REFRESH_IN_PROGRESS
Deprecated.
2720
Deprecated.
A world visible/modifiable object!
See Also:
Constant Field Values
ACCESS_PUBLIC_READ_ONLY
public static final int ACCESS_PUBLIC_READ_ONLY
Deprecated.
A world visible object! Can only be modified by its creator.
See Also:
Constant Field Values
ACCESS_APPLICATION
public static final int ACCESS_APPLICATION
Deprecated.
An application visible/modifiable object!
See Also:
Constant Field Values
ACCESS_APPLICATION_READ_ONLY
public static final int ACCESS_APPLICATION_READ_ONLY
Deprecated.
An application scope readable object! Can only be modified by its creator
See Also:
Constant Field Values
ACCESS_PRIVATE
public static final int ACCESS_PRIVATE
Deprecated.
An object that can only be viewed or modified by its creator
See Also:
Constant Field Values
BINDING_DEFERRED
public static final int BINDING_DEFERRED
Deprecated.
Changes to the bound property won't be reflected into the bound cloud object until
commit binding is invoked
See Also:
Constant Field Values
BINDING_IMMEDIATE
public static final int BINDING_IMMEDIATE
Deprecated.
Changes to the bound property will be reflected instantly into the cloud object
See Also:
Constant Field Values
BINDING_AUTO_SAVE
public static final int BINDING_AUTO_SAVE
Deprecated.
Changes to the bound property will be reflected instantly into the cloud object and the
object would be saved immediately (not committed!).
Field Detail
2721
Constructor Detail
CloudObject
public CloudObject()
Deprecated.
Default constructor for externalization purposes only!
CloudObject
public CloudObject(String type)
Deprecated.
Constructor
Parameters:
type - the type of the object
CloudObject
public CloudObject(String type,
int permissions)
Deprecated.
Create an object with different permissions settings
Parameters:
type - the type of the object
permissions - one of the ACCESS_* values
Method Detail
getStatus
public int getStatus()
Deprecated.
Returns one of the status constants in this class
Returns:
the status of the object against the cloud
setType
public void setType(String type)
Deprecated.
Set the type of the object
Parameters:
type - the type of the field
getType
public String getType()
Deprecated.
Returns the type of the object
Returns:
the type of the object
setIndexString
public void setIndexString(int index,
String value)
Deprecated.
Only indexed values can be queried and sorted
Parameters:
index - the index which must be a value between 1 and 10.
Constructor Detail
2722
Deprecated.
Returns the index value for the given index number
Parameters:
index - the index number
Returns:
the value of this entry for that index as a String
setIndexLong
public void setIndexLong(int index,
long value)
Deprecated.
Only indexed values can be queried and sorted
Parameters:
index - the index which must be a value between 1 and 10.
value - the value for the given index
getIndexLong
public Long getIndexLong(int index)
Deprecated.
Returns the index value for the given index number
Parameters:
index - the index number
Returns:
the value of this entry for that index as a Long value
setIndexDouble
public void setIndexDouble(int index,
double value)
Deprecated.
Only indexed values can be queried and sorted
Parameters:
index - the index which must be a value between 1 and 10.
value - the value for the given index
getIndexDouble
public Double getIndexDouble(int index)
Deprecated.
Returns the index value for the given index number
Parameters:
index - the index number
Returns:
the value of this entry for that index as a Double value
isOwner
public boolean isOwner()
Deprecated.
Returns true if this object is owned by me or is world writeable
Returns:
ownership status
getCloudId
public String getCloudId()
Deprecated.
The object id is a unique key that allows you to find an object that was persisted in
the store (a primary key). When it is null the object is effectively unsynchronized!
Returns:
Method Detail
2723
Deprecated.
Indicates the last modification date for the object
Returns:
the last modification date
getObject
public Object getObject(String key)
Deprecated.
Allows us to extract an object from the cloud object without knowing its type in
advance or whether it exists
Parameters:
key - the key for the object
Returns:
the value of the object
setCustomProperty
public static void setCustomProperty(String key,
CustomProperty cp)
Deprecated.
Install a custom property on the given property name
Parameters:
key - the key on which to install the custom property
cp - the custom property implementation
setString
public void setString(String key,
String value)
Deprecated.
Sets a value that can be no more than 512 characters
Parameters:
key - the key for the given value
value - the value
getString
public String getString(String key)
Deprecated.
Returns the value for the given key
Parameters:
key - the key
Returns:
a string value
remove
public void remove(String key)
Deprecated.
Delete an entry within the object
Parameters:
key - the key to remove from the object
setLong
public void setLong(String key,
long value)
Deprecated.
Sets a value
Parameters:
key - the key for the given value
Method Detail
2724
- the value
setLong
public void setLong(String key,
Long value)
Deprecated.
Sets a value
Parameters:
key - the key for the given value
value - the value
getLong
public Long getLong(String key)
Deprecated.
Returns the value for the given key
Parameters:
key - the key
Returns:
a long value
setInteger
public void setInteger(String key,
int value)
Deprecated.
Sets a value
Parameters:
key - the key for the given value
value - the value
setInteger
public void setInteger(String key,
Integer value)
Deprecated.
Sets a value
Parameters:
key - the key for the given value
value - the value
getInteger
public Integer getInteger(String key)
Deprecated.
Returns the value for the given key
Parameters:
key - the key
Returns:
a value
setDouble
public void setDouble(String key,
double value)
Deprecated.
Sets a value
Parameters:
key - the key for the given value
value - the value
setDouble
public void setDouble(String key,
Double value)
Deprecated.
Sets a value
Method Detail
2725
Deprecated.
Returns the value for the given key
Parameters:
key - the key
Returns:
a value
setFloat
public void setFloat(String key,
float value)
Deprecated.
Sets a value
Parameters:
key - the key for the given value
value - the value
setFloat
public void setFloat(String key,
Float value)
Deprecated.
Sets a value
Parameters:
key - the key for the given value
value - the value
getFloat
public Float getFloat(String key)
Deprecated.
Returns the value for the given key
Parameters:
key - the key
Returns:
a value
setBoolean
public void setBoolean(String key,
boolean value)
Deprecated.
Sets a value
Parameters:
key - the key for the given value
value - the value
setBoolean
public void setBoolean(String key,
Boolean value)
Deprecated.
Sets a value
Parameters:
key - the key for the given value
value - the value
Method Detail
2726
Deprecated.
Returns the value for the given key
Parameters:
key - the key
Returns:
a value
getVersion
public int getVersion()
Deprecated.
Returns the version for the current persistance code, the version will be pased to
internalized thus allowing the internalize method to recognize classes persisted in
older revisions
Specified by:
getVersion in interface Externalizable
Returns:
version number for the persistant code
externalize
public void externalize(DataOutputStream out)
throws IOException
Deprecated.
Allows us to store an object state, this method must be implemented in order to save
the state of an object
Specified by:
externalize in interface Externalizable
Parameters:
out - the stream into which the object must be serialized
Throws:
IOException - the method may throw an exception
getObjectId
public String getObjectId()
Deprecated.
Description copied from interface: Externalizable
The object id must be unique, it is used to identify the object when loaded even when
it is obfuscated.
Specified by:
getObjectId in interface Externalizable
Returns:
a unique id
internalize
public void internalize(int version,
DataInputStream in)
throws IOException
Deprecated.
Loads the object from the input stream and allows deserialization
Specified by:
internalize in interface Externalizable
Parameters:
version - the version the class returned during the externalization processs
in - the input stream used to load the class
Throws:
IOException - the method may throw an exception
Method Detail
2727
Deprecated.
The access permissions for an object can only be changed for an object in which the
current user is the owner
Returns:
the accessPermissions
equals
public boolean equals(Object o)
Deprecated.
Indicates whether some other object is "equal to" this one. The equals method
implements an equivalence relation: It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for
any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true. It is consistent: for any reference values x
and y, multiple invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons on the object is
modified. For any non-null reference value x, x.equals(null) should return false. The
equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any reference values x and y, this method
returns true if and only if x and y refer to the same object (x==y has the value true).
Overrides:
equals in class Object
hashCode
public int hashCode()
Deprecated.
Returns a hash code value for the object. This method is supported for the benefit of
hashtables such as those provided by java.util.Hashtable. The general contract of
hashCode is: Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application. If two objects are equal
according to the equals(Object) method, then calling the hashCode method on each
of the two objects must produce the same integer result. It is not required that if two
objects are unequal according to the equals(java.lang.Object) method, then calling
the hashCode method on each of the two objects must produce distinct integer
results. However, the programmer should be aware that producing distinct integer
results for unequal objects may improve the performance of hashtables. As much as
is reasonably practical, the hashCode method defined by class Object does return
distinct integers for distinct objects. (This is typically implemented by converting the
internal address of the object into an integer, but this implementation technique is not
required by the JavaTM programming language.)
Overrides:
hashCode in class Object
bindTree
public void bindTree(Container ui,
int defer,
boolean objectLead)
Deprecated.
Binds a UI tree to the cloud object so its values automatically update in the cloud
object
Parameters:
ui - the component tree to bind
defer - bind settings whether to defer the binding which requires developers
to explicitly commit the binding to perform the changes
objectLead - if set to true the UI property is initialized from values in the
CloudObject, if false the cloud object property is initialized from the UI
Method Detail
2728
Deprecated.
Clears the binding to this component tree
Parameters:
ui - the container whose children might be bound
bindProperty
public void bindProperty(Component cmp,
String propertyName,
String attributeName,
int defer,
boolean objectLead)
Deprecated.
Binds a property value within the given component to this cloud object, this means
that when the component changes the cloud object changes unless deferred. If the
defer flag is false all changes are stored in a temporary location and only "committed"
once commitBindings() is invoked.
Parameters:
cmp - the component to bind
propertyName - the name of the property in the bound component
attributeName - the key within the cloud object
defer - bind settings whether to defer the binding which requires developers
to explicitly commit the binding to perform the changes
objectLead - if set to true the UI property is initialized from values in the
CloudObject, if false the cloud object property is initialized from the UI
unbindProperty
public void unbindProperty(Component cmp,
String propertyName)
Deprecated.
Releases the binding for the specific property name
Parameters:
cmp - the component
propertyName - the name of the property
commitBinding
public void commitBinding()
Deprecated.
If deferred changes exist this method applies these changes to the data
cancelBinding
public void cancelBinding()
Deprecated.
If deferred changes exist this method discards such values
Method Detail
2729
Class CloudListModel
java.lang.Object
com.codename1.cloud.CloudListModel
All Implemented Interfaces:
ListModel
Deprecated.
the cloud storage API is no longer supported, we recommend switching to a solution such as
parse4cn1
public class
extends Object
implements ListModel
Constructor Summary
Constructor and Description
CloudListModel(String type, int visibilityScope, int sortProperty,
boolean ascending)
Deprecated.
Creates a list model that shows all the cloud elements that have the given key matching the
given value at the visibility scope listed bellow.
CloudListModel(String type, int visibilityScope, int index, String queryValue,
boolean ascending)
Deprecated.
Creates a list model that shows all the cloud elements that have the given key matching the
given value at the visibility scope listed bellow.
Method Summary
Modifier
and Type
void
Deprecated.
Invoked to indicate interest in future change events
addItem(Object item)
void
Deprecated.
Notice this method does NOT commit the data, after committing the data the
cache MUST be cleared! Adds the specified item to the end of this list.
addSelectionListener(SelectionListener l)
void
Deprecated.
Invoked to indicate interest in future selection events
clearCache()
void
Deprecated.
Flushes the cache which might be essential when adding new elements
getBatchSize()
int
Deprecated.
Returns the batch size fetched from the server
getCacheSize()
int
Deprecated.
Returns the elements cached within the implementation
Object
getItemAt(int index)
Deprecated.
Class CloudListModel
2730
Deprecated.
When loading the element from the cloud a placehold is shown to indicate to
the user that the content isn't fully here
getRefreshRateMillis()
Deprecated.
Indicates the rate in milliseconds in which to poll the server for the current data
of elements that are visible at the moment.
int
getSelectedIndex()
Deprecated.
Returns the selected list offset
int
getSize()
Deprecated.
Returns the number of items in the list
int
getStorageCacheSize()
Deprecated.
Returns the elements cached within the persistent storage
int
protected
void
onError(CloudException err)
Deprecated.
Invoked when a cloud error occurs
refresh()
Deprecated.
Refreshes the list from the server, this method blocks the EDT until completion.
void
removeDataChangedListener(DataChangedListener l)
Deprecated.
Invoked to indicate no further interest in future change events
void
removeItem(int index)
Deprecated.
Notice this method does NOT commit the data, after committing the data the
cache MUST be cleared! Removes the item at the specified position in this list.
void
removeSelectionListener(SelectionListener l)
Deprecated.
Invoked to indicate no further interest in future selection events
void
setBatchSize(int batchSize)
Deprecated.
Updates the number of elements fetched from the server in a single batch
void
setCacheSize(int elements)
Deprecated.
Sets the size of the local cache
void
setLoadingPlaceholder(Hashtable loadingPlaceholder)
Deprecated.
When loading the element from the cloud a placehold is shown to indicate to
the user that the content isn't fully here
void
setRefreshRateMillis(int refreshRateMillis)
Deprecated.
Indicates the rate in milliseconds in which to poll the server for the current data
of elements that are visible at the moment.
void
setSelectedIndex(int index)
Deprecated.
Sets the selected list offset can be set to -1 to clear selection
void
setStorageCacheSize(int elements)
Deprecated.
Sets the size of the cache in persistent storage
void
Method Summary
2731
Detail
CloudListModel
public CloudListModel(String type,
int visibilityScope,
int sortProperty,
boolean ascending)
Deprecated.
Creates a list model that shows all the cloud elements that have the given key
matching the given value at the visibility scope listed bellow. This model can be
further narrowed down by using the filter functionality bellow.
This is effectively equivalent to issuing a queryEquals method, however it polls in
batches and caches data as needed.
Parameters:
type - the type of object shown on the list
visibilityScope - the scope of the list (CloudObject.ACCESS_* values)
sortProperty - the index by which we sort the entries, 0 for unsorted
ascending - whether the sort is ascending or descending
CloudListModel
public CloudListModel(String type,
int visibilityScope,
int index,
String queryValue,
boolean ascending)
Deprecated.
Creates a list model that shows all the cloud elements that have the given key
matching the given value at the visibility scope listed bellow. This model can be
further narrowed down by using the filter functionality bellow.
This is effectively equivalent to issuing a queryEquals method, however it polls in
batches and caches data as needed.
Parameters:
type - the type of object shown on the list
visibilityScope - the scope of the list (CloudObject.ACCESS_* values)
index - the index by which we limit the entries
queryValue - the queryValue for the given index
ascending - whether the sort is ascending or descending
Method Detail
refresh
public void refresh()
Deprecated.
Refreshes the list from the server, this method blocks the EDT until completion.
clearCache
public void clearCache()
Deprecated.
Flushes the cache which might be essential when adding new elements
setCacheSize
public void setCacheSize(int elements)
Deprecated.
Sets the size of the local cache
Parameters:
elements - elements to store in cache
Constructor Detail
2732
Deprecated.
Returns the elements cached within the implementation
Returns:
the cache size
setStorageCacheSize
public void setStorageCacheSize(int elements)
Deprecated.
Sets the size of the cache in persistent storage
Parameters:
elements - elements to store in cache
getStorageCacheSize
public int getStorageCacheSize()
Deprecated.
Returns the elements cached within the persistent storage
Returns:
the cache size
setLoadingPlaceholder
public void setLoadingPlaceholder(Hashtable loadingPlaceholder)
Deprecated.
When loading the element from the cloud a placehold is shown to indicate to the user
that the content isn't fully here
Parameters:
loadingPlaceholder - shows blank content to the user
getLoadingPlaceholder
public Hashtable getLoadingPlaceholder()
Deprecated.
When loading the element from the cloud a placehold is shown to indicate to the user
that the content isn't fully here
Returns:
the element shown when content isn't available for a specific entry
getBatchSize
public int getBatchSize()
Deprecated.
Returns the batch size fetched from the server
Returns:
the size
setBatchSize
public void setBatchSize(int batchSize)
Deprecated.
Updates the number of elements fetched from the server in a single batch
Parameters:
batchSize - the batch size
getItemAt
public Object getItemAt(int index)
Deprecated.
Returns the item at the given offset
Specified by:
getItemAt in interface ListModel
Parameters:
Method Detail
2733
Deprecated.
Returns the number of items in the list
Specified by:
getSize in interface ListModel
Returns:
the number of items in the list
onError
protected void onError(CloudException err)
Deprecated.
Invoked when a cloud error occurs
Parameters:
err - the exception representing the error in cloud communications
getSelectedIndex
public int getSelectedIndex()
Deprecated.
Returns the selected list offset
Specified by:
getSelectedIndex in interface ListModel
Returns:
the selected list index
setSelectedIndex
public void setSelectedIndex(int index)
Deprecated.
Sets the selected list offset can be set to -1 to clear selection
Specified by:
setSelectedIndex in interface ListModel
Parameters:
index - an index into this list
addDataChangedListener
public void addDataChangedListener(DataChangedListener l)
Deprecated.
Invoked to indicate interest in future change events
Specified by:
addDataChangedListener in interface ListModel
Parameters:
l - a data changed listener
removeDataChangedListener
public void removeDataChangedListener(DataChangedListener l)
Deprecated.
Invoked to indicate no further interest in future change events
Specified by:
removeDataChangedListener in interface ListModel
Parameters:
l - a data changed listener
addSelectionListener
public void addSelectionListener(SelectionListener l)
Deprecated.
Invoked to indicate interest in future selection events
Method Detail
2734
Specified by:
addSelectionListener
in interface ListModel
Parameters:
l - a selection listener
removeSelectionListener
public void removeSelectionListener(SelectionListener l)
Deprecated.
Invoked to indicate no further interest in future selection events
Specified by:
removeSelectionListener in interface ListModel
Parameters:
l - a selection listener
addItem
public void addItem(Object item)
Deprecated.
Notice this method does NOT commit the data, after committing the data the cache
MUST be cleared! Adds the specified item to the end of this list. An optional operation
for mutable lists, it can throw an unsupported operation exception if a list model is not
mutable.
Specified by:
addItem in interface ListModel
Parameters:
item - the item to be added
removeItem
public void removeItem(int index)
Deprecated.
Notice this method does NOT commit the data, after committing the data the cache
MUST be cleared! Removes the item at the specified position in this list.
Specified by:
removeItem in interface ListModel
Parameters:
index - the index of the item to removed
getRefreshRateMillis
public int getRefreshRateMillis()
Deprecated.
Indicates the rate in milliseconds in which to poll the server for the current data of
elements that are visible at the moment.
Returns:
the refreshRateMillis
setRefreshRateMillis
public void setRefreshRateMillis(int refreshRateMillis)
Deprecated.
Indicates the rate in milliseconds in which to poll the server for the current data of
elements that are visible at the moment.
Parameters:
refreshRateMillis - the refreshRateMillis to set
Method Detail
2735
Class CloudImageProperty
java.lang.Object
com.codename1.cloud.CloudImageProperty
All Implemented Interfaces:
CustomProperty
Deprecated.
the cloud storage API is no longer supported, we recommend switching to a solution such as
parse4cn1
public class
extends Object
implements CustomProperty
A custom property that converts a cloud file id value to an image that is cached locally
asynchronously.
Constructor Summary
Constructor and Description
CloudImageProperty(String idProperty, EncodedImage placeholderImage)
Deprecated.
Create an image property for the given id that will hold the place holder image while
downloading the actual image
Method Summary
Modifier and Type
Deprecated.
Returns a property value for the given property name
Object
Constructor Detail
CloudImageProperty
public CloudImageProperty(String idProperty,
EncodedImage placeholderImage)
Deprecated.
Create an image property for the given id that will hold the place holder image while
downloading the actual image
Parameters:
idProperty - the id
placeholderImage - placeholder shown while id is downloaded
Method Detail
Class CloudImageProperty
2736
Deprecated.
Returns a property value for the given property name
Specified by:
propertyValue in interface CustomProperty
Parameters:
obj - the cloud object
propertyName - the name of the property
Returns:
the property value
Method Detail
2737
Class CloudException
java.lang.Object
java.lang.Throwable
java.lang.Exception
com.codename1.cloud.CloudException
Deprecated.
the cloud storage API is no longer supported, we recommend switching to a solution such as
parse4cn1
public class
extends Exception
Method Summary
Modifier and
Type
Deprecated.
Returns the error code for the cloud exception, see the cloud storage for
return codes
int
Method Detail
getErrorCode
public int getErrorCode()
Deprecated.
Returns the error code for the cloud exception, see the cloud storage for return codes
Returns:
the error code
Class CloudException
2738
Interface BindTarget
public interface
Method Summary
Modifier and Type
void
Method Detail
propertyChanged
void propertyChanged(Component source,
String propertyName,
Object oldValue,
Object newValue)
Method Detail
2739
Class XYChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
Direct Known Subclasses:
BarChart, BubbleChart, CombinedXYChart, LineChart, ScatterChart
Field Summary
Modifier and Type
protected XYMultipleSeriesDataset
protected XYMultipleSeriesRenderer
mDataset
Constructor Summary
Modifier
protected XYChart()
XYChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
Method Summary
Modifier and Type
protected abstract
ClickableArea[]
protected void
drawChartValuesText(com.codename1.charts.compat.Canvas canvas,
XYSeries series, XYSeriesRenderer renderer,
com.codename1.charts.compat.Paint paint,
List<Float> points, int seriesIndex, int startIndex)
protected void
drawPoints(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> pointsList,
XYSeriesRenderer seriesRenderer, float yAxisValue,
int seriesIndex, int startIndex)
Method Detail
drawSeries(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> points, XYSeriesRenderer seriesRenderer,
float yAxisValue, int seriesIndex, int startIndex)
2740
protected void
drawSeries(XYSeries series,
com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> pointsList,
XYSeriesRenderer seriesRenderer, float yAxisValue,
int seriesIndex,
XYMultipleSeriesRenderer.Orientation or,
int startIndex)
protected void
protected void
drawText(com.codename1.charts.compat.Canvas canvas,
String text, float x, float y,
com.codename1.charts.compat.Paint paint,
float extraAngle)
protected void
drawXTextLabels(Double[] xTextLabelLocations,
com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
boolean showLabels, int left, int top, int bottom,
double xPixelsPerUnit, double minX, double maxX)
protected void
drawYLabels(Map<Integer,List<Double>> allYLabels,
com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
int maxScaleNumber, int left, int right, int bottom,
double[] yPixelsPerUnit, double[] minY)
getCalcRange(int scale)
getChartType()
ScatterChart
XYMultipleSeriesRenderer
getRenderer()
protected Rectangle
getScreenR()
getSeriesAndPointForScreenCoordinate(Point screenPoint)
SeriesSelection
protected List<Double>
protected
Map<Integer,List<Double>>
protected boolean
isRenderNullValues()
boolean
void
protected void
setDatasetRenderer(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
protected void
setScreenR(Rectangle screenR)
Method Summary
2741
double[]
toScreenPoint(double[] realPoint)
double[]
Field Detail
mDataset
protected XYMultipleSeriesDataset mDataset
Constructor Detail
XYChart
protected XYChart()
XYChart
public XYChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
Method Detail
setDatasetRenderer
protected void setDatasetRenderer(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
draw
public void draw(com.codename1.charts.compat.Canvas canvas,
int x,
int y,
int width,
int height,
com.codename1.charts.compat.Paint paint)
2742
in class AbstractChart
Parameters:
canvas - the canvas to paint to
x - the top left x value of the view to draw
y - the top left y value of the view to draw
width - the width of the view to draw to
height - the height of the view to draw to
paint - the paint
to
to
getXLabels
protected List<Double> getXLabels(double min,
double max,
int count)
getYLabels
protected Map<Integer,List<Double>> getYLabels(double[] minY,
double[] maxY,
int maxScaleNumber)
getScreenR
protected Rectangle getScreenR()
setScreenR
protected void setScreenR(Rectangle screenR)
drawSeries
protected void drawSeries(XYSeries series,
com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> pointsList,
XYSeriesRenderer seriesRenderer,
float yAxisValue,
int seriesIndex,
XYMultipleSeriesRenderer.Orientation or,
int startIndex)
Method Detail
2743
Method Detail
2744
getDataset
public XYMultipleSeriesDataset getDataset()
getCalcRange
public double[] getCalcRange(int scale)
setCalcRange
public void setCalcRange(double[] range,
int scale)
toRealPoint
public double[] toRealPoint(float screenX,
float screenY)
toScreenPoint
public double[] toScreenPoint(double[] realPoint)
toRealPoint
public double[] toRealPoint(float screenX,
float screenY,
int scale)
Method Detail
2745
getSeriesAndPointForScreenCoordinate
public SeriesSelection getSeriesAndPointForScreenCoordinate(Point screenPoint)
Method Detail
2746
Returns the scatter chart to be used for drawing the data points.
Returns:
the data points scatter chart
getChartType
public abstract String getChartType()
Method Detail
2747
Class TimeChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
com.codename1.charts.views.LineChart
com.codename1.charts.views.TimeChart
public class
extends LineChart
Field Summary
Modifier and Type
static long
static String
Constructor Summary
Constructor and Description
TimeChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer)
Method Summary
Modifier and
Type
protected void
String
String
Returns the date format pattern to be used for formatting the X axis labels.
protected
List<Double>
void
Sets the date format pattern to be used for formatting the X axis labels.
Class TimeChart
2748
inherited from
class com.codename1.charts.views.XYChart
draw, drawChartValuesText, drawPoints, drawSeries, drawText,
drawXTextLabels, drawYLabels, getCalcRange, getDataset, getDefaultMinimum,
getRenderer, getScreenR, getSeriesAndPointForScreenCoordinate, getYLabels,
isRenderNullValues, setCalcRange, setScreenR, toRealPoint, toRealPoint,
toScreenPoint, toScreenPoint
Field Detail
TYPE
public static final String TYPE
Constructor Detail
TimeChart
public TimeChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
Method Detail
getDateFormat
public String getDateFormat()
Returns the date format pattern to be used for formatting the X axis labels.
Returns:
the date format pattern for the X axis labels
setDateFormat
public void setDateFormat(String format)
Sets the date format pattern to be used for formatting the X axis labels.
2749
Overrides:
getXLabels
Method Detail
in class XYChart
2750
Class ScatterChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
com.codename1.charts.views.ScatterChart
public class
extends XYChart
Field Summary
Modifier and Type
static String
Constructor Summary
Constructor and Description
ScatterChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer)
Method Summary
Modifier and Type
protected
ClickableArea[]
drawLegendShape(com.codename1.charts.compat.Canvas canvas,
SimpleSeriesRenderer renderer, float x, float y,
int seriesIndex, com.codename1.charts.compat.Paint paint)
void
drawSeries(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint, List<Float> points,
XYSeriesRenderer renderer, float yAxisValue, int seriesIndex,
int startIndex)
Class ScatterChart
getChartType()
2751
inherited from
class com.codename1.charts.views.XYChart
draw, drawChartValuesText, drawPoints, drawSeries, drawText, drawXLabels,
drawXTextLabels, drawYLabels, getCalcRange, getDataset, getDefaultMinimum,
getPointsChart, getRenderer, getScreenR,
getSeriesAndPointForScreenCoordinate, getXLabels, getYLabels,
isRenderNullValues, isRenderPoints, setCalcRange, setScreenR, toRealPoint,
toRealPoint, toScreenPoint, toScreenPoint
Field Detail
TYPE
public static final String TYPE
Constructor Detail
ScatterChart
public ScatterChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
Method Detail
setDatasetRenderer
protected void setDatasetRenderer(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
Overrides:
setDatasetRenderer
in class XYChart
drawSeries
public void drawSeries(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> points,
XYSeriesRenderer renderer,
float yAxisValue,
int seriesIndex,
int startIndex)
2752
in class XYChart
Parameters:
canvas - the canvas to paint to
paint - the paint to be used for drawing
points - the array of points to be used for drawing the series
seriesRenderer - the series renderer
yAxisValue - the minimum value of the y axis
seriesIndex - the index of the series currently being drawn
startIndex - the start index of the rendering points
clickableAreasForPoints
protected ClickableArea[] clickableAreasForPoints(List<Float> points,
List<Double> values,
float yAxisValue,
int seriesIndex,
int startIndex)
Method Detail
2753
Class RoundChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.RoundChart
Direct Known Subclasses:
DialChart, DoughnutChart, PieChart
Field Summary
Modifier and Type
protected boolean
protected int
protected int
protected CategorySeries
protected DefaultRenderer
protected static int
protected static int
mDataset
A no value constant.
SHAPE_WIDTH
Constructor Summary
Constructor and Description
RoundChart(CategorySeries dataset, DefaultRenderer renderer)
Round chart.
Method Summary
Modifier and
Type
void
Class RoundChart
getCenterX()
2754
getRenderer()
boolean
isAutocalculateCenter()
void
setAutocalculateCenter(boolean a)
setCenterX(int centerX)
void
void
Field Detail
SHAPE_WIDTH
protected static final int SHAPE_WIDTH
A no value constant.
See Also:
Constant Field Values
mCenterX
protected int mCenterX
Method Summary
2755
Detail
RoundChart
public RoundChart(CategorySeries dataset,
DefaultRenderer renderer)
Round chart.
Parameters:
dataset - the series dataset
renderer - the series renderer
Method Detail
drawTitle
public void drawTitle(com.codename1.charts.compat.Canvas canvas,
int x,
int y,
int width,
com.codename1.charts.compat.Paint paint)
Constructor Detail
2756
isAutocalculateCenter
public boolean isAutocalculateCenter()
Method Detail
2757
Class RangeStackedBarChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
com.codename1.charts.views.BarChart
com.codename1.charts.views.RangeBarChart
com.codename1.charts.views.RangeStackedBarChart
public class
extends RangeBarChart
Field Summary
Modifier and Type Field and Description
static String
TYPE
Method Summary
Modifier and Type
String
Class RangeStackedBarChart
2758
inherited from
class com.codename1.charts.views.XYChart
draw, drawPoints, drawSeries, drawText, drawXLabels, drawXTextLabels,
drawYLabels, getCalcRange, getDataset, getPointsChart, getRenderer,
getScreenR, getSeriesAndPointForScreenCoordinate, getXLabels, getYLabels,
isRenderPoints, setCalcRange, setDatasetRenderer, setScreenR, toRealPoint,
toRealPoint, toScreenPoint, toScreenPoint
Field Detail
TYPE
public static final String TYPE
Method Detail
getChartType
public String getChartType()
2759
Class RangeBarChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
com.codename1.charts.views.BarChart
com.codename1.charts.views.RangeBarChart
Direct Known Subclasses:
RangeStackedBarChart
public class
extends BarChart
Field Summary
Modifier and Type Field and Description
static String
TYPE
Constructor Summary
Constructor and Description
RangeBarChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer,
BarChart.Type type)
Method Summary
Modifier
and Type
protected
void
Method Detail
2760
void
String
protected
float
getCoeficient()
Field Detail
TYPE
public static final String TYPE
Constructor Detail
RangeBarChart
public RangeBarChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer,
BarChart.Type type)
Method Summary
2761
Detail
drawSeries
public void drawSeries(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> points,
XYSeriesRenderer seriesRenderer,
float yAxisValue,
int seriesIndex,
int startIndex)
Method Detail
2762
Enum PointStyle
java.lang.Object
java.lang.Enum<PointStyle>
com.codename1.charts.views.PointStyle
All Implemented Interfaces:
Comparable<PointStyle>
public enum
extends Enum<PointStyle>
Method Summary
Modifier and Type
static int
String
static PointStyle
getPointStyleForName(String name)
String
static PointStyle
static
PointStyle[]
valueOf(String name)
Returns the enum constant of this type with the specified name.
values()
Enum PointStyle
2763
Constant Detail
X
public static final PointStyle X
CIRCLE
public static final PointStyle CIRCLE
TRIANGLE
public static final PointStyle TRIANGLE
SQUARE
public static final PointStyle SQUARE
DIAMOND
public static final PointStyle DIAMOND
POINT
public static final PointStyle POINT
Method Detail
values
public static PointStyle[] values()
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
for (PointStyle c : PointStyle.values())
System.out.println(c);
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static PointStyle valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
getName
public String getName()
2764
Returns:
the point shape name
getPointStyleForName
public static PointStyle getPointStyleForName(String name)
Method Detail
2765
Class PieSegment
java.lang.Object
com.codename1.charts.views.PieSegment
public class
extends Object
Constructor Summary
Constructor and Description
PieSegment(int dataIndex, float value, float startAngle, float angle)
Method Summary
Modifier and Type
protected int
getDataIndex()
protected float
getEndAngle()
Shape
protected float
getStartAngle()
protected float
getValue()
boolean
isInSegment(double angle)
String
Constructor Detail
PieSegment
public PieSegment(int dataIndex,
float value,
float startAngle,
float angle)
Method Detail
isInSegment
public boolean isInSegment(double angle)
Class PieSegment
2766
getEndAngle
protected float getEndAngle()
getDataIndex
protected int getDataIndex()
getValue
protected float getValue()
toString
public String toString()
Method Detail
2767
Class PieMapper
java.lang.Object
com.codename1.charts.views.PieMapper
public class
extends Object
Constructor Summary
Constructor and Description
PieMapper()
Method Summary
Modifier and
Type
void
areAllSegmentPresent(int datasetSize)
void
double
Fetches angle relative to pie chart center point where 3 O'Clock is 0 and
12 O'Clock is 270degrees
Shape
getSegmentShape(int dataIndex)
SeriesSelection
boolean
getSeriesAndPointForScreenCoordinate(Point screenPoint)
void
Constructor Detail
PieMapper
public PieMapper()
Method Detail
Class PieMapper
2768
Fetches angle relative to pie chart center point where 3 O'Clock is 0 and 12 O'Clock
is 270degrees
Parameters:
screenPoint Returns:
angle in degress from 0-360.
isOnPieChart
public boolean isOnPieChart(Point screenPoint)
Method Detail
2769
Method Detail
2770
Class PieChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.RoundChart
com.codename1.charts.views.PieChart
public class
extends RoundChart
Field Summary
Constructor Summary
Constructor and Description
PieChart(CategorySeries dataset, DefaultRenderer renderer)
Method Summary
Modifier and
Type
void
Shape
SeriesSelection
Given screen coordinates, returns the series and point indexes of a chart
element.
Class PieChart
2771
Constructor Detail
PieChart
public PieChart(CategorySeries dataset,
DefaultRenderer renderer)
Method Detail
draw
public void draw(com.codename1.charts.compat.Canvas canvas,
int x,
int y,
int width,
int height,
com.codename1.charts.compat.Paint paint)
2772
Class LineChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
com.codename1.charts.views.LineChart
Direct Known Subclasses:
CubicLineChart, TimeChart
public class
extends XYChart
Field Summary
Modifier and Type
static String
Constructor Summary
Constructor and Description
LineChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer)
Method Summary
Modifier and Type
protected
ClickableArea[]
drawLegendShape(com.codename1.charts.compat.Canvas canvas,
SimpleSeriesRenderer renderer, float x, float y,
int seriesIndex, com.codename1.charts.compat.Paint paint)
void
drawSeries(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint, List<Float> points,
XYSeriesRenderer renderer, float yAxisValue, int seriesIndex,
int startIndex)
Method Detail
getChartType()
Returns the scatter chart to be used for drawing the data points.
isRenderPoints(SimpleSeriesRenderer renderer)
2773
setDatasetRenderer(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
Field Detail
TYPE
public static final String TYPE
Constructor Detail
LineChart
public LineChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
Method Detail
setDatasetRenderer
protected void setDatasetRenderer(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
Method Summary
2774
Method Detail
2775
drawing
isRenderPoints
public boolean isRenderPoints(SimpleSeriesRenderer renderer)
Returns the scatter chart to be used for drawing the data points.
Overrides:
getPointsChart in class XYChart
Returns:
the data points scatter chart
getChartType
public String getChartType()
Method Detail
2776
Class DoughnutChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.RoundChart
com.codename1.charts.views.DoughnutChart
public class
extends RoundChart
Field Summary
Constructor Summary
Constructor and Description
DoughnutChart(MultipleCategorySeries dataset, DefaultRenderer renderer)
Method Summary
Modifier
and Type
void
void
int
Class DoughnutChart
2777
Constructor Detail
DoughnutChart
public DoughnutChart(MultipleCategorySeries dataset,
DefaultRenderer renderer)
Method Detail
draw
public void draw(com.codename1.charts.compat.Canvas canvas,
int x,
int y,
int width,
int height,
com.codename1.charts.compat.Paint paint)
2778
Method Detail
drawing
2779
Class DialChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.RoundChart
com.codename1.charts.views.DialChart
public class
extends RoundChart
Field Summary
Constructor Summary
Constructor and Description
DialChart(CategorySeries dataset, DialRenderer renderer)
Method Summary
Modifier
and Type
void
Class DialChart
2780
Constructor
Detail
DialChart
public DialChart(CategorySeries dataset,
DialRenderer renderer)
Method Detail
draw
public void draw(com.codename1.charts.compat.Canvas canvas,
int x,
int y,
int width,
int height,
com.codename1.charts.compat.Paint paint)
Constructor Detail
2781
Class CubicLineChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
com.codename1.charts.views.LineChart
com.codename1.charts.views.CubicLineChart
public class
extends LineChart
Field Summary
Modifier and Type Field and Description
static String
TYPE
Constructor Summary
Constructor and Description
CubicLineChart()
CubicLineChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer,
float smoothness)
Method Summary
Modifier
and Type
protected
void
drawPoints(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint, List<Float> pointsList,
XYSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex,
int startIndex)
getChartType()
Method Detail
2782
inherited from
class com.codename1.charts.views.XYChart
draw, drawChartValuesText, drawSeries, drawText, drawXLabels,
drawXTextLabels, drawYLabels, getCalcRange, getDataset, getDefaultMinimum,
getRenderer, getScreenR, getSeriesAndPointForScreenCoordinate, getXLabels,
getYLabels, isRenderNullValues, setCalcRange, setScreenR, toRealPoint,
toRealPoint, toScreenPoint, toScreenPoint
Field Detail
TYPE
public static final String TYPE
Constructor Detail
CubicLineChart
public CubicLineChart()
CubicLineChart
public CubicLineChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer,
float smoothness)
Method Detail
drawPath
protected void drawPath(com.codename1.charts.compat.Canvas canvas,
List<Float> points,
com.codename1.charts.compat.Paint paint,
boolean circular)
2783
to paint
drawPoints
protected void drawPoints(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> pointsList,
XYSeriesRenderer seriesRenderer,
float yAxisValue,
int seriesIndex,
int startIndex)
Method Detail
2784
Class CombinedXYChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
com.codename1.charts.views.CombinedXYChart
public class
extends XYChart
Field Summary
Constructor Summary
Constructor and Description
CombinedXYChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer,
CombinedXYChart.XYCombinedChartDef[] chartDefinitions)
Method Summary
Modifier and Type
protected
ClickableArea[]
drawLegendShape(com.codename1.charts.compat.Canvas canvas,
SimpleSeriesRenderer renderer, float x, float y,
int seriesIndex, com.codename1.charts.compat.Paint paint)
void
drawSeries(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint, List<Float> points,
XYSeriesRenderer seriesRenderer, float yAxisValue,
int seriesIndex, int startIndex)
protected void
drawSeries(XYSeries series,
com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> pointsList, XYSeriesRenderer seriesRenderer,
float yAxisValue, int seriesIndex,
XYMultipleSeriesRenderer.Orientation or, int startIndex)
Class CombinedXYChart
2785
String
int
Constructor Detail
CombinedXYChart
public CombinedXYChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer,
CombinedXYChart.XYCombinedChartDef[] chartDefinitions)
Method Detail
drawSeries
public void drawSeries(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> points,
XYSeriesRenderer seriesRenderer,
float yAxisValue,
int seriesIndex,
int startIndex)
Method Summary
2786
Method Detail
2787
be drawn at
be drawn at
getChartType
public String getChartType()
Method Detail
2788
Class CombinedXYChart.XYCombinedChartDef
java.lang.Object
com.codename1.charts.views.CombinedXYChart.XYCombinedChartDef
Enclosing class:
CombinedXYChart
Constructor Summary
Constructor and Description
XYCombinedChartDef(String type, int... seriesIndex)
Method Summary
Modifier and Type
boolean
containsSeries(int seriesIndex)
int
getChartSeriesIndex(int seriesIndex)
int[]
getSeriesIndex()
String
getType()
Constructor Detail
XYCombinedChartDef
public XYCombinedChartDef(String type,
int... seriesIndex)
Method Detail
containsSeries
public boolean containsSeries(int seriesIndex)
getChartSeriesIndex
public int getChartSeriesIndex(int seriesIndex)
Class CombinedXYChart.XYCombinedChartDef
2789
getSeriesIndex
public int[] getSeriesIndex()
Method Detail
2790
Class ClickableArea
java.lang.Object
com.codename1.charts.views.ClickableArea
public class
extends Object
Constructor Summary
Constructor and Description
ClickableArea(Rectangle2D rect, double x, double y)
Method Summary
Method and
Description
getRect()
double
getX()
double
getY()
Constructor Detail
ClickableArea
public ClickableArea(Rectangle2D rect,
double x,
double y)
Method Detail
getRect
public Rectangle2D getRect()
getX
public double getX()
getY
public double getY()
Class ClickableArea
2791
Class BubbleChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
com.codename1.charts.views.BubbleChart
public class
extends XYChart
Field Summary
Modifier and Type
static String
Constructor Summary
Constructor and Description
BubbleChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer)
Method Summary
Modifier and Type
protected
ClickableArea[]
void
void
getChartType()
int
Method Detail
2792
Field Detail
TYPE
public static final String TYPE
Constructor Detail
BubbleChart
public BubbleChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer)
Method Detail
drawSeries
public void drawSeries(com.codename1.charts.compat.Canvas canvas,
com.codename1.charts.compat.Paint paint,
List<Float> points,
XYSeriesRenderer renderer,
float yAxisValue,
int seriesIndex,
int startIndex)
2793
Method Detail
2794
Class BarChart
java.lang.Object
com.codename1.charts.views.AbstractChart
com.codename1.charts.views.XYChart
com.codename1.charts.views.BarChart
Direct Known Subclasses:
RangeBarChart
public class
extends XYChart
Field Summary
Modifier and Type
protected BarChart.Type
static String
Constructor Summary
Constructor and Description
BarChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer,
BarChart.Type type)
Method Summary
Modifier and Type
protected
ClickableArea[]
protected void
Draws a bar.
protected void
Class BarChart
2795
Draws a bar.
protected void
drawChartValuesText(com.codename1.charts.compat.Canvas canvas,
XYSeries series, XYSeriesRenderer renderer,
com.codename1.charts.compat.Paint paint, List<Float> points,
int seriesIndex, int startIndex)
void
void
String
protected float
getCoeficient()
double
protected int
protected float
int
protected boolean
isRenderNullValues()
Field Detail
TYPE
public static final String TYPE
Method Summary
2796
Constructor Detail
BarChart
public BarChart(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer,
BarChart.Type type)
Method Detail
clickableAreasForPoints
protected ClickableArea[] clickableAreasForPoints(List<Float> points,
List<Double> values,
float yAxisValue,
int seriesIndex,
int startIndex)
Field Detail
2797
Draws a bar.
Parameters:
canvas - the canvas
xMin - the X axis minimum
yMin - the Y axis minimum
xMax - the X axis maximum
yMax - the Y axis maximum
halfDiffX - half the size of a bar
seriesNr - the total number of series
seriesIndex - the current series index
paint - the paint
drawBar
protected void drawBar(com.codename1.charts.compat.Canvas canvas,
float xMin,
float yMin,
float xMax,
float yMax,
int scale,
int seriesIndex,
com.codename1.charts.compat.Paint paint)
Draws a bar.
Parameters:
canvas - the canvas
xMin - the X axis minimum
yMin - the Y axis minimum
xMax - the X axis maximum
yMax - the Y axis maximum
scale - the scale index
seriesIndex - the current series
paint - the paint
index
getGradientPartialColor
protected int getGradientPartialColor(int minColor,
int maxColor,
float fraction)
drawChartValuesText
protected void drawChartValuesText(com.codename1.charts.compat.Canvas canvas,
XYSeries series,
XYSeriesRenderer renderer,
com.codename1.charts.compat.Paint paint,
List<Float> points,
int seriesIndex,
int startIndex)
Method Detail
2798
Method Detail
2799
Method Detail
2800
Enum BarChart.Type
java.lang.Object
java.lang.Enum<BarChart.Type>
com.codename1.charts.views.BarChart.Type
All Implemented Interfaces:
Comparable<BarChart.Type>
Enclosing class:
BarChart
Method Summary
Modifier and Type
static BarChart.Type
static
BarChart.Type[]
Returns the enum constant of this type with the specified name.
values()
STACKED
public static final BarChart.Type STACKED
HEAPED
public static final BarChart.Type HEAPED
Enum BarChart.Type
2801
Detail
values
public static BarChart.Type[] values()
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
for (BarChart.Type c : BarChart.Type.values())
System.out.println(c);
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static BarChart.Type valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
Method Detail
2802
Class AbstractChart
java.lang.Object
com.codename1.charts.views.AbstractChart
Direct Known Subclasses:
RoundChart, XYChart
Constructor Summary
Constructor and Description
AbstractChart()
Method Summary
Modifier and
Type
abstract void
protected void
drawBackground(DefaultRenderer renderer,
com.codename1.charts.compat.Canvas canvas, int x, int y,
int width, int height, com.codename1.charts.compat.Paint paint,
boolean newColor, int color)
protected void
drawLabel(com.codename1.charts.compat.Canvas canvas,
String labelText, DefaultRenderer renderer,
List<Rectangle2D> prevLabelsBounds, int centerX, int centerY,
float shortRadius, float longRadius, float currentAngle,
float angle, int left, int right, int color,
com.codename1.charts.compat.Paint paint, boolean line,
boolean display)
protected int
drawLegend(com.codename1.charts.compat.Canvas canvas,
DefaultRenderer renderer, String[] titles, int left, int right,
int y, int width, int height, int legendSize,
com.codename1.charts.compat.Paint paint, boolean calculate)
drawLegendShape(com.codename1.charts.compat.Canvas canvas,
SimpleSeriesRenderer renderer, float x, float y, int seriesIndex,
com.codename1.charts.compat.Paint paint)
drawPath(com.codename1.charts.compat.Canvas canvas,
float[] points, com.codename1.charts.compat.Paint paint,
boolean circular)
drawPath(com.codename1.charts.compat.Canvas canvas,
List<Float> points, com.codename1.charts.compat.Paint paint,
boolean circular)
drawString(com.codename1.charts.compat.Canvas canvas,
String text, float x, float y,
com.codename1.charts.compat.Paint paint)
Class AbstractChart
2803
protected int
Given screen coordinates, returns the series and point indexes of a chart
element.
boolean
isNullValue(double value)
boolean
isVertical(DefaultRenderer renderer)
Constructor Detail
AbstractChart
public AbstractChart()
Method Detail
draw
public abstract void draw(com.codename1.charts.compat.Canvas canvas,
int x,
int y,
int width,
int height,
com.codename1.charts.compat.Paint paint)
Method Summary
2804
to
drawLegend
protected int drawLegend(com.codename1.charts.compat.Canvas canvas,
DefaultRenderer renderer,
String[] titles,
int left,
int right,
int y,
int width,
int height,
int legendSize,
com.codename1.charts.compat.Paint paint,
boolean calculate)
Method Detail
2805
Method Detail
2806
be drawn at
be drawn at
getLegendSize
protected int getLegendSize(DefaultRenderer renderer,
int defaultHeight,
float extraHeight)
getSeriesAndPointForScreenCoordinate
public SeriesSelection getSeriesAndPointForScreenCoordinate(Point screenPoint)
Given screen coordinates, returns the series and point indexes of a chart element. If
there is no chart element (line, point, bar, etc) at those coordinates, null is returned.
Parameters:
screenPoint Returns:
the series and point indexes
Method Detail
2807
Class NumberFormat
java.lang.Object
com.codename1.charts.util.NumberFormat
public class
extends Object
Constructor Summary
Constructor and Description
NumberFormat()
Method Summary
Modifier and Type
String
parseDouble(String format)
void
setMaximumFractionDigits(int i)
Constructor Detail
NumberFormat
public NumberFormat()
Method Detail
getNumberInstance
public static NumberFormat getNumberInstance()
format
public String format(double label)
setMaximumFractionDigits
public void setMaximumFractionDigits(int i)
parseDouble
public double parseDouble(String format)
throws ParseException
Throws:
ParseException
Class NumberFormat
2808
Class MathHelper
java.lang.Object
com.codename1.charts.util.MathHelper
public class
extends Object
Field Summary
Modifier and Type
static double
Method Summary
Modifier and Type
static
List<Double>
static double[]
Field Detail
NULL_VALUE
public static final double NULL_VALUE
Method Detail
minmax
public static double[] minmax(List<Double> values)
Method Detail
2809
Computes a reasonable set of labels for a data interval and number of labels.
Parameters:
start - start value
end - final value
approxNumLabels - desired number of labels
Returns:
collection containing the label values
Method Detail
2810
Class ColorUtil
java.lang.Object
com.codename1.charts.util.ColorUtil
public class
extends Object
Field Summary
Modifier and Type Field and Description
static int
BLACK
static int
BLUE
static int
CYAN
static int
GRAY
static int
GREEN
static int
LTGRAY
static int
MAGENTA
static int
WHITE
static int
YELLOW
Constructor Summary
Constructor and Description
ColorUtil()
Method Summary
Modifier and Type
static int
alpha(int c)
static int
static int
blue(int c)
static int
green(int c)
static int
red(int c)
static int
Field Detail
Class ColorUtil
2811
BLUE
public static int BLUE
BLACK
public static int BLACK
WHITE
public static int WHITE
CYAN
public static int CYAN
GREEN
public static int GREEN
YELLOW
public static int YELLOW
MAGENTA
public static int MAGENTA
GRAY
public static int GRAY
Constructor Detail
ColorUtil
public ColorUtil()
Method Detail
argb
public static int argb(int
int
int
int
a,
r,
g,
b)
alpha
public static int alpha(int c)
red
public static int red(int c)
green
public static int green(int c)
blue
public static int blue(int c)
rgb
public static int rgb(int r,
int g,
int b)
Field Detail
2812
Class XYValueSeriesTransition
java.lang.Object
com.codename1.charts.transitions.SeriesTransition
com.codename1.charts.transitions.XYValueSeriesTransition
All Implemented Interfaces:
Animation
public class
extends SeriesTransition
Field Summary
Constructor Summary
Constructor and Description
XYValueSeriesTransition(ChartComponent chart, XYValueSeries series)
Method Summary
Modifier and Type
protected void
XYValueSeries
XYValueSeries
void
protected void
Method Detail
2813
Constructor
Detail
XYValueSeriesTransition
public XYValueSeriesTransition(ChartComponent chart,
XYValueSeries series)
Creates a new transition on the given chart and associated series. The series should
be one of the series rendered by the given chart.
Parameters:
chart - The ChartComponent that is being used to render the series.
series - The series whose data you wish to animate.
Method Detail
initTransition
public void initTransition()
Initializes the transition. This can be overridden by subclasses to provide their own
functionality to be executed just before the transition occurs.
Overrides:
initTransition in class SeriesTransition
cleanup
protected void cleanup()
Updates the series and renderer at the given progress position (0 to 100).
Specified by:
update in class SeriesTransition
Parameters:
progress - The progress position in the motion. (0-100).
getBuffer
public XYValueSeries getBuffer()
Gets the "buffer" series where values can be set. Any values set on the buffer will be
applied to the target series during the course of the transition.
Returns:
getSeries
public XYValueSeries getSeries()
Constructor Detail
2814
Class XYSeriesTransition
java.lang.Object
com.codename1.charts.transitions.SeriesTransition
com.codename1.charts.transitions.XYSeriesTransition
All Implemented Interfaces:
Animation
public class
extends SeriesTransition
Field Summary
Constructor Summary
Constructor and Description
XYSeriesTransition(ChartComponent chart, XYSeries series)
Method Summary
Modifier and
Type
protected void
XYSeries
XYSeries
void
protected void
Method Detail
2815
Constructor
Detail
XYSeriesTransition
public XYSeriesTransition(ChartComponent chart,
XYSeries series)
Creates a new transition on the given chart and associated series. The series should
be one of the series rendered by the given chart.
Parameters:
chart - The ChartComponent that is being used to render the series.
series - The series whose data you wish to animate.
Method Detail
initTransition
public void initTransition()
Initializes the transition. This can be overridden by subclasses to provide their own
functionality to be executed just before the transition occurs.
Overrides:
initTransition in class SeriesTransition
cleanup
protected void cleanup()
Updates the series and renderer at the given progress position (0 to 100).
Specified by:
update in class SeriesTransition
Parameters:
progress - The progress position in the motion. (0-100).
getBuffer
public XYSeries getBuffer()
Gets the "buffer" series where values can be set. Any values set on the buffer will be
applied to the target series during the course of the transition.
Returns:
getSeries
public XYSeries getSeries()
Constructor Detail
2816
Class XYMultiSeriesTransition
java.lang.Object
com.codename1.charts.transitions.SeriesTransition
com.codename1.charts.transitions.XYMultiSeriesTransition
All Implemented Interfaces:
Animation
public class
extends SeriesTransition
Field Summary
Constructor Summary
Constructor and Description
XYMultiSeriesTransition(ChartComponent chart, XYMultipleSeriesDataset dataset)
Method Summary
Modifier and Type
protected void
XYMultipleSeriesDataset
protected void
protected void
Constructor Detail
Method Detail
2817
Creates a new transition for the given chart and dataset. The dataset must be
rendered by the given chart for this to work correctly.
Parameters:
chart dataset
Method Detail
initTransition
protected void initTransition()
Gets the buffer/cache for values. Values set in the buffer will be applied to the target
dataset when the transition takes place.
Returns:
Constructor Detail
2818
Class SeriesTransition
java.lang.Object
com.codename1.charts.transitions.SeriesTransition
All Implemented Interfaces:
Animation
Direct Known Subclasses:
XYMultiSeriesTransition, XYSeriesTransition, XYValueSeriesTransition
A base class for series transitions of ChartComponent. This should be overridden by concrete classes
that implement the update(int) method to update the chart's model and renderer appropriately. This
class can serve as a buffer for changes to the model so that they don't affect the ChartComponent
immediately. Changes can either be eased in using animateChart() or updated in one shot using
updateChart().
Field Summary
Modifier and Type Field and Description
static int
EASING_IN
static int
EASING_IN_OUT
static int
EASING_LINEAR
static int
EASING_OUT
Constructor Summary
Constructor and Description
SeriesTransition(ChartComponent chart)
SeriesTransition(ChartComponent chart, int easing)
SeriesTransition(ChartComponent chart, int easing, int duration)
Method Summary
Modifier and Type
boolean
void
protected void
ChartComponent
int
int
Method Detail
Applies all pending changes to the chart model and renderer using the
current animation settings.
cleanup()
2819
initTransition()
void
setChart(ChartComponent chart)
void
void
void
protected
abstract void
update(int progress)
Applies all pending changes to the chart model and renderer and
repaints the chart.
void
Field Detail
EASING_LINEAR
public static final int EASING_LINEAR
See Also:
Constant Field Values
EASING_IN
public static final int EASING_IN
See Also:
Constant Field Values
EASING_OUT
public static final int EASING_OUT
See Also:
Constant Field Values
EASING_IN_OUT
public static final int EASING_IN_OUT
See Also:
Constant Field Values
Constructor Detail
SeriesTransition
public SeriesTransition(ChartComponent chart)
SeriesTransition
public SeriesTransition(ChartComponent chart,
int easing)
Method Summary
2820
Method Detail
initTransition
protected void initTransition()
Initializes the transition for another iteration. This can be overridden by subclasses to
provide their own initialization. This method will be called just prior to the transition
taking place. IMPORTANT: Subclasses must make sure to call super.initTransition()
so that the animation will be initialized properly.
cleanup
protected void cleanup()
Cleans up any settings in the transition. Called after a transition is complete. This is
meant to be overridden by subclasses.
update
protected abstract void update(int progress)
Updates the renderer and model at the specified progress position of the animation.
Meant to be overridden by subclasses.
Parameters:
progress - The progress of the animation (between 0 and 100).
animate
public boolean animate()
Constructor Detail
2821
Gets the type of easing used in the transition. Should be one of EASING_LINEAR,
EASING_IN, EASING_OUT, or EASING_IN_OUT.
Returns:
the easing
setEasing
public void setEasing(int easing)
Sets the type of easing used in the transition. Should be one of EASING_LINEAR,
EASING_IN, EASING_OUT, or EASING_IN_OUT.
Parameters:
easing - the easing to set
animateChart
public void animateChart()
Applies all pending changes to the chart model and renderer using the current
animation settings.
updateChart
public void updateChart()
Applies all pending changes to the chart model and renderer and repaints the chart.
This is basically like calling animateChart() with a duration of 0.
Method Detail
2822
Class XYSeriesRenderer
java.lang.Object
com.codename1.charts.renderers.SimpleSeriesRenderer
com.codename1.charts.renderers.XYSeriesRenderer
public class
extends SimpleSeriesRenderer
Constructor Summary
Constructor and Description
XYSeriesRenderer()
Method Summary
Modifier and Type
void
int
int
float
float
int
float
int
XYSeriesRenderer.FillOutsideLine[]
float
float
PointStyle
boolean
Class XYSeriesRenderer
addFillOutsideLine(XYSeriesRenderer.FillOutsideLine fil
2823
boolean
Deprecated.
Use getFillOutsideLine() instead.
isFillPoints()
void
void
Sets the annotations text font size using a Font object instead
a point size.
void
setAnnotationsTextSize(float textSize)
void
void
void
Sets the chart values title text font size using a Font object
instead of a point size.
void
setChartValuesTextSize(float textSize)
void
void
void
Deprecated.
Use addFillOutsideLine(FillOutsideLine) instead.
void
setFillBelowLineColor(int color)
Deprecated.
Use FillOutsideLine.setColor instead
void
setFillPoints(boolean fill)
void
void
void
void
Constructor Detail
Method Summary
2824
Method Detail
isFillBelowLine
@Deprecated
public boolean isFillBelowLine()
Sets if the line chart should be filled outside its line. Filling outside with
FillOutsideLine.INTEGRAL the line transforms a line chart into an area chart.
Parameters:
fill - the type of the filling
isFillPoints
public boolean isFillPoints()
Constructor Detail
2825
Method Detail
2826
Sets the chart values title text font size using a Font object instead of a point size.
This method is the preferred way to set font size because it allows you to more easily
have fonts appear in an appropriate size for the target device. Alternatively check out
setChartValuesTextSize(float) to set the text size in pixels.
Parameters:
font getChartValuesTextAlign
public int getChartValuesTextAlign()
Method Detail
2827
Sets the annotations text font size using a Font object instead of a point size. This
method is the preferred way to set font size because it allows you to more easily have
fonts appear in an appropriate size for the target device. Alternatively check out
setAnnotationsTextSize(float) to set the text size in pixels.
Parameters:
font getAnnotationsTextAlign
public int getAnnotationsTextAlign()
Method Detail
2828
Class XYSeriesRenderer.FillOutsideLine
java.lang.Object
com.codename1.charts.renderers.XYSeriesRenderer.FillOutsideLine
Enclosing class:
XYSeriesRenderer
Constructor Summary
Constructor and Description
FillOutsideLine(XYSeriesRenderer.FillOutsideLine.Type type)
Method Summary
Modifier and Type
int
int[]
XYSeriesRenderer.FillOutsideLine.Type
getType()
void
void
Constructor Detail
FillOutsideLine
public FillOutsideLine(XYSeriesRenderer.FillOutsideLine.Type type)
Class XYSeriesRenderer.FillOutsideLine
2829
Method Detail
getColor
public int getColor()
Returns the fill range which is the minimum and maximum data index values for the
fill.
Returns:
the fill range
setFillRange
public void setFillRange(int[] range)
Sets the fill range which is the minimum and maximum data index values for the fill.
Parameters:
range - the fill range
Constructor Detail
2830
Enum XYSeriesRenderer.FillOutsideLine.Type
java.lang.Object
java.lang.Enum<XYSeriesRenderer.FillOutsideLine.Type>
com.codename1.charts.renderers.XYSeriesRenderer.FillOutsideLine.Type
All Implemented Interfaces:
Comparable<XYSeriesRenderer.FillOutsideLine.Type>
Enclosing class:
XYSeriesRenderer.FillOutsideLine
Method Summary
Modifier and Type
static
XYSeriesRenderer.FillOutsideLine.Type
static
XYSeriesRenderer.FillOutsideLine.Type[]
Method Detail
2831
BOUNDS_BELOW
public static final XYSeriesRenderer.FillOutsideLine.Type BOUNDS_BELOW
BOUNDS_ABOVE
public static final XYSeriesRenderer.FillOutsideLine.Type BOUNDS_ABOVE
BELOW
public static final XYSeriesRenderer.FillOutsideLine.Type BELOW
ABOVE
public static final XYSeriesRenderer.FillOutsideLine.Type ABOVE
Method Detail
values
public static XYSeriesRenderer.FillOutsideLine.Type[] values()
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static XYSeriesRenderer.FillOutsideLine.Type valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
2832
Class XYMultipleSeriesRenderer
java.lang.Object
com.codename1.charts.renderers.DefaultRenderer
com.codename1.charts.renderers.XYMultipleSeriesRenderer
public class
extends DefaultRenderer
Field Summary
Constructor Summary
Constructor and Description
XYMultipleSeriesRenderer()
XYMultipleSeriesRenderer(int scaleNumber)
Method Summary
Modifier and Type
void
void
void
void
Deprecated.
use addXTextLabel instead
addXTextLabel(double x, String text)
void
void
void
void
Method Detail
Deprecated.
use clearXTextLabels instead
clearXTextLabels()
2833
getAxisTitleTextSize()
double
float
int
double[]
double[]
Deprecated.
use getBarSpacing instead
getBarWidth()
NumberFormat
int
XYMultipleSeriesRenderer.Orientation
double[]
float
int
double
double
double
double
NumberFormat
int
int
float
int
float
String
Double[]
String
int
double
double
Method Summary
Deprecated.
use getXLabelFormat and getYLabelFormat instead
getMarginsColor()
2834
getYAxisMin()
void
initAxesRange(int scales)
void
initAxesRangeForScale(int i)
boolean
isInitialRangeSet()
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
Method Summary
isInitialRangeSet(int scale)
2835
isMinYSet(int scale)
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
void
Method Summary
Sets the Axis title text font size using a Font object instead o
size.
setAxisTitleTextSize(float textSize)
setOrientation(XYMultipleSeriesRenderer.Orientation o
so it ca
2836
Method Summary
Sets the rotation angle (in degrees) of labels for the X axis.
setXLabelsColor(int color)
Sets the rotation angle (in degrees) of labels for the Y axis.
setYLabelsColor(int scale, int color)
2837
Constructor Detail
XYMultipleSeriesRenderer
public XYMultipleSeriesRenderer()
XYMultipleSeriesRenderer
public XYMultipleSeriesRenderer(int scaleNumber)
Method Detail
initAxesRange
public void initAxesRange(int scales)
initAxesRangeForScale
public void initAxesRangeForScale(int i)
getOrientation
public XYMultipleSeriesRenderer.Orientation getOrientation()
2838
Method Detail
2839
Method Detail
2840
Method Detail
2841
isMaxXSet
public boolean isMaxXSet(int scale)
Method Detail
2842
Method Detail
2843
Method Detail
2844
Method Detail
2845
Method Detail
2846
Sets the spacing between bars, in bar charts. Only available for bar charts. This is a
coefficient of the bar width. For instance, if you want the spacing to be a half of the
bar width, set this value to 0.5.
Parameters:
spacing - the spacing between bars coefficient
getMarginsColor
public int getMarginsColor()
Method Detail
2847
Sets the pan limits as an array of 4 values. Setting it to null or a different size array
will disable the panning limitation. Values: [panMinimumX, panMaximumX,
panMinimumY, panMaximumY]
Parameters:
panLimits - the pan limits
getZoomLimits
public double[] getZoomLimits()
Sets the zoom limits as an array of 4 values. Setting it to null or a different size array
will disable the zooming limitation. Values: [zoomMinimumX, zoomMaximumX,
zoomMinimumY, zoomMaximumY]
Parameters:
zoomLimits - the zoom limits
getXLabelsAngle
public float getXLabelsAngle()
Sets the rotation angle (in degrees) of labels for the X axis.
Parameters:
angle - the rotation angle of labels for the X axis
getYLabelsAngle
public float getYLabelsAngle()
Sets the rotation angle (in degrees) of labels for the Y axis.
Parameters:
angle - the rotation angle of labels for the Y axis
getPointSize
public float getPointSize()
Method Detail
2848
setRange
public void setRange(double[] range,
int scale)
isInitialRangeSet
public boolean isInitialRangeSet(int scale)
Sets the axes initial range values. This will be used in the zoom fit tool.
Parameters:
range - an array having the values in this order: minX, maxX, minY, maxY
setInitialRange
public void setInitialRange(double[] range,
int scale)
Sets the axes initial range values. This will be used in the zoom fit tool.
Parameters:
range - an array having the values in this order: minX, maxX, minY, maxY
scale - the renderer scale
Method Detail
2849
getYAxisAlign
public int getYAxisAlign(int scale)
setYAxisAlign
public void setYAxisAlign(int align,
int scale)
Method Detail
2850
Method Detail
2851
setZoomInLimitX
public void setZoomInLimitX(double zoomInLimitX)
Sets the zoom in limit permitted in the axis X. This function prevent that the distance
between getXAxisMin() and getXAxisMax() can't be greater or equal than
getZoomInLimitX()
Parameters:
zoomInLimitX - the
getXAxisMax().
getZoomInLimitY
public double getZoomInLimitY()
setZoomInLimitY
public void setZoomInLimitY(double zoomInLimitY)
Sets zoom in limit permitted in the axis Y. This function prevent that the distance
between getYAxisMin() and getYAxisMax() can't be greater or equal than
getZoomInLimitY()
Parameters:
zoomInLimitY getYAxisMax()
Method Detail
2852
Method Detail
2853
Enum XYMultipleSeriesRenderer.Orientation
java.lang.Object
java.lang.Enum<XYMultipleSeriesRenderer.Orientation>
com.codename1.charts.renderers.XYMultipleSeriesRenderer.Orientation
All Implemented Interfaces:
Comparable<XYMultipleSeriesRenderer.Orientation>
Enclosing class:
XYMultipleSeriesRenderer
Method Summary
Modifier and Type
int
static
XYMultipleSeriesRenderer.Orientation
valueOf(String name)
static
XYMultipleSeriesRenderer.Orientation[]
VERTICAL
public static final XYMultipleSeriesRenderer.Orientation VERTICAL
Enum XYMultipleSeriesRenderer.Orientation
2854
Detail
values
public static XYMultipleSeriesRenderer.Orientation[] values()
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static XYMultipleSeriesRenderer.Orientation valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
getAngle
public int getAngle()
Method Detail
2855
Class SimpleSeriesRenderer
java.lang.Object
com.codename1.charts.renderers.SimpleSeriesRenderer
Direct Known Subclasses:
XYSeriesRenderer
public class
extends Object
Constructor Summary
Constructor and Description
SimpleSeriesRenderer()
Method Summary
Modifier and
Type
NumberFormat
int
int
double
int
double
BasicStroke
boolean
boolean
boolean
boolean
void
void
Returns if the bounding points of the first and last visible ones should be
displayed.
isGradientEnabled()
void
void
Class SimpleSeriesRenderer
Sets if the bounding points of the first and last visible ones should be
displayed.
setGradientEnabled(boolean enabled)
2856
void
void
void
void
void
Constructor Detail
SimpleSeriesRenderer
public SimpleSeriesRenderer()
Method Detail
getColor
public int getColor()
Method Summary
2857
Method Detail
2858
Sets if the item for this renderer should be highlighted. Pie chart is supported for now.
Parameters:
highlighted - the highlighted flag for the item for this renderer
isDisplayBoundingPoints
public boolean isDisplayBoundingPoints()
Returns if the bounding points of the first and last visible ones should be displayed.
Returns:
the bounding points display
setDisplayBoundingPoints
public void setDisplayBoundingPoints(boolean display)
Sets if the bounding points of the first and last visible ones should be displayed.
Parameters:
display - the bounding points display
getChartValuesFormat
public NumberFormat getChartValuesFormat()
Method Detail
2859
Class DialRenderer
java.lang.Object
com.codename1.charts.renderers.DefaultRenderer
com.codename1.charts.renderers.DialRenderer
public class
extends DefaultRenderer
DialRenderer.Type
Field Summary
Constructor Summary
Constructor and Description
DialRenderer()
Method Summary
Modifier and Type
double
double
double
double
double
double
DialRenderer.Type
boolean
boolean
void
Class DialRenderer
2860
void
void
void
void
void
void
Constructor Detail
DialRenderer
public DialRenderer()
Method Detail
getAngleMin
public double getAngleMin()
Method Summary
2861
Method Detail
2862
Method Detail
2863
Enum DialRenderer.Type
java.lang.Object
java.lang.Enum<DialRenderer.Type>
com.codename1.charts.renderers.DialRenderer.Type
All Implemented Interfaces:
Comparable<DialRenderer.Type>
Enclosing class:
DialRenderer
Method Summary
Modifier and Type
static DialRenderer.Type
static
DialRenderer.Type[]
Returns the enum constant of this type with the specified name.
values()
ARROW
public static final DialRenderer.Type ARROW
Method Detail
values
public static DialRenderer.Type[] values()
Enum DialRenderer.Type
2864
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static DialRenderer.Type valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
Method Detail
2865
Class DefaultRenderer
java.lang.Object
com.codename1.charts.renderers.DefaultRenderer
Direct Known Subclasses:
DialRenderer, XYMultipleSeriesRenderer
public class
extends Object
Field Summary
Modifier and Type
static int
static int
static int
A no color constant.
TEXT_COLOR
Constructor Summary
Constructor and Description
DefaultRenderer()
Method Summary
Modifier and Type
void
Class DefaultRenderer
addSeriesRenderer(SimpleSeriesRenderer renderer)
2866
getMargins()
SimpleSeriesRenderer[]
float
Font
int
int
int
int
float
boolean
boolean
boolean
boolean
boolean
boolean
Returns the start angle for circular charts such as pie, doughnut.
getTextTypeface()
Deprecated.
isAntialiasing()
Deprecated.
isDisplayValues()
Deprecated.
isFitLegend()
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
Method Summary
Deprecated.
isShowAxes()
2867
isShowLegend()
Deprecated.
isZoomEnabled()
Deprecated.
removeAllRenderers()
void
void
void
Sets the chart title font size using a Font object instead of a point
size.
setChartTitleTextSize(float textSize)
Deprecated.
setDisplayValues(boolean display)
void
void
void
Deprecated.
setFitLegend(boolean fit)
void
void
void
void
void
Sets the label title font size using a Font object instead of a point
size.
setLabelsTextSize(float textSize)
void
void
void
void
void
Method Summary
Sets the legend text font size using a Font object instead of a
point size.
setLegendTextSize(float textSize)
Deprecated.
setScale(float scale)
2868
void
void
void
void
void
void
void
void
void
void
void
void
Sets the start angle for circular charts such as pie, doughnut, etc.
setTextTypeface(Font typeface)
void
void
void
void
void
Deprecated.
setZoomEnabled(boolean enabled)
void
Deprecated.
setZoomRate(float rate)
void
Deprecated.
Field Detail
NO_COLOR
public static final int NO_COLOR
A no color constant.
See Also:
Constant Field Values
BACKGROUND_COLOR
public static final int BACKGROUND_COLOR
2869
Constructor Detail
DefaultRenderer
public DefaultRenderer()
Method Detail
getChartTitle
public String getChartTitle()
Sets the chart title font size using a Font object instead of a point size. This method is
the preferred way to set font size because it allows you to more easily have fonts
appear in an appropriate size for the target device. Alternatively check out
setChartTitleTextSize(float) to set the text size in pixels.
Parameters:
font addSeriesRenderer
public void addSeriesRenderer(SimpleSeriesRenderer renderer)
Field Detail
2870
Method Detail
2871
Method Detail
2872
Sets the label title font size using a Font object instead of a point size. This method is
the preferred way to set font size because it allows you to more easily have fonts
appear in an appropriate size for the target device. Alternatively check out
setLabelsTextSize(float) to set the text size in pixels.
Parameters:
font isShowAxes
public boolean isShowAxes()
Method Detail
2873
Method Detail
2874
Method Detail
2875
Sets the legend text font size using a Font object instead of a point size. This method
is the preferred way to set font size because it allows you to more easily have fonts
appear in an appropriate size for the target device. Alternatively check out
setLegendTextSize(float) to set the text size in pixels.
Parameters:
font setTextTypeface
public void setTextTypeface(int typefaceName,
int style)
Method Detail
2876
Sets the value to be used for scaling the chart. It works on some charts like pie,
doughnut, dial.
Parameters:
scale - the scale value
isZoomEnabled
public boolean isZoomEnabled()
Deprecated.
Returns the enabled state of the zoom.
Returns:
if zoom is enabled
setZoomEnabled
public void setZoomEnabled(boolean enabled)
Deprecated.
Sets the enabled state of the zoom.
Parameters:
enabled - zoom enabled
isZoomButtonsVisible
public boolean isZoomButtonsVisible()
Deprecated.
Returns the visible state of the zoom buttons.
Returns:
if zoom buttons are visible
setZoomButtonsVisible
public void setZoomButtonsVisible(boolean visible)
Deprecated.
Sets the visible state of the zoom buttons.
Parameters:
visible - if the zoom buttons are visible
isExternalZoomEnabled
public boolean isExternalZoomEnabled()
Deprecated.
Returns the enabled state of the external (application implemented) zoom.
Returns:
if external zoom is enabled
setExternalZoomEnabled
public void setExternalZoomEnabled(boolean enabled)
Deprecated.
Sets the enabled state of the external (application implemented) zoom.
Parameters:
enabled - external zoom enabled
getZoomRate
public float getZoomRate()
Deprecated.
Returns the zoom rate.
Returns:
the zoom rate
Method Detail
2877
Deprecated.
Returns the enabled state of the pan.
Returns:
if pan is enabled
setPanEnabled
public void setPanEnabled(boolean enabled)
Deprecated.
Sets the enabled state of the pan.
Parameters:
enabled - pan enabled
setZoomRate
public void setZoomRate(float rate)
Deprecated.
Sets the zoom rate.
Parameters:
rate - the zoom rate
isClickEnabled
public boolean isClickEnabled()
Deprecated.
Returns the enabled state of the click.
Returns:
if click is enabled
setClickEnabled
public void setClickEnabled(boolean enabled)
Deprecated.
Sets the enabled state of the click.
Parameters:
enabled - click enabled
getSelectableBuffer
public int getSelectableBuffer()
Method Detail
2878
getMargins
public int[] getMargins()
Returns the margin sizes. An array containing the margins in this order: top, left,
bottom, right
Returns:
the margin sizes
setMargins
public void setMargins(int[] margins)
Returns if the chart is inside a scroll view and doesn't need to shrink.
Returns:
if it is inside a scroll view
setInScroll
public void setInScroll(boolean inScroll)
To be set if the chart is inside a scroll view and doesn't need to shrink when not
enough space.
Parameters:
inScroll - if it is inside a scroll view
getStartAngle
public float getStartAngle()
Returns the start angle for circular charts such as pie, doughnut. An angle of 0
degrees correspond to the geometric angle of 0 degrees (3 o'clock on a watch.)
Returns:
the start angle in degrees
setStartAngle
public void setStartAngle(float startAngle)
Sets the start angle for circular charts such as pie, doughnut, etc. An angle of 0
degrees correspond to the geometric angle of 0 degrees (3 o'clock on a watch.)
Parameters:
startAngle - the start angle in degrees
isDisplayValues
public boolean isDisplayValues()
Method Detail
2879
Class BasicStroke
java.lang.Object
com.codename1.charts.renderers.BasicStroke
public class
extends Object
Field Summary
Modifier and Type Field and Description
static BasicStroke
static BasicStroke
static BasicStroke
DASHED
Constructor Summary
Constructor and Description
BasicStroke(int cap, int join, float miter, float[] intervals, float phase)
Method Summary
Modifier and Type
int
float[]
getIntervals()
int
float
float
Field Detail
SOLID
public static final BasicStroke SOLID
Class BasicStroke
2880
Constructor Detail
BasicStroke
public BasicStroke(int cap,
int join,
float miter,
float[] intervals,
float phase)
Method Detail
getCap
public int getCap()
Field Detail
2881
Method Detail
2882
Class XYValueSeries
java.lang.Object
com.codename1.charts.models.XYSeries
com.codename1.charts.models.XYValueSeries
public class
extends XYSeries
An extension of the XY series which adds a third dimension. It is used for XY charts like bubble.
Constructor Summary
Constructor and Description
XYValueSeries(String title)
Method Summary
Modifier and Type
void
void
void
double
double
double
getMaxValue()
void
Constructor Detail
Class XYValueSeries
2883
Method Detail
add
public void add(double x,
double y,
double value)
Constructor Detail
2884
Method Detail
2885
Class XYSeries
java.lang.Object
com.codename1.charts.models.XYSeries
Direct Known Subclasses:
TimeSeries, XYValueSeries
public class
extends Object
An XY series encapsulates values for XY charts like line, time, area, scatter... charts.
Constructor Summary
Constructor and Description
XYSeries(String title)
Method Summary
Modifier and Type
void
void
void
addAnnotation(String annot
double x, double y)
void
void
void
String
int
getAnnotationAt(int index)
double
double
getAnnotationY(int index)
Class XYSeries
2886
getIndexForKey(double key)
getItemCount()
int
double
getMaxY()
double
getMinX()
double
getMinY()
double
protected double
getPadding(double x)
getRange(double start,
double stop,
boolean beforeAfterPoints)
SortedMap<Double,Double>
int
getScaleNumber()
getTitle()
String
double
getXYMap()
com.codename1.charts.models.XYSeries.IndexXYMap<Double,Double>
double
remove(int index)
void
removeAnnotation(int index
void
void
Constructor Detail
XYSeries
public XYSeries(String title)
Method Summary
2887
Method Detail
getScaleNumber
public int getScaleNumber()
getTitle
public String getTitle()
remove
public void remove(int index)
Removes all the existing values and annotations from the series.
Constructor Detail
2888
Removes all the existing values from the series but annotations.
clearAnnotations
public void clearAnnotations()
Returns the current values that are used for drawing the series.
Returns:
the XY map
getX
public double getX(int index)
Method Detail
2889
Returns submap of x and y values according to the given start and end
Parameters:
start - start x value
stop - stop x value
beforeAfterPoints - if the points before and after the first and last visible
ones must be displayed
Returns:
a submap of x and y values
getIndexForKey
public int getIndexForKey(double key)
getItemCount
public int getItemCount()
Method Detail
2890
Method Detail
2891
Class XYMultipleSeriesDataset
java.lang.Object
com.codename1.charts.models.XYMultipleSeriesDataset
public class
extends Object
Constructor Summary
Constructor and Description
XYMultipleSeriesDataset()
Method Summary
Modifier and Type
void
void
void
void
XYSeries[]
XYSeries
getSeries()
int
void
void
Constructor Detail
XYMultipleSeriesDataset
public XYMultipleSeriesDataset()
Method Detail
Class XYMultipleSeriesDataset
2892
Method Detail
2893
Class TimeSeries
java.lang.Object
com.codename1.charts.models.XYSeries
com.codename1.charts.models.TimeSeries
public class
extends XYSeries
Constructor Summary
Constructor and Description
TimeSeries(String title)
Method Summary
Modifier and Type
void
protected double
getPadding(double x)
Constructor Detail
TimeSeries
public TimeSeries(String title)
Method Detail
Class TimeSeries
2894
Overrides:
getPadding
Method Detail
in class XYSeries
2895
Class SeriesSelection
java.lang.Object
com.codename1.charts.models.SeriesSelection
public class
extends Object
Constructor Summary
Constructor and Description
SeriesSelection(int seriesIndex, int pointIndex, double xValue, double value)
Method Summary
Modifier and Type Method and Description
int
getPointIndex()
int
getSeriesIndex()
double
getValue()
double
getXValue()
Constructor Detail
SeriesSelection
public SeriesSelection(int seriesIndex,
int pointIndex,
double xValue,
double value)
Method Detail
getSeriesIndex
public int getSeriesIndex()
getPointIndex
public int getPointIndex()
getXValue
public double getXValue()
getValue
public double getValue()
Class SeriesSelection
2896
Class RangeCategorySeries
java.lang.Object
com.codename1.charts.models.CategorySeries
com.codename1.charts.models.RangeCategorySeries
public class
extends CategorySeries
A series for the range category charts like the range bar.
Constructor Summary
Constructor and Description
RangeCategorySeries(String title)
Method Summary
Modifier and Type
void
void
void
double
double
void
XYSeries
toXYSeries()
Constructor Detail
RangeCategorySeries
public RangeCategorySeries(String title)
Method Detail
2897
Detail
add
public void add(double minValue,
double maxValue)
Method Detail
2898
Class Point
java.lang.Object
com.codename1.charts.models.Point
Constructor Summary
Constructor and Description
Point()
Point(float x, float y)
Method Summary
Modifier and Type Method and Description
float
getX()
float
getY()
void
setX(float x)
void
setY(float y)
Constructor Detail
Point
public Point()
Point
public Point(float x,
float y)
Method Detail
getX
public float getX()
getY
public float getY()
setX
public void setX(float x)
Class Point
2899
Method Detail
2900
Class MultipleCategorySeries
java.lang.Object
com.codename1.charts.models.MultipleCategorySeries
public class
extends Object
Constructor Summary
Constructor and Description
MultipleCategorySeries(String title)
Method Summary
Modifier and Type
void
void
void
int
String
int
String[]
double[]
getTitles(int index)
void
XYSeries
toXYSeries()
Constructor Detail
MultipleCategorySeries
public MultipleCategorySeries(String title)
Class MultipleCategorySeries
2901
Method Detail
add
public void add(String[] titles,
double[] values)
Constructor Detail
2902
Method Detail
2903
Class CategorySeries
java.lang.Object
com.codename1.charts.models.CategorySeries
Direct Known Subclasses:
RangeCategorySeries
public class
extends Object
Constructor Summary
Constructor and Description
CategorySeries(String title)
Method Summary
Modifier and Type
void
void
void
String
int
String
double
void
void
XYSeries
toXYSeries()
Constructor Detail
Class CategorySeries
2904
Method Detail
getTitle
public String getTitle()
Constructor Detail
2905
Method Detail
2906
Class PathMeasure
java.lang.Object
com.codename1.charts.compat.PathMeasure
Deprecated.
public class
extends Object
Constructor Summary
Constructor and Description
PathMeasure(GeneralPath p, boolean b)
Deprecated.
Method Summary
Modifier and Type
Deprecated.
float
Deprecated.
void
Constructor Detail
PathMeasure
public PathMeasure(GeneralPath p,
boolean b)
Deprecated.
Method Detail
getLength
public float getLength()
Deprecated.
getPosTan
public void getPosTan(int i,
float[] coords,
float[] tan)
Deprecated.
Class PathMeasure
2907
Class Paint
java.lang.Object
com.codename1.charts.compat.Paint
Deprecated.
public class
extends Object
Deprecated.
Paint.Cap
static class
Deprecated.
Paint.Join
static class
Deprecated.
Paint.Style
static class
Deprecated.
Constructor Summary
Constructor and Description
Paint()
Deprecated.
Method Summary
Modifier and
Type
int
Deprecated.
getColor()
int
Deprecated.
getStrokeCap()
int
Deprecated.
getStrokeJoin()
int
Deprecated.
float
getStrokeMiter()
Deprecated.
Method Detail
2908
getStrokeWidth()
float
Deprecated.
getStyle()
Paint.Style
Deprecated.
getTextAlign()
int
void
Deprecated.
getTextBounds(String string, int start, int count,
Rectangle2D rect)
Deprecated.
getTextSize()
float
Deprecated.
getTextWidths(String text, float[] widths)
void
Deprecated.
getTypeface()
Font
Deprecated.
measureText(char[] chars, int start, int count)
float
Deprecated.
measureText(String newText)
float
Deprecated.
setAntiAlias(boolean antialiasing)
void
Deprecated.
setColor(int color)
void
Deprecated.
setStrokeCap(int cap)
void
Deprecated.
setStrokeJoin(int join)
void
Deprecated.
setStrokeMiter(float miter)
void
Deprecated.
setStrokeWidth(float i)
void
Deprecated.
setStyle(Paint.Style style)
void
Deprecated.
setTextAlign(int align)
void
Deprecated.
setTextSize(float size)
void
Deprecated.
setTypeface(Font textTypeface)
void
Deprecated.
String
toString()
Method Summary
2909
Constructor Detail
Paint
public Paint()
Deprecated.
Method Detail
getTextWidths
public void getTextWidths(String text,
float[] widths)
Deprecated.
breakText
public int breakText(String text,
boolean measureForwards,
float maxWidth,
float[] measuredWidth)
Deprecated.
getTextBounds
public void getTextBounds(String string,
int start,
int count,
Rectangle2D rect)
Deprecated.
measureText
public float measureText(String newText)
Deprecated.
measureText
public float measureText(char[] chars,
int start,
int count)
Deprecated.
setAntiAlias
public void setAntiAlias(boolean antialiasing)
Deprecated.
getTypeface
public Font getTypeface()
Deprecated.
2910
Deprecated.
getStrokeCap
public int getStrokeCap()
Deprecated.
getStrokeJoin
public int getStrokeJoin()
Deprecated.
getStrokeMiter
public float getStrokeMiter()
Deprecated.
getStyle
public Paint.Style getStyle()
Deprecated.
setStrokeCap
public void setStrokeCap(int cap)
Deprecated.
setStrokeJoin
public void setStrokeJoin(int join)
Deprecated.
setStrokeMiter
public void setStrokeMiter(float miter)
Deprecated.
getStrokeWidth
public float getStrokeWidth()
Deprecated.
setStrokeWidth
public void setStrokeWidth(float i)
Deprecated.
getColor
public int getColor()
Deprecated.
setColor
public void setColor(int color)
Deprecated.
setStyle
public void setStyle(Paint.Style style)
Deprecated.
Method Detail
2911
Deprecated.
getTextAlign
public int getTextAlign()
Deprecated.
setTextSize
public void setTextSize(float size)
Deprecated.
getTextSize
public float getTextSize()
Deprecated.
toString
public String toString()
Deprecated.
Description copied from class: Object
Returns a string representation of the object. In general, the toString method returns
a string that "textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is recommended that
all subclasses override this method. The toString method for class Object returns a
string consisting of the name of the class of which the object is an instance, the
at-sign character `@', and the unsigned hexadecimal representation of the hash code
of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Overrides:
toString in class Object
Method Detail
2912
Enum Paint.Style
java.lang.Object
java.lang.Enum<Paint.Style>
com.codename1.charts.compat.Paint.Style
All Implemented Interfaces:
Comparable<Paint.Style>
Enclosing class:
Paint
Method Summary
Modifier and Type
static Paint.Style
static
Paint.Style[]
Returns the enum constant of this type with the specified name.
values()
FILL_AND_STROKE
public static final Paint.Style FILL_AND_STROKE
STROKE
public static final Paint.Style STROKE
Method Detail
Enum Paint.Style
2913
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
for (Paint.Style c : Paint.Style.values())
System.out.println(c);
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static Paint.Style valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
Method Detail
2914
Class Paint.Join
java.lang.Object
com.codename1.charts.compat.Paint.Join
Enclosing class:
Paint
Field Summary
Modifier and Type Field and Description
static int
BEVEL
static int
MITER
static int
ROUND
Constructor Summary
Constructor and Description
Join()
Method Summary
Field Detail
BEVEL
public static final int BEVEL
See Also:
Constant Field Values
MITER
public static final int MITER
See Also:
Constant Field Values
ROUND
public static final int ROUND
See Also:
Constant Field Values
Class Paint.Join
2915
Detail
Join
public Join()
Constructor Detail
2916
Class Paint.Cap
java.lang.Object
com.codename1.charts.compat.Paint.Cap
Enclosing class:
Paint
Field Summary
Modifier and Type Field and Description
static int
BUTT
static int
ROUND
static int
SQUARE
Constructor Summary
Constructor and Description
Cap()
Method Summary
Field Detail
BUTT
public static final int BUTT
See Also:
Constant Field Values
ROUND
public static final int ROUND
See Also:
Constant Field Values
SQUARE
public static final int SQUARE
See Also:
Constant Field Values
Class Paint.Cap
2917
Detail
Cap
public Cap()
Constructor Detail
2918
Class Paint.Align
java.lang.Object
com.codename1.charts.compat.Paint.Align
Enclosing class:
Paint
Field Summary
Modifier and Type Field and Description
static int
CENTER
static int
LEFT
static int
RIGHT
Constructor Summary
Constructor and Description
Align()
Method Summary
Field Detail
CENTER
public static final int CENTER
See Also:
Constant Field Values
LEFT
public static final int LEFT
See Also:
Constant Field Values
RIGHT
public static final int RIGHT
See Also:
Constant Field Values
Class Paint.Align
2919
Detail
Align
public Align()
Constructor Detail
2920
Class GradientDrawable
java.lang.Object
com.codename1.charts.compat.GradientDrawable
public class
extends Object
Constructor Summary
Constructor and Description
GradientDrawable(GradientDrawable.Orientation orientation, int[] colors)
Method Summary
Modifier and Type
void
draw(Canvas canvas)
void
Constructor Detail
GradientDrawable
public GradientDrawable(GradientDrawable.Orientation orientation,
int[] colors)
Method Detail
setBounds
public void setBounds(int
int
int
int
left,
top,
right,
bottom)
draw
public void draw(Canvas canvas)
Class GradientDrawable
2921
Enum GradientDrawable.Orientation
java.lang.Object
java.lang.Enum<GradientDrawable.Orientation>
com.codename1.charts.compat.GradientDrawable.Orientation
All Implemented Interfaces:
Comparable<GradientDrawable.Orientation>
Enclosing class:
GradientDrawable
Method Summary
Modifier and Type
static
GradientDrawable.Orientation
static
GradientDrawable.Orientation[]
Method Detail
2922
BR_TL
public static final GradientDrawable.Orientation BR_TL
LEFT_RIGHT
public static final GradientDrawable.Orientation LEFT_RIGHT
RIGHT_LEFT
public static final GradientDrawable.Orientation RIGHT_LEFT
TL_BR
public static final GradientDrawable.Orientation TL_BR
TOP_BOTTOM
public static final GradientDrawable.Orientation TOP_BOTTOM
TR_BL
public static final GradientDrawable.Orientation TR_BL
Method Detail
values
public static GradientDrawable.Orientation[] values()
Returns an array containing the constants of this enum type, in the order they are
declared. This method may be used to iterate over the constants as follows:
for (GradientDrawable.Orientation c : GradientDrawable.Orientation.values())
System.out.println(c);
Returns:
an array containing the constants of this enum type, in the order they are
declared
valueOf
public static GradientDrawable.Orientation valueOf(String name)
Returns the enum constant of this type with the specified name. The string must
match exactly an identifier used to declare an enum constant in this type.
(Extraneous whitespace characters are not permitted.)
Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the
specified name
NullPointerException - if the argument is null
2923
Class Canvas
java.lang.Object
com.codename1.charts.compat.Canvas
Deprecated.
public class
extends Object
An internal compatibility class for use by the Charts library. Since the library was ported from an
Android library, it made use of Canvas and Paint, so rather than rewriting all of this, we added a
Canvas and Paint compatibility layer. **DO NOT USE DIRECTLY**
Field Summary
Modifier and Type Field and Description
absoluteX
int
Deprecated.
absoluteY
int
Deprecated.
bounds
Rectangle
Deprecated.
g
Graphics
Deprecated.
Constructor Summary
Constructor and Description
Canvas()
Deprecated.
Method Summary
Modifier and
Type
void
Deprecated.
drawBitmap(Image img, float left, float top, Paint paint)
void
Deprecated.
drawCircle(float cx, float cy, float r, Paint paint)
void
Deprecated.
drawLine(float x1, float y1, float x2, float y2, Paint paint)
void
Method Detail
Deprecated.
2924
Deprecated.
void
Deprecated.
void
void
Deprecated.
drawRoundRect(Rectangle2D rect, float rx, float ry, Paint mPaint)
Deprecated.
void
Deprecated.
void
getClipBounds(Rectangle mRect)
Deprecated.
void
getHeight()
Deprecated.
int
getWidth()
Deprecated.
int
Deprecated.
void
scale(float x, float y)
Deprecated.
void
translate(float x, float y)
Deprecated.
void
Field Detail
g
public Graphics g
Deprecated.
bounds
public Rectangle bounds
Deprecated.
absoluteX
public int absoluteX
Deprecated.
absoluteY
public int absoluteY
Deprecated.
Method Summary
2925
Detail
Canvas
public Canvas()
Deprecated.
Method Detail
getClipBounds
public void getClipBounds(Rectangle mRect)
Deprecated.
drawRect
public void drawRect(float
float
float
float
Paint
left,
top,
right,
bottom,
paint)
Deprecated.
drawText
public void drawText(String string,
float x,
float y,
Paint paint)
Deprecated.
getHeight
public int getHeight()
Deprecated.
getWidth
public int getWidth()
Deprecated.
drawPath
public void drawPath(Shape p,
Paint paint)
Deprecated.
drawLine
public void drawLine(float
float
float
float
Paint
x1,
y1,
x2,
y2,
paint)
Deprecated.
rotate
public void rotate(float angle,
float x,
float y)
Deprecated.
Constructor Detail
2926
Deprecated.
translate
public void translate(float x,
float y)
Deprecated.
drawCircle
public void drawCircle(float
float
float
Paint
cx,
cy,
r,
paint)
Deprecated.
drawArc
public void drawArc(Rectangle2D oval,
float currentAngle,
float sweepAngle,
boolean useCenter,
Paint paint)
Deprecated.
drawPoint
public void drawPoint(Float get,
Float get0,
Paint paint)
Deprecated.
drawRoundRect
public void drawRoundRect(Rectangle2D rect,
float rx,
float ry,
Paint mPaint)
Deprecated.
drawBitmap
public void drawBitmap(Image
float
float
Paint
img,
left,
top,
paint)
Deprecated.
Method Detail
2927
Class ChartUtil
java.lang.Object
com.codename1.charts.ChartUtil
public class
extends Object
A utility class for painting a chart onto a Graphics context. This is a low level API. You should use the
ChartComponent class instead.
Constructor Summary
Constructor and Description
ChartUtil()
Method Summary
Modifier and Type
void
Constructor Detail
ChartUtil
public ChartUtil()
Method Detail
paintChart
public void paintChart(Graphics g,
AbstractChart chart,
Rectangle bounds,
int absX,
int absY)
Class ChartUtil
2928
Class ChartComponent
java.lang.Object
com.codename1.ui.Component
com.codename1.charts.ChartComponent
All Implemented Interfaces:
Animation, StyleListener
public class
extends Component
Method Detail
2929
The above screenshots were taken from the ChartsDemo app. Y ou can start playing with this app
by checking it out from our git repository.
How to Create A Chart
Adding a chart to your app involves four steps:
1. Build the model. You can construct a model (aka data set) for the chart using one of the
existing model classes in the com.codename1.charts.models package. Essentially, this is just
where you add the data that you want to display.
2. Set up a renderer. You can create a renderer for your chart using one of the existing
renderer classes in the com.codename1.charts.renderers package. The renderer allows you
to specify how the chart should look. E.g. the colors, fonts, styles, to use.
3. Create the Chart View. Use one of the existing view classes in the
com.codename1.charts.views package.
4. Create a com.codename1.charts,ChartComponent . In order to add your chart to the UI, you
need to wrap it in a com.codename1.charts,ChartComponent object.
You can check out the ChartsDemo app for specific examples, but here is a high level view of some
code that creates a Pie Chart.
The charts package is derived work from the excellent open source aChartEngine API.
Class ChartComponent
2930
Summary
Constructor Summary
Constructor and Description
ChartComponent(AbstractChart chart)
Method Summary
Modifier and
Type
protected
Dimension
Point
Shape
AbstractChart
Transform
boolean
boolean
void
void
If this Component is focused, the pointer dragged event will call this
method
pointerPressed(int x, int y)
void
If this Component is focused, the pointer pressed event will call this
method
pointerReleased(int x, int y)
void
Point
If this Component is focused, the pointer released event will call this
method
screenToChartCoord(int x, int y)
Shape
protected void
protected void
void
void
Field Summary
2931
setTransform(Transform transform)
void
void
setZoomEnabled(boolean zoomEnabled)
zoomToShapeInChartCoords(Shape s)
void
void
Method Summary
2932
Detail
ChartComponent
public ChartComponent(AbstractChart chart)
Method Detail
getChart
public AbstractChart getChart()
Constructor Detail
2933
Returns:
a position within the screen
screenToChartShape
public Shape screenToChartShape(Shape s)
Converts a chart coordinate spaced shape to the same shape in the screen
coordinate space
Parameters:
s - shape in screen coordinates
Returns:
same shape using chart space coordinates
chartToScreenShape
public Shape chartToScreenShape(Shape s)
Converts a screen coordinate spaced shape to the same shape in the chart
coordinate space
Parameters:
s - shape in chart coordinates
Returns:
same shape using screen coordinate space
zoomToShapeInChartCoords
public void zoomToShapeInChartCoords(Shape s)
Zooms the view port to show a specified shape. The shape should be expressed in
chart coordinates (not screen coordinates).
Parameters:
s - The shape that should be shown.
zoomToShapeInChartCoords
public void zoomToShapeInChartCoords(Shape s,
int duration)
Zooms the view port to show a specified shape. The shape should be expressed in
chart coordinates (not screen coordinates).
Parameters:
s - The shape that should be shown.
duration - The duration of the transition.
pointerPressed
public void pointerPressed(int x,
int y)
Called when a pointer is pressed on a series in the chart. This can be overridden by
subclasses to respond to this event.
Parameters:
sel pointerReleased
public void pointerReleased(int x,
int y)
Method Detail
2934
Called when a pointer is released from a series in the chart. This can be overridden in
subclasses to handle these events.
Parameters:
sel getTransform
public Transform getTransform()
Gets the transform for the chart. This can be used to scale, translate, and rotate the
chart. This transform assumes its origin at the (absoluteX, absoluteY) of the
component at the time it is drawn rather than the screen's origin as is normally the
case with transforms. This allows the transform to be applied consistently with
respect to the chart's coordinates even when the component is moved around the
screen.
Returns:
The transform for the chart in component coordinates.
setTransform
public void setTransform(Transform transform)
Sets the transform for the chart. Transforms origin assumed to be at (getAbsoluteX,
getAbsoluteY).
Parameters:
transform - the transform to set
pointerDragged
public void pointerDragged(int[] x,
int[] y)
Parameters:
panEnabled
isZoomEnabled
public boolean isZoomEnabled()
Returns:
the zoomEnabled
Method Detail
2935
setZoomEnabled
public void setZoomEnabled(boolean zoomEnabled)
Parameters:
zoomEnabled
Method Detail
2936
Class Capture
java.lang.Object
com.codename1.capture.Capture
public class
extends Object
This is the main class for capturing media files from the device. Use this class to invoke the native
camera to capture images, audio or video Notice that files returned by this class are potentially
temporary files and might be deleted by the OS in the future.
Constructor Summary
Constructor and Description
Capture()
Method Summary
Modifier and
Type
static String
static void
This method tries to invoke the device native hardware to capture audio.
capturePhoto()
static String
static void
Invokes the camera and takes a photo synchronously while blocking the
EDT
capturePhoto(ActionListener response)
This method tries to invoke the device native camera to capture images.
capturePhoto(int width, int height)
static String
static String
static void
static boolean
Invokes the camera and takes a photo synchronously while blocking the
EDT
captureVideo()
This method tries to invoke the device native camera to capture video.
hasCamera()
Constructor Detail
Capture
public Capture()
Class Capture
2937
Method Detail
hasCamera
public static boolean hasCamera()
This method tries to invoke the device native camera to capture images. The method
returns immediately and the response will be sent asynchronously to the given
ActionListener Object The image is saved as a jpeg to a file on the device. use this in
the actionPerformed to retrieve the file path String path = (String) evt.getSource(); if
evt returns null the image capture was cancelled by the user.
Parameters:
response - a callback Object to retrieve the file path
Throws:
RuntimeException - if this feature failed or unsupported on the platform
capturePhoto
public static String capturePhoto()
Invokes the camera and takes a photo synchronously while blocking the EDT
Returns:
the photo file location or null if the user canceled
captureAudio
public static String captureAudio()
Invokes the camera and takes a photo synchronously while blocking the EDT
Parameters:
width - the target width for the image if possible, some platforms don't
support scaling. To maintain aspect ratio set to -1
height - the target height for the image if possible, some platforms don't
support scaling. To maintain aspect ratio set to -1
Returns:
the photo file location or null if the user canceled
captureAudio
public static void captureAudio(ActionListener response)
This method tries to invoke the device native hardware to capture audio. The method
returns immediately and the response will be sent asynchronously to the given
ActionListener Object The audio is saved to a file on the device. use this in the
actionPerformed to retrieve the file path String path = (String) evt.getSource();
Parameters:
response - a callback Object to retrieve the file path
Method Detail
2938
Throws:
RuntimeException
captureVideo
public static void captureVideo(ActionListener response)
This method tries to invoke the device native camera to capture video. The method
returns immediately and the response will be sent asynchronously to the given
ActionListener Object The video is saved to a file on the device. use this in the
actionPerformed to retrieve the file path String path = (String) evt.getSource();
Parameters:
response - a callback Object to retrieve the file path
Throws:
RuntimeException - if this feature failed or unsupported on the platform
Method Detail
2939
Class AnalyticsService
java.lang.Object
com.codename1.analytics.AnalyticsService
public class
extends Object
The analytics service allows an application to report its usage, it is seamlessly invoked by GUI builder
applications if analytics is enabled for your application! To enable analytics just use the init() method
of the analytics service. If you are not using the GUI builder invoke the visit method whenever you
would like to log a page view event.
Constructor Summary
Constructor and Description
AnalyticsService()
Method Summary
Modifier
and Type
static void
static void
protected
boolean
static
boolean
Apps mode allows improved analytics using the newer google analytics API
designed for apps
static
boolean
isEnabled()
static
boolean
isFailSilently()
static void
static void
static void
Apps mode allows improved analytics using the newer google analytics API
designed for apps
setFailSilently(boolean aFailSilently)
static void
protected
void
Class AnalyticsService
2940
Constructor Detail
AnalyticsService
public AnalyticsService()
Method Detail
isFailSilently
public static boolean isFailSilently()
Apps mode allows improved analytics using the newer google analytics API designed
for apps
Returns:
the appsMode
setAppsMode
public static void setAppsMode(boolean aAppsMode)
Apps mode allows improved analytics using the newer google analytics API designed
for apps
Parameters:
aAppsMode - the appsMode to set
isEnabled
public static boolean isEnabled()
Indicates if the analytics is enabled, subclasses must override this method to process
their information
Returns:
true if analytics is enabled
init
public static void init(String agent,
String domain)
2941
Sends an asynchronous notice to the server regarding a page in the application being
viewed, notice that you don't need to append the URL prefix to the page string.
Parameters:
page - the page viewed
referer - the source page
visitPage
protected void visitPage(String page,
String referer)
In apps mode we can send information about an exception to the analytics server
Parameters:
t - the exception
message - up to 150 character message,
fatal - is the exception fatal
Method Detail
2942
Class InnerActive
java.lang.Object
com.codename1.io.ConnectionRequest
com.codename1.ads.AdsService
com.codename1.ads.InnerActive
All Implemented Interfaces:
IOProgressListener
public class
extends AdsService
Field Summary
Constructor Summary
Constructor and Description
InnerActive()
Method Summary
Modifier and Type
void
protected void
readResponse(InputStream input)
Callback for the server response with the input stream from the server.
setBanner(boolean banner)
void
static void
setTestAds(boolean test)
If true and no ads exists the network will return house holds ads
Class InnerActive
2943
Constructor Detail
InnerActive
public InnerActive()
Method Detail
setBanner
public void setBanner(boolean banner)
If true and no ads exists the network will return house holds ads
Parameters:
testAds initService
public void initService(Ads ads)
Callback for the server response with the input stream from the server. This method
is invoked on the network thread
Overrides:
readResponse in class AdsService
Parameters:
2944
Throws:
IOException
Method Detail
2945
Class AdsService
java.lang.Object
com.codename1.io.ConnectionRequest
com.codename1.ads.AdsService
All Implemented Interfaces:
IOProgressListener
Direct Known Subclasses:
InnerActive
This is an abstract Ads Service. Each supported Ad network needs to extend this Service and to
implement the initService method
Field Summary
Constructor Summary
Modifier Constructor and Description
protected
AdsService()
Empty constructor
Method Summary
Modifier and
Type
static
AdsService
String
protected
void
protected
void
protected
void
void
abstract void
void
Handles a server response code that is not 200 and not a redirect (unless
redirect handling is disabled)
handleException(Exception err)
Class AdsService
2946
Callback for the server response with the input stream from the server.
requestAd()
void
Schedule this service on the Network thread and executes the request
static void
setAdsProvider(Class provider)
Constructor Detail
AdsService
protected AdsService()
Empty constructor
Method Detail
initialize
public void initialize(Ads adsComponent)
Method Summary
2947
Schedule this service on the Network thread and executes the request
readResponse
protected void readResponse(InputStream input)
throws IOException
Callback for the server response with the input stream from the server. This method
is invoked on the network thread
Overrides:
readResponse in class ConnectionRequest
Parameters:
input - the input stream containing the response
Throws:
IOException - when a read input occurs
onAdDisplay
public void onAdDisplay(HTMLComponent cmp)
Handles a server response code that is not 200 and not a redirect (unless redirect
handling is disabled)
Overrides:
handleErrorResponseCode in class ConnectionRequest
Parameters:
code - the response code from the server
message - the response message from the server
handleRuntimeException
protected void handleRuntimeException(RuntimeException err)
Method Detail
2948
Method Detail
2949
All Classes
AbstractChart
AbstractCollection
AbstractLayer
AbstractList
AbstractMap
AbstractMap.SimpleEntry
AbstractMap.SimpleImmutableEntry
AbstractQueue
AbstractSequentialList
AbstractSet
AbstractTest
AC
AccessToken
ActionEvent
ActionEvent.Type
ActionListener
Address
Adler32
Ads
AdsService
Album
AnalyticsService
Animation
AnimationManager
AnimationObject
Annotation
AnnotationFormatError
Appendable
ArithmeticException
ArrayDeque
ArrayIndexOutOfBoundsException
ArrayList
Arrays
ArrayStoreException
ArrowLinesLayer
AssertionError
AsyncDocumentRequestHandler
AsyncDocumentRequestHandlerImpl
AutoCloseable
AutoCompleteTextField
BackgroundPainter
BarChart
BarChart.Type
Base64
BaseSpinner
BasicStroke
BigDecimal
BigInteger
BindTarget
BitSet
Boolean
Border
BorderLayout
BoundingBox
BoundSize
BoxLayout
BrowserComponent
BrowserNavigationCallback
BubbleChart
BufferedInputStream
BufferedOutputStream
Button
ButtonGroup
All Classes
2950
All Classes
2951
All Classes
2952
All Classes
2953
All Classes
2954
All Classes
2955
All Classes
2956
All Classes
2957
All Classes
2958
All Classes
AbstractChart
AbstractCollection
AbstractLayer
AbstractList
AbstractMap
AbstractMap.SimpleEntry
AbstractMap.SimpleImmutableEntry
AbstractQueue
AbstractSequentialList
AbstractSet
AbstractTest
AC
AccessToken
ActionEvent
ActionEvent.Type
ActionListener
Address
Adler32
Ads
AdsService
Album
AnalyticsService
Animation
AnimationManager
AnimationObject
Annotation
AnnotationFormatError
Appendable
ArithmeticException
ArrayDeque
ArrayIndexOutOfBoundsException
ArrayList
Arrays
ArrayStoreException
ArrowLinesLayer
AssertionError
AsyncDocumentRequestHandler
AsyncDocumentRequestHandlerImpl
AutoCloseable
AutoCompleteTextField
BackgroundPainter
BarChart
BarChart.Type
Base64
BaseSpinner
BasicStroke
BigDecimal
BigInteger
BindTarget
BitSet
Boolean
Border
BorderLayout
BoundingBox
BoundSize
BoxLayout
BrowserComponent
BrowserNavigationCallback
BubbleChart
BufferedInputStream
BufferedOutputStream
Button
ButtonGroup
All Classes
2959
All Classes
2960
All Classes
2961
All Classes
2962
All Classes
2963
All Classes
2964
All Classes
2965
All Classes
2966
All Classes
2967