Problem with ActionListener to give a buttona value - user-interface

I'm trying to give a functions to an array of jbuttons with ActionListener
but when I pass 'i' as variable it gives erorr :
App.java:45: error: local variables referenced from an inner class must be final or effectively final
the error is on line 45, 58, and 71.
Here's the code :
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class App extends JFrame {
App(){
JFrame calcFrame = new JFrame();
calcFrame.setSize(320, 420);
calcFrame.setVisible(true);
calcFrame.setTitle("Calculator");
calcFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
calcFrame.setResizable(false);
calcFrame.getContentPane().setBackground(new Color(0x123456));
//add panel
JTextField textField = new JTextField();
textField.setBounds(35, 20, 200, 100);
textField.setBackground(new Color(0x000000));
calcFrame.add(textField);
JButton cbtn = new JButton(String.valueOf('c')); // clear button
cbtn.setBounds(240, 140, 50, 50);
calcFrame.add(cbtn);
JButton pbtn = new JButton(String.valueOf('^')); // power button
pbtn.setBounds(240, 200, 50, 50);
calcFrame.add(pbtn);
/*Add array of buttuns from 0 ... 9 */
JButton nums[] = new JButton[10];
calcFrame.getContentPane().setLayout(null);
// organzie using if statment
for(int i = 0; i < 4; i++)
{
nums[i] = new JButton(String.valueOf(i)); // organzie first line 0 ... 3
nums[i].setBounds(i * 60, 140, 50, 50);
nums[i].addActionListener(new ActionListener(){
//give buttons a function
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
});
calcFrame.add(nums[i]);
}
for(int i = 4, j = 0; i < 8; i++, j++)//organzie second line 4 ... 7
{
nums[i] = new JButton(String.valueOf(i));
nums[i].setBounds(j * 60, 200, 50, 50);
nums[i].addActionListener(new ActionListener(){
//give buttons a function
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
});
calcFrame.add(nums[i]);
}
for(int i = 8, j = 0; i < 10; i++, j++)//last numbers line 8 ... 9
{
nums[i] = new JButton(String.valueOf(i));
nums[i].setBounds(j * 60, 260, 50, 50);
nums[i].addActionListener(new ActionListener(){
//give buttons a function
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
});
calcFrame.add(nums[i]);
}
//End of numbers 0 ... 9
JButton dotbtn = new JButton();
JButton eqlbtn = new JButton();
dotbtn = new JButton(String.valueOf('.'));// dot button for a value less than 1
dotbtn.setBounds(120, 260, 50, 50);
calcFrame.add(dotbtn);
eqlbtn = new JButton(String.valueOf('=')); //equal button
eqlbtn.setBounds(180, 260, 50, 50);;
calcFrame.add(eqlbtn);
String[] arthmetictools = {"+", "-", "x", "/"};
JButton[] artbtns = new JButton[4]; // array of arthmetic buttons
for (int i = 0; i <= 4; i++) {
artbtns[i] = new JButton(String.valueOf(arthmetictools[i]));
artbtns[i].setBounds( 60 * i, 320, 50, 50);
calcFrame.add(artbtns[i]);
}
}
public static void main(String[] args) {
System.out.println("Hello, World!");
/* make the frame call it calc frame */
App calc = new App();
}
}
Thank you.
Tried to set text field to string of i from for loop.

Related

Fill a text with JLabel entered by user

