Codenameone list adding functionality - codenameone

I'm currently busy with a Codenameone app that requires me to add a list of items by button click like how you would add a task in a task list. How would I approach this? I'm a bit new at this. Please help.

This is a short example:
Form form = new Form("List Example"); //Create Form
Button button = new Button("PRESS ME"); //Create Button
form.add(button); // add button to Form
List myList = new List<>(); //Create List
form.add(myList); //add List to Form
// Create an Array of Elements
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < 20; i++)
{
arrayList.add("Elemnt " + i);
}
// Create ListModel
DefaultListModel<String> listModel = new DefaultListModel<>(arrayList);
// Add Button ActionListner
button.addActionListener(new ActionListener<ActionEvent>()
{
public void actionPerformed(ActionEvent arg0)
{
myList.setModel(listModel); //add ListModel to List
form.repaint();
}
});
form.show();

Related

Unknown size of TextFields Array JavaFX

I am trying to build a GUI stack using JavaFX. I am supposed to ask the user how many elements he wants for the stack. Then the number of text fields should appear on the right screen (based on the size of user's entry). I have been trying all day in vain.
Here is what I have been trying to do so far. Once I solve TextFields array issue, I should complete my program.
public class StackGUI extends Application {
private Button push, pop, peek, empty, create, build;
private TextField[] data;
private TextField size, numberText;
private Label sizeLabel, numberLabel;
private int sizeOfStack;
String sizeDialog = "0";
#Override
public void start(Stage primaryStage) {
BorderPane border = new BorderPane();
// Buttons
push = new Button("PUSH");
push.setPrefSize(150, 50);
pop = new Button("POP");
pop.setPrefSize(150, 50);
peek = new Button("PEEK");
peek.setPrefSize(150, 50);
empty = new Button("EMPTY");
empty.setPrefSize(150, 50);
FlowPane bottom = new FlowPane();
bottom.setHgap(10);
bottom.setAlignment(Pos.CENTER);
bottom.getChildren().addAll(push, pop, peek, empty);
border.setBottom(bottom);
//Center
VBox center = new VBox(5);
center.setAlignment(Pos.CENTER);
size = new TextField();
size.setMaxWidth(200);
size.setEditable(false);
numberLabel = new Label("Enter a number: ");
numberText = new TextField();
numberText.setMaxWidth(200);
//sizeLabel = new Label("How many numbers? ");
create = new Button("Create a stack");
create.setPrefWidth(200);
build = new Button("Build the stack");
build.setPrefWidth(200);
build.setDisable(true);
center.getChildren().addAll(create, size, build);
border.setCenter(center);
//Stack TextFields --> right
create.setOnAction(ae -> {
TextInputDialog input = new TextInputDialog();
input.setContentText("How many Numbers");
input.setHeaderText("Size Of Stack");
input.setTitle("Stack");
input.showAndWait();
size.setAlignment(Pos.CENTER);
size.setText("Number Of Elements: " + input.getEditor().getText());
sizeDialog = input.getEditor().getText();
build.setDisable(false);
});
sizeOfStack = Integer.parseInt(sizeDialog);
data = new TextField[sizeOfStack];
HBox right = new HBox(5);
build.setOnAction(ae -> {
create.setDisable(true);
numberText.setPromptText("Enter a number to push");
center.getChildren().addAll(numberLabel, numberText);
for (int i = 0; i < sizeOfStack; i++) {
data[i] = new TextField();
right.getChildren().add(data[i]);
}
});
border.setRight(right);
//Scene
Scene scene = new Scene(border, 800, 400);
primaryStage.setScene(scene);
primaryStage.setTitle("Stack");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
As #James_D pointed out, you need to move sizeOfStack = Integer.parseInt(sizeDialog); inside of build.setOnAction. You also need to move data = new TextField[sizeOfStack] ;.
I also moved HBox right = new HBox(sizeOfStack); and border.setRight(right);, but that may not have been necesary.
Code:
build.setOnAction((ActionEvent event) - > {
sizeOfStack = Integer.parseInt(sizeDialog);
data = new TextField[sizeOfStack];
create.setDisable(true);
numberText.setPromptText("Enter a number to push");
center.getChildren().addAll(numberLabel, numberText);
HBox right = new HBox(sizeOfStack);
for (int i = 0; i < sizeOfStack; i++) {
TextField text = new TextField();
data[i] = text;
right.getChildren().add(data[i]);
}
border.setRight(right);
});

How to get current radio button index value from a radio button group in codename one?

I have some radio button which I put in radio button group.
So, how can I get the radio button index value or selected index value when I going to click on a particular radio button.
Here is my code
bg=new ButtonGroup();
for(i=0;i<8;i++){
rbt =new RadioButton();
rbt.setName("rbt"+i);
radioList.add(rbt);
}
for(int i=0;i<radioList.size();i++){
radioList.get(i).addPointerPressedListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
for(int i=0;i<radioList.size();i++){
Log.p("================"+bg.getSelectedIndex);
}
}
});
}
In the above code I am getting the previously selected value not the current. value
Thanks in Advance
pointerPressed is called before the radio button has processed the event. Use addActionListener instead, which is fired after the state is changed, so the selected index should be the currently-selected radio button.
You should add the radiobutton in container as well as buttongroup and call getselectedIndex of buttongroup to get current index as shown in below code
void testRadio(Form form) {
Container radioList = new Container(new BoxLayout(BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
for (int i = 0; i < 8; i++) {
RadioButton rbt = new RadioButton();
rbt.setName("rbt" + i);
rbt.setText("rbt" + i);
**radioList.add(rbt);
bg.add(rbt);**
}
bg.setSelected(0);
form.add(radioList);
Button getIndexButton = new Button("Get Radio Index");
getIndexButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
Log.p("================" + bg.getSelectedIndex());
}
});
form.add(getIndexButton);
}