I am making a project that fill a text with information entered previously by a user.
For that, I am using the library JFrame.
So I have the form in the left of the panel and I want to put the filled text in the right when I click on the submit button.
My problem is that I don't undertand how to put the information in the right place of the text.
And for the moment the text doesn't appear at all in the frame on the click of the submit.
Can someone help me ?
Thanks a lot !
Here is my complete code :
public class LemurienAgileForm extends MainApplication {
public LemurienAgileForm(){
leLemurienAgileWindow();
}
public static void leLemurienAgileWindow() {
JFrame f = new JFrame("Le lémurien agile");
//set size of frame
f.setSize(1200, 1000);
f.setBackground(Color.black);
//make sure it quits when x is clicked
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel labelNameFP = new JLabel("Nom (f.pl) : ");
labelNameFP.setBounds(50, 50, 200, 30);
JTextField nameFP = new JTextField();
//set size of the text box
nameFP.setBounds(165, 50, 200, 30);
JLabel labelAdjectiveFP = new JLabel("Adj. (f.pl) : ");
labelAdjectiveFP.setBounds(50, 100, 200, 30);
JTextField adjectiveFP = new JTextField();
adjectiveFP.setBounds(165, 100, 200, 30);
JLabel labelNumber = new JLabel("Nombre : ");
labelNumber.setBounds(50, 150, 200, 30);
JTextField number = new JTextField();
number.setBounds(165, 150, 200, 30);
JButton submitButton = new JButton("Submit");
submitButton.setBounds(130, 720, 70, 50);
submitButton.setBackground(Color.black);
submitButton.setForeground(Color.white);
submitButton.setSize(150, 50);
submitButton.setFont(new Font("Times New Roman", Font.PLAIN, 25));
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JTextArea textArea = new JTextArea();
textArea.setText("Text " + labelAdjectiveMS.getText() + " Text");
JPanel panel = new JPanel();
panel.setBounds(300, 50, 400, 200);
panel.setBackground(Color.black);
panel.add(textArea);
}
});
//add elements to the frame
f.add(labelNameFP);
f.add(nameFP);
f.add(labelAdjectiveFP);
f.add(adjectiveFP);
f.add(labelNumber);
f.add(number);
f.add(submitButton);
f.setLayout(null);
f.setVisible(true);
}
}

JavaFX Animation: Move Shape (Star) randomly

My problem is, that after every keyframe the x- and y-Position of the rectangle should change by random.
Right now only when I start the program, the rectangles position is set by random, but not in the animation itself.
How can I do this, thanks a lot...
public class TimeLines extends Application {
private Rectangle rectBasicTimeline;
private Timeline timeline;
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Do Animation");
int x = new Random().nextInt(500);
int y = new Random().nextInt(400);
rectBasicTimeline = new Rectangle(x, y, 100, 50);
rectBasicTimeline.setFill(Color.RED);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
final Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
final KeyValue kx = new KeyValue(rectBasicTimeline.xProperty(), x + 200);
final KeyValue ky = new KeyValue(rectBasicTimeline.yProperty(), y + 200);
final KeyValue kScale = new KeyValue(rectBasicTimeline.scaleXProperty(), 2);
final KeyValue kFade = new KeyValue(rectBasicTimeline.opacityProperty(), 0);
final KeyFrame kf = new KeyFrame(Duration.millis(3000), kx, ky, kScale, kFade);
timeline.getKeyFrames().add(kf);
timeline.play();
}
});
AnchorPane root = new AnchorPane();
root.getChildren().addAll(btn, rectBasicTimeline);
Scene scene = new Scene(root, 800, 600);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
I agree with #Roland, no need to create multiple Timeline. Reclicking the button just restarts the timeline with new KeyFrame:
public class StarFall extends Application
{
private Polygon star;
private Timeline timeline;
private final double shs = 5.0; // Star Hand Size
private final Random random = new Random();
#Override
public void start( Stage primaryStage )
{
// init shape
Pos initPos = getRandomPos();
star = new Polygon();
star.setLayoutX( initPos.x );
star.setLayoutY( initPos.y );
star.setFill( Color.YELLOW );
// the shape
star.getPoints().addAll( new Double[]
{
0.0, shs * 3,
shs * 2, shs * 2,
shs * 3, 0.0,
shs * 4, shs * 2,
shs * 6, shs * 3,
shs * 4, shs * 4,
shs * 3, shs * 6,
shs * 2, shs * 4
} );
// init timeline
timeline = new Timeline();
timeline.setCycleCount( Timeline.INDEFINITE );
timeline.setAutoReverse( true );
// init button
Button btnStart = new Button( "Do Animation" );
btnStart.setOnAction( ( e ) -> playNextKeyFrame() );
Button btnStop = new Button( "Stop Animation" );
btnStop.setLayoutX( 200 );
btnStart.setLayoutX( 0 );
btnStop.setOnAction( ( e ) -> timeline.stop() );
// init scene with root
AnchorPane root = new AnchorPane( btnStart, btnStop, star );
Scene scene = new Scene( root, 800, 600 );
// show
primaryStage.setScene( scene );
primaryStage.show();
}
private void playNextKeyFrame()
{
// generate next random start and end positions for star
Pos startPos = getRandomPos();
Pos endPos = getRandomPos();
// initial values (resetting)
star.setLayoutX( startPos.x );
star.setLayoutY( startPos.y );
star.setScaleX( 1 );
star.setScaleY( 1 );
star.setOpacity( 1 );
// target values
KeyValue kx = new KeyValue( star.layoutXProperty(), endPos.x );
KeyValue ky = new KeyValue( star.layoutYProperty(), endPos.y );
KeyValue kScaleX = new KeyValue( star.scaleXProperty(), 3 );
KeyValue kScaleY = new KeyValue( star.scaleYProperty(), 3 );
KeyValue kFade = new KeyValue( star.opacityProperty(), 0.0 );
// delay animation before start. Use this instead of THread.sleep() !!
timeline.setDelay( Duration.millis( random.nextInt( 2000 ) + 100 ) );
// restart timeline with new values
timeline.stop();
timeline.getKeyFrames().clear();
timeline.getKeyFrames().add( new KeyFrame( Duration.millis( 3000 ),
( e ) -> playNextKeyFrame(), kx, ky, kFade, kScaleX, kScaleY ) );
timeline.play();
}
private Pos getRandomPos()
{
int x = random.nextInt( 500 );
int y = random.nextInt( 400 );
Pos p = new Pos();
p.x = x + 200;
p.y = y + 200;
return p;
}
private class Pos
{
int x;
int y;
}
public static void main( String[] args )
{
launch( args );
}
}
You initialize the random numbers and hence the location once and use it all the time. What you need to do is to perform the animation cycle once and then create a new animation when the current one finishes.
Example:
import java.util.Random;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class TimeLines extends Application {
private Rectangle rectBasicTimeline;
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Do Animation");
int x = new Random().nextInt(500);
int y = new Random().nextInt(400);
rectBasicTimeline = new Rectangle(x, y, 100, 50);
rectBasicTimeline.setFill(Color.RED);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
play();
}
});
AnchorPane root = new AnchorPane();
root.getChildren().addAll(btn, rectBasicTimeline);
Scene scene = new Scene(root, 800, 600);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
private void play() {
double x = new Random().nextInt(500);
double y = new Random().nextInt(400);
final Timeline timeline = new Timeline();
// cycle count = 2 because of autoreverse
timeline.setCycleCount(2);
timeline.setAutoReverse(true);
final KeyValue kx = new KeyValue(rectBasicTimeline.xProperty(), x + 200);
final KeyValue ky = new KeyValue(rectBasicTimeline.yProperty(), y + 200);
final KeyValue kScale = new KeyValue(rectBasicTimeline.scaleXProperty(), 2);
final KeyValue kFade = new KeyValue(rectBasicTimeline.opacityProperty(), 0);
final KeyFrame kf = new KeyFrame(Duration.millis(1000), kx, ky, kScale, kFade);
timeline.getKeyFrames().add(kf);
timeline.setOnFinished(e -> {
// create new animation after this animation finishes
play();
});
timeline.play();
}
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
I wouldn't suggest this approach though, e. g. you run into problems with multiple timelines when you click the button multiple times. But I have no information what you're trying to do, so I'll leave it at that.

How to create a custom dialog in installanywhere?