Codename one Android Sidemenu

I'm trying to implement an Android style side menu and I'm having an issue implementing the rounded icon on top and labels below it before the sideCommands are added.
How do I implement this please?
You can use Toolbar API which allows you to add components to the Sidemenu.
Have a look at Flickr demo.
Instead of using tool.addCommandToSideMenu(Command) you should use tool.addComponentToSideMenu(yourComponent, CommandToPerform)
Example:
#Override
protected void beforeMain(Form f) {
//Store your commands before setting toolbar
List<Command> cmds = new ArrayList();
for (int i = 0; i < f.getCommandCount(); i++) {
cmds.add(f.getCommand(i));
}
Toolbar toolbar = new Toolbar();
f.setToolBar(toolbar);
Label lblTitle = new Label("My Form", "Title");
lblTitle.setEndsWith3Points(false);
toolbar.setTitleComponent(lblTitle);
// Use your stored commands after setting toolbar
for (Command cmd : cmds) {
toolbar.addCommandToSideMenu(cmd);
}
Container CustomContainer = ...
toolbar.addComponentToSideMenu(CustomContainer, new Command("") {
#Override
public void actionPerformed(ActionEvent evt) {
//What CustomContainer should do (if any)
}
});
f.revalidate();
}

Dispatcher Invoke multi control in one delegate?

I am working on a WPF application,
I have to fetch the picasa album from google API and bind to WPF listview.
I have to bind to 2 listview and using Dispatcher.Invoke().
Below is the code snippet:
private void BindPicasa()
{
//My custom Google helper class.
GoogleClass google = new GoogleClass();
ThreadStart start = delegate()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(delegate()
{
//Fetch the album list
List<AlbumClass.Album> album = google.RequestAlbum(GoogleID);
//bind to a 1st listview in text title.
ListLeftAlbum.DataContext = album;
//bind to a 2nd listview in thumbnail preview.
ListMainAlbum.Visibility = System.Windows.Visibility.Visible;
ListMainAlbum.DataContext = album;
}));
};
new Thread(start).Start();
}
The UI will freeze when start,
However if i take out each listview and run with its own Dispatcher, it is fine, the UI responsible, but it seems not elegant way to do so.
Any recommend? Thanks you!
private void BindPicasa()
{
//My custom Google helper class.
GoogleClass google = new GoogleClass();
ThreadStart start = delegate()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(delegate()
{
//Fetch the album list
List<AlbumClass.Album> album = google.RequestAlbum(GoogleID);
}));
ListLeftAlbum.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(delegate()
{
//bind to a 1st listview in text title.
ListLeftAlbum.DataContext = album;
}));
ListMainAlbum.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(delegate()
{
//bind to a 2nd listview in thumbnail preview.
ListMainAlbum.Visibility = System.Windows.Visibility.Visible;
ListMainAlbum.DataContext = album;
}));
};
new Thread(start).Start();
}
your first version was almost right, you just need to fetch the album on the background thread instead of dispatching the request back to the ui thread
private void BindPicasa()
{
//My custom Google helper class.
GoogleClass google = new GoogleClass();
ThreadStart start = delegate()
{
//Fetch the album list
List<AlbumClass.Album> album = google.RequestAlbum(GoogleID);
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(delegate()
{
//bind to a 1st listview in text title.
ListLeftAlbum.DataContext = album;
//bind to a 2nd listview in thumbnail preview.
ListMainAlbum.Visibility = System.Windows.Visibility.Visible;
ListMainAlbum.DataContext = album;
}));
};
new Thread(start).Start();
}