I want to know , how to create a custom dialog using installanywhere 2012. We are migrating our installer from installshiled to installanywhere. We have used alot of custom dialogs in installshiled. Now I need to change the same in IA 2013. I'm new to IA.
Please help me.
Thanks,
Thananjeyan
All the screens i n InstallAnywhere could be designed using Swings and AWT. You need to import and extend CustomCodePanel
Sample code is as below:
import com.zerog.ia.api.pub.CustomCodePanel;
import com.zerog.ia.api.pub.CustomCodePanelProxy;
import java.awt.*;
import java.util.Map;
import java.util.HashMap;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
public class JDBCParamsPanel extends CustomCodePanel{
private boolean inited = false;
private Font plainFont;
private Font boldFont;
private Map<String, TextField> varName2TextField = new HashMap<String, TextField>();
String databaseType = "";
#Override
public boolean setupUI(CustomCodePanelProxy customCodePanelProxy) {
if(!inited){
final String fontName = "Dialog";
LineBorder border = new LineBorder(Color.GRAY, 1, true);
final int fontSize = System.getProperty("os.name").contains("Windows") ? 12 : 8;
plainFont = new Font(fontName, Font.PLAIN, fontSize);
boldFont = new Font(fontName, Font.BOLD, fontSize);
setLayout(new BorderLayout(20, 1));
JTextArea topPrompt = new JTextArea(
"Please enter the following parameters that ABC will use\n"
+ "to connect to the database");
topPrompt.setRows(7);
topPrompt.setBorder(border);
databaseType = (String) customCodePanelProxy.getVariable("$DATABASE_TYPE$");
System.out.println("databaseType::: "+databaseType);
topPrompt.setEditable(false);
topPrompt.setFont(plainFont);
Panel topPanel = new Panel() {
public Insets getInsets() {
// return new Insets(10, 10, 10, 10);
return new Insets(7, 1, 4, 10);
}
};
topPanel.setSize(1, 50);
topPanel.setLayout(new BorderLayout());
topPanel.add(topPrompt, BorderLayout.CENTER);
add(topPanel, BorderLayout.NORTH);
Panel dataEntryPanel = new Panel();
add(dataEntryPanel, BorderLayout.CENTER);
dataEntryPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(5, 2, 8, 10);
gbc.fill = GridBagConstraints.BOTH;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.Host"), "$DB_HOST$", false, 100), gbc);
gbc.gridy = 1;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.Port"), "$DB_PORT$", false, 102), gbc);
gbc.gridy = 2;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.Database_Name"), "$DB_NAME$", false, 36), gbc);
gbc.gridy = 3;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.User"), "$DB_USER$", false, 99), gbc);
gbc.gridy = 4;
dataEntryPanel.add(makeEntryPanel(customCodePanelProxy
.getValue("PromptUserConsole.Password"), "$DB_PASSWORD$", true, 68), gbc);
inited=true;
}
return true;
}
private Panel makeEntryPanel(String labelText, String varName, boolean useEchoChar, int hgap) {
Panel panel = new Panel(new BorderLayout(hgap, 1));
panel.add(makeStarLabel(labelText), BorderLayout.WEST);
TextField tf = new TextField();
tf.setFont(plainFont);
tf.setCaretPosition(Integer.MAX_VALUE);
if (useEchoChar) {
tf.setEchoChar('*');
}
panel.add(tf, BorderLayout.CENTER);
varName2TextField.put(varName, tf);
return panel;
}
private Label makeLabel(String text) {
Label label = new Label(text, Label.RIGHT);
label.setFont(boldFont);
return label;
}
private JLabel makeStarLabel(String text) {
JLabel label = new JLabel(text, Label.RIGHT);
label.setText("<html>" + text + "<font color=FF0000>*</font> </html>");
label.setFont(boldFont);
return label;
}
public String getTitle() {
return "JDBC Parameters";
}
#Override
public void panelIsDisplayed() {
populate("$DB_HOST$");
populate("$DB_PORT$");
populate("$DB_NAME$");
populate("$DB_USER$");
populate("$DB_PASSWORD$");
}
private void populate(String varName) {
TextField tf = varName2TextField.get(varName);
String value = (String) customCodePanelProxy.getVariable(varName);
tf.setText(value);
}
#Override
public boolean okToContinue() {
for (Map.Entry<String, TextField> entry : varName2TextField.entrySet()) {
String varName = entry.getKey();
TextField tf = entry.getValue();
String value = tf.getText().trim();
customCodePanelProxy.setVariable(varName, value);
}
return true;
}
}
The above code constructs a panel with 5 text input fields.
You can refer the above and write custom panels as per your requirement