How do I create a Treeview with a Context Menu in Silverlight 4?

Silverlight 4 now include the option for creating a context menu upon right clicking. Can anyone provide me with an example of a treeview with a right click context menu for the treeview?
Ultimately I want a the menu to show different options depending upon the node depth selected - bonus points if the example includes this!
You can use this open source menu for this:
http://sl4popupmenu.codeplex.com
The control supports right click on TreeViews out of the box. The code has been adapted from the sample code on the homepage to use a TreeView instead of a DataGrid:
private void GenerateMenu()
{
var data = new ObservableCollection<string>("Item 1,Item 2,Item 3,Item 4,Item 6,Item 7,Item 8".Split(','));
TreeView treeView1 = new TreeView() { Margin = new Thickness(50), ItemsSource = data };
this.LayoutRoot.Children.Add(dataGrid1);
// Create the submenu
var pmTimeSub = new PopupMenu();
pmTimeSub.AddItem("Time Now", null);
// Create the main menu
var pm = new PopupMenu();
pm.AddItem("Delete row", delegate { data.RemoveAt(dataGrid1.SelectedIndex); });
pm.AddSeparator();
pm.AddSubMenu(pmTimeSub, "Get Time ", "images/arrow.png", null, null, false, null);
// Attach the submenu pmTimeSub
pm.AddSeparator();
pm.AddItem("Demo2", delegate { this.Content = new Demo2(); });
// Set dataGrid1 as the trigger element
pm.AddTrigger(TriggerTypes.RightClick, treeView1);
// Showing main menu
pm.Showing += (sender, e) =>
{
pm.PopupMenuItem(0).Header = "Delete " + treeView1.SelectedItem;
TreeViewItem tvi = pm.GetClickedElement<TreeViewItem>();
// Add code to calculate the node depth here using the GetParentTreeViewItem method
// Add code to modify the menu items according to the node depth value.
pm.PopupMenuItem(0).IsVisible =
pm.PopupMenuItem(1).IsVisible = tvi != null;
};
// Showing submenu
pmTimeSub.Showing += delegate
{
pmTimeSub.PopupMenuItem(0).Header = DateTime.Now.ToLongTimeString();
};
}
Note that the code does not allow you to show different menus upon the node depth yet. To do this you can use the following method to get the parent of the TreeViewItem that was clicked:
private static TreeViewItem GetParentTreeViewItem(DependencyObject item)
{
if (item != null)
{
DependencyObject parent = VisualTreeHelper.GetParent(item);
TreeViewItem parentTreeViewItem = parent as TreeViewItem;
return parentTreeViewItem ?? GetParentTreeViewItem(parent);
}
return null;
}
From there you can determine depth of the node by calling the GetParentTreeViewItem function in a loop until the parent is null. You would place this code in the event where the menu is being shown and then add the necessary code in there to show the appropriate menu.
Hope this helps.
So, I tried the above code, downloaded and attempted to include within my Existing Silverlight Application. I was able to find an easier solution. This will add a Context Menu allowing Right-Clicks on the Branches (Headers, or Parent Nodes).
private ContextMenu menu;
foreach(var model in models)
{
// Populate the Tree View Control
var cb = new CheckBox {Content = model.Value};
cb.Click += new RoutedEventHandler(cb_Click);
var header = new TreeViewItem {Header = cb};
// Menu for Header
menu = new ContextMenu();
MenuItem setAsRows = new MenuItem();
setAsRows.Header = "Set as Rows";
setAsRows.Click += new RoutedEventHandler(setAsRows_Click);
menu.Items.Add(setAsRows);
MenuItem addToRows = new MenuItem();
addToRows.Header = "Add to Rows";
addToRows.Click += new RoutedEventHandler(addToRows_Click);
menu.Items.Add(addToRows);
MenuItem setAsCols = new MenuItem();
setAsCols.Header = "Set as Columns";
menu.Items.Add(setAsCols);
MenuItem addToCols = new MenuItem();
addToCols.Header = "Add to Columns";
menu.Items.Add(addToCols);
header.ContextMenu = menu;
treeView1.Items.Add(header);
var thisItem = treeView1.Items;
// Model Contexts
var contexts = myFramework.GetConceptsOfModel(model.Key);
// Add Leafs To Branch
foreach(var context in contexts)
{
cb = new CheckBox {Content = context.Value.ToString()};
header.Items.Add(cb);
}
}

Resources