Can't draw .jpeg on a JPanel

I'm working on a Game where I need to draw a board and pawns actively when I move them. I've searched for a few hours now, but I can't find a solution.
They're located in the same folder as the classes.
Thanks in advance for any help :)
code:
import java.awt.*;
import javax.swing.*;
public class MyPanel extends JPanel{
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
try {
Image board = new ImageIcon("images/ChackerBoard.jpeg").getImage();
Image black = new ImageIcon("images\\BlackPawn.jpeg").getImage();
Image white = new ImageIcon("images\\WhitePawn.jpeg").getImage();
this.setSize(320, 320);
g.drawImage(board, 0, 0, this);
for (int i = 0; i < Game.BlackList.size(); i++) {
g.drawImage(black, (Game.BlackList.get(i).GetX() * 40) - 36, (Game.BlackList.get(i).GetY() * 40) - 36, this);
}
for (int i = 0; i < Game.WhiteList.size(); i++) {
g.drawImage(white, (Game.WhiteList.get(i).GetX() * 40) - 36, (Game.WhiteList.get(i).GetY() * 40) - 36, this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
images:
http://i.stack.imgur.com/bhuc2.jpg
http://imageshack.us/a/img7/8673/checkerboardo.jpg
#FailX in paintComponent, imageobserver object is null. Set the image observer as "this" and it works.
#Override
protected void paintComponent( Graphics g ){
super.paintComponent( g );
g.drawImage(img, 0, 0, this); //Image is also drawn
g.drawLine( 10, 10, 100, 50 ); //Line is drawn
g.draw3DRect(20,20,50,30,true); // Rectangle is drawn
}

BlackBerry - Custom menu toolbar

I'm a beginner in BlackBerry programming, I need to replace in my application the default menu (when you press the menu button) by a custom menu, horizontal. The best to describe is I want the same result as the WeatherEye application for BlackBerry...
alt text http://www.blackberrybing.com/resource/pics/201002/WeatherEye-OS-45.jpg
I know how to create the default menu, but this one I have no idea!
Thank you,
What you will need to do is:
create SizebleVFManager (contentManager) as an extension of VerticalFieldManager
set display width and height = (display height - menu height) size to contentManager
add contentManager to screen
create HorizontalFieldManager (menuManager)
create BitmapButtonField (menuButton) as an extension of ButtonField
set FieldChangeListeners to menuButtons
add menuButtons to menuManager
add menuManager to screen
Sample of SizebleVFManager :
class SizebleVFManager extends VerticalFieldManager
{
int mWidth = 0;
int mHeight = 0;
public SizebleVFM(int width, int height, long style) {
super(style);
mWidth = width;
mHeight = height;
}
public SizebleVFM(int width, int height) {
mWidth = width;
mHeight = height;
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
protected void sublayout(int width, int height) {
width = getPreferredWidth();
height = getPreferredHeight();
super.sublayout(width, height);
setExtent(width, height);
}
}
...
SizebleVFManager contentManager =
new SizebleVFManager(Display.getWidth(), Display.getHeight(),
VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
See also
sample of BitmapButtonField and Toolbar
PS though its better to use standard menu...
UPDATE
If you want to disable default menu functionality, cancel MENU keydown:
protected boolean keyDown(int keycode, int time) {
if(Keypad.KEY_MENU == Keypad.key(keycode))
{
return true;
}
else
return super.keyDown(keycode, time);
}
UPDATE
I've installed that wonderful weather application and understood this sample may be more alike with several improvements:
use CyclicHFManager as an extension of HorizontalFieldManager
show/hide menuManager on Menu button click
CyclicHFManager is a manager which will keep focus on the same place visually and run all fields over, in cycle. Like in BlackBerry - Custom centered cyclic HorizontalFieldManager
class CyclicHFManager extends HorizontalFieldManager {
int mFocusedFieldIndex = 0;
boolean mCyclicTurnedOn = false;
public void focusChangeNotify(int arg0) {
super.focusChangeNotify(arg0);
if (mCyclicTurnedOn) {
int focusedFieldIndexNew = getFieldWithFocusIndex();
if (focusedFieldIndexNew != mFocusedFieldIndex) {
if (focusedFieldIndexNew - mFocusedFieldIndex > 0)
switchField(0, getFieldCount() - 1);
else
switchField(getFieldCount() - 1, 0);
}
}
else
{
mFocusedFieldIndex = getFieldWithFocusIndex();
}
}
private void switchField(int prevIndex, int newIndex) {
Field field = getField(prevIndex);
delete(field);
insert(field, newIndex);
}
}
alt text http://img109.imageshack.us/img109/6176/toolbarj.jpg
And whole code sample:
abstract class AScreen extends MainScreen {
boolean mMenuEnabled = false;
SizebleVFManager mContentManager = null;
CyclicHFManager mMenuManager = null;
public AScreen() {
mContentManager = new SizebleVFManager(Display.getWidth(), Display
.getHeight(), VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
add(mContentManager);
// mMenuManager = new CyclicHFManager(Display.getWidth(), 60);
mMenuManager = new CyclicHFManager();
mMenuManager.setBorder(BorderFactory.createBevelBorder(new XYEdges(4,
0, 0, 0), new XYEdges(Color.DARKBLUE, 0, 0, 0), new XYEdges(
Color.WHITE, 0, 0, 0)));
mMenuManager.setBackground(BackgroundFactory
.createLinearGradientBackground(Color.DARKBLUE, Color.DARKBLUE,
Color.LIGHTBLUE, Color.LIGHTBLUE));
for (int i = 0; i < 10; i++) {
Bitmap nBitmap = new Bitmap(60, 60);
Graphics g = new Graphics(nBitmap);
g.setColor(Color.DARKBLUE);
g.fillRect(0, 0, 60, 60);
g.setColor(Color.WHITE);
g.drawRect(0, 0, 60, 60);
Font f = g.getFont().derive(Font.BOLD, 40);
g.setFont(f);
String text = String.valueOf(i);
g.drawText(text, (60 - f.getAdvance(text)) >> 1, (60 - f
.getHeight()) >> 1);
Bitmap fBitmap = new Bitmap(60, 60);
g = new Graphics(fBitmap);
g.setColor(Color.DARKBLUE);
g.fillRect(0, 0, 60, 60);
g.setColor(Color.GOLD);
g.drawRect(0, 0, 60, 60);
g.setFont(f);
g.drawText(text, (60 - f.getAdvance(text)) >> 1, (60 - f
.getHeight()) >> 1);
BitmapButtonField button = new BitmapButtonField(nBitmap, fBitmap,
fBitmap);
button.setCookie(String.valueOf(i));
button.setPadding(new XYEdges(0, 18, 0, 18));
button.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
Dialog.inform("Button # " + (String) field.getCookie());
}
});
mMenuManager.add(button);
}
}
protected boolean keyDown(int keycode, int time) {
if (Keypad.KEY_MENU == Keypad.key(keycode)) {
if (mMenuManager.getManager() != null) {
delete(mMenuManager);
mMenuManager.mCyclicTurnedOn = false;
mContentManager.updateSize(Display.getWidth(), Display
.getHeight());
} else {
add(mMenuManager);
mMenuManager.getField(2).setFocus();
mMenuManager.mCyclicTurnedOn = true;
mContentManager.updateSize(Display.getWidth(), Display
.getHeight()
- mMenuManager.getHeight());
}
return true;
} else
return super.keyDown(keycode, time);
}
}
class FirstScreen extends AScreen {
public FirstScreen() {
mContentManager.add(new LabelField("This is a first screen"));
}
}
public class ToolbarMenuApp extends UiApplication {
public ToolbarMenuApp() {
pushScreen(new FirstScreen());
}
public static void main(String[] args) {
(new ToolbarMenuApp()).enterEventDispatcher();
}
}

Resources