Xamarin.iOS- How to implement Stepped Progress bar - xamarin.ios

I have attached screen short I want to implement this stepped progress bar in Xamarin.iOS.
Please help any source code regarding to this process in Xamarin.iOS.Thanks

You could create a custom step progress bar.
public class StepProgressBarControl : StackLayout
{
Button _lastStepSelected;
public static readonly BindableProperty StepsProperty =BindableProperty.Create(nameof(Steps), typeof(int), typeof(StepProgressBarControl), 0);
public static readonly BindableProperty StepSelectedProperty =BindableProperty.Create(nameof(StepSelected), typeof(int), typeof(StepProgressBarControl), 0, defaultBindingMode: BindingMode.TwoWay);
public static readonly BindableProperty StepColorProperty = BindableProperty.Create(nameof(StepColor), typeof(Xamarin.Forms.Color), typeof(StepProgressBarControl), Color.Black, defaultBindingMode: BindingMode.TwoWay);
public Color StepColor
{
get { return (Color)GetValue(StepColorProperty); }
set { SetValue(StepColorProperty, value); }
}
public int Steps
{
get { return (int)GetValue(StepsProperty); }
set { SetValue(StepsProperty, value); }
}
public int StepSelected
{
get { return (int)GetValue(StepSelectedProperty); }
set { SetValue(StepSelectedProperty, value); }
}
public StepProgressBarControl()
{
Orientation = StackOrientation.Horizontal;
HorizontalOptions = LayoutOptions.FillAndExpand;
Padding = new Thickness(10, 0);
Spacing = 0;
AddStyles();
}
protected override void OnPropertyChanged(string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == StepsProperty.PropertyName)
{
for (int i = 0; i < Steps; i++)
{
var button = new Button()
{
Text = $"{i + 1}", ClassId= $"{i + 1}",
Style = Resources["unSelectedStyle"] as Style
};
button.Clicked += Handle_Clicked;
this.Children.Add(button);
if (i < Steps - 1)
{
var separatorLine = new BoxView()
{
BackgroundColor = Color.Silver,
HeightRequest = 1,
WidthRequest=5,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.FillAndExpand
};
this.Children.Add(separatorLine);
}
}
}else if(propertyName == StepSelectedProperty.PropertyName){
var children= this.Children.First(p => (!string.IsNullOrEmpty(p.ClassId) && Convert.ToInt32(p.ClassId) == StepSelected));
if(children != null) SelectElement(children as Button);
}else if(propertyName == StepColorProperty.PropertyName){
AddStyles();
}
}
void Handle_Clicked(object sender, System.EventArgs e)
{
SelectElement(sender as Button);
}
void SelectElement(Button elementSelected){
if (_lastStepSelected != null) _lastStepSelected.Style = Resources["unSelectedStyle"] as Style;
elementSelected.Style = Resources["selectedStyle"] as Style;
StepSelected = Convert.ToInt32(elementSelected.Text);
_lastStepSelected = elementSelected;
}
void AddStyles(){
var unselectedStyle = new Style(typeof(Button))
{
Setters = {
new Setter { Property = BackgroundColorProperty, Value = Color.Transparent },
new Setter { Property = Button.BorderColorProperty, Value = StepColor },
new Setter { Property = Button.TextColorProperty, Value = StepColor },
new Setter { Property = Button.BorderWidthProperty, Value = 0.5 },
new Setter { Property = Button.BorderRadiusProperty, Value = 20 },
new Setter { Property = HeightRequestProperty, Value = 40 },
new Setter { Property = WidthRequestProperty, Value = 40 }
}
};
var selectedStyle = new Style(typeof(Button))
{
Setters = {
new Setter { Property = BackgroundColorProperty, Value = StepColor },
new Setter { Property = Button.TextColorProperty, Value = Color.White },
new Setter { Property = Button.BorderColorProperty, Value = StepColor },
new Setter { Property = Button.BorderWidthProperty, Value = 0.5 },
new Setter { Property = Button.BorderRadiusProperty, Value = 20 },
new Setter { Property = HeightRequestProperty, Value = 40 },
new Setter { Property = WidthRequestProperty, Value = 40 },
new Setter { Property = Button.FontAttributesProperty, Value = FontAttributes.Bold }
}
};
Resources = new ResourceDictionary();
Resources.Add("unSelectedStyle", unselectedStyle);
Resources.Add("selectedStyle", selectedStyle);
}
}
Or you could use Xamarin.Forms.StepProgressBar. Install it from NuGet.

Related

MvvmCross bind to progress indicator in MvxDialogViewController

I have a MvxDialogViewController and I'm trying to use the progress indicator shown in the Xamarin example by adding bindable properties.
I can get the indicator to appear when I set Visble to true programatically but not when I bind to a vm property.
Here is the view code:
var bindings = this.CreateInlineBindingTarget<LoginViewModel>();
Root = new RootElement("Login")
{
new Section("Login Credentials")
{
new EntryElement("Username", "Enter user name").Bind(bindings, vm => vm.UserName),
new EntryElement("Password", "Enter password", "", true).Bind(bindings, vm => vm.Password)
}
};
_bindableProgress = new BindableProgress(UIScreen.MainScreen.Bounds).Bind(bindings, b => b.Visible, vm => vm.IsBusy);
_bindableProgress.Title = "Logging in...";
View.Add(_bindableProgress);
I also tried to bind like this:
var set = this.CreateBindingSet<LoginView, LoginViewModel>();
set.Bind(_bindableProgress).For(b => b.Title).To(vm => vm.ProgressTitle);
set.Bind(_bindableProgress).For(b => b.Visible).To(vm => vm.IsBusy);
set.Apply();
But neither way worked.
Here is by BindableProgress class:
public class BindableProgress : UIView
{
private UIActivityIndicatorView _activitySpinner;
private UILabel _loadingLabel;
public string Title { get; set; }
private bool _visible;
public bool Visible
{
get { return _visible; }
set
{
_visible = value;
if (_visible)
{
Show();
}
else
{
Hide();
}
}
}
public BindableProgress(RectangleF frame) : base(frame)
{
// configurable bits
BackgroundColor = UIColor.Black;
Alpha = 0;
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
float labelHeight = 22;
float labelWidth = Frame.Width - 20;
// derive the center x and y
float centerX = Frame.Width/2;
float centerY = Frame.Height/2;
// create the activity spinner, center it horizontally and put it 5 points above center x
_activitySpinner = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge);
_activitySpinner.Frame = new RectangleF(
centerX - (_activitySpinner.Frame.Width / 2),
centerY - _activitySpinner.Frame.Height - 20,
_activitySpinner.Frame.Width,
_activitySpinner.Frame.Height);
_activitySpinner.AutoresizingMask = UIViewAutoresizing.FlexibleMargins;
AddSubview(_activitySpinner);
// create and configure the label
_loadingLabel = new UILabel(new RectangleF(
centerX - (labelWidth/2),
centerY + 20,
labelWidth,
labelHeight
));
_loadingLabel.BackgroundColor = UIColor.Clear;
_loadingLabel.TextColor = UIColor.White;
_loadingLabel.TextAlignment = UITextAlignment.Center;
_loadingLabel.AutoresizingMask = UIViewAutoresizing.FlexibleMargins;
AddSubview(_loadingLabel);
}
private void Show()
{
_loadingLabel.Text = Title;
Alpha = 0.75f;
_activitySpinner.StartAnimating();
}
/// <summary>
/// Fades out the control and then removes it from the super view
/// </summary>
private void Hide()
{
_activitySpinner.StopAnimating();
Animate(
0.5, // duration
() => { Alpha = 0; },
() => { RemoveFromSuperview(); }
);
}
}
Any ideas?
UPDATE
My vm property looks like this
private bool _isBusy;
public bool IsBusy
{
get { return _isBusy; }
set { _isBusy = value; RaisePropertyChanged(() => IsBusy); }
}
It works fine in Android so I'm guessing the problem in not with that.
IsBusy is probably false at binding time. So _visible is set to false and Hide() is called. Now the view is removed from the superview and you can't show it anymore, because Show() doesn't add it to the superview again. Try to omit the RemoveFromSuperview();. Or modify the Visible property like this:
public bool Visible
{
get { return _visible; }
set
{
if(_visible == value)
return;
_visible = value;
if (_visible)
{
Show();
}
else
{
Hide();
}
}
}

Some trouble with ComboBox in Ext.net

I have a Page which a FormPanel(there's a ComboBox in it) and a TreePanel(has a default root node) in it and open ViewState.
I set a value to ComboBox in GET.
When i GET the page the TreePanel's Store send a POST request(store read) before FormPane rendered in client,in this POST request the fromdata has no info about FormPane.
in the POST request recover the ComboBox.Value from ViewState,but in ComboBoxBase.LoadPostData() Ext.Net get value from formdata and cover ComboBox.Value without precondition
it's ComboBoxBase.LoadPostData() code
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
if (!this.EmptyText.Equals(text) && text.IsNotEmpty())
{
List<ListItem> items = null;
if (this.SimpleSubmit)
{
var array = state.Split(new char[] { ',' });
items = new List<ListItem>(array.Length);
foreach (var item in array)
{
items.Add(new ListItem(item));
}
}
else if(state.IsNotEmpty())
{
items = ComboBoxBase.ParseSelectedItems(state);
}
bool fireEvent = false;
if (items == null)
{
items = new List<ListItem>
{
new ListItem(text)
};
/*fireEvent = this.SelectedItems.Count > 0;
this.SelectedItems.Clear();
return fireEvent;
*/
}
foreach (var item in items)
{
if (!this.SelectedItems.Contains(item))
{
fireEvent = true;
break;
}
}
this.SelectedItems.Clear();
this.SelectedItems.AddRange(items);
return fireEvent;
}
else
{
if (this.EmptyText.Equals(text) && this.SelectedItems.Count > 0)
{
this.SelectedItems.Clear();
return true;
}
}
return false;
}
Look at Line 5 to 11,why not change like this
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.Value = text;
this.ResumeScripting();
Sample for this question
page file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<ext:ResourceManager ID="ResourceManager1" runat="server" DisableViewState="false"
AjaxViewStateMode="Enabled" ViewStateMode="Enabled"/>
<form id="form1" runat="server">
<ext:Viewport runat="server" ID="VP">
</ext:Viewport>
</form>
</body>
</html>
cs file
public partial class WebFormTest : System.Web.UI.Page
{
protected override void OnInitComplete(EventArgs e)
{
FP = new FormPanel();
FP.ID = "FP";
FP.Title = "FP";
FP.Region = Region.Center;
TF = new TextField();
TF.ID = "TF";
TF.FieldLabel = "TF";
CB = new ComboBox();
CB.ID = "CB";
CB.FieldLabel = "CB";
CB.Items.Clear();
CB.Items.Add(new ListItem("one", "1"));
CB.Items.Add(new ListItem("two", "2"));
Button test = new Button() { ID = "testbtn", Text = "test" };
test.Listeners.Click.Handler = "App.Store2.load()";
FP.TopBar.Add(new Toolbar() { Items = { test } });
FP.Items.Add(TF);
FP.Items.Add(CB);
GP = new GridPanel();
GP.ID = "GP";
GP.Title = "GP";
GP.Region = Region.East;
GP.Listeners.BeforeRender.Handler = "App.Store1.reload()";
BTN = new Button();
BTN.ID = "BTN";
BTN.Text = "click";
BTN.Icon = Icon.ArrowJoin;
BTN.DirectEvents.Click.Event += new ComponentDirectEvent.DirectEventHandler(Click);
TB = new Toolbar();
TB.Items.Add(BTN);
GP.TopBar.Add(TB);
Store1 = new Store();
Store1.ID = "Store1";
Store1.ReadData += new Store.AjaxReadDataEventHandler(WebFormTest_ReadData);
Model1 = new Model();
Model1.ID = "Model1";
Store1.Model.Add(Model1);
GP.Store.Add(Store1);
TP = new TreePanel();
TP.ID = "TP";
TP.Title = "TP";
TP.Region = Region.East;
TP.RootVisible = false;
TP.Root.Add(new Node() { NodeID = "test", Text = "test" });
Store2 = new TreeStore();
Store2.ID = "Store2";
Store2.ReadData += new TreeStoreBase.ReadDataEventHandler(Store2_ReadData);
TP.Store.Add(Store2);
VP.Items.Add(FP);
//VP.Items.Add(GP);
VP.Items.Add(TP);
if (!X.IsAjaxRequest)
{
CB.Value = "2";
TF.Value = "TEXT";
}
base.OnInitComplete(e);
}
FormPanel FP;
TextField TF;
ComboBox CB;
GridPanel GP;
Button BTN;
Toolbar TB;
Store Store1;
Model Model1;
TreePanel TP;
TreeStore Store2;
protected override void CreateChildControls()
{
base.CreateChildControls();
}
void Store2_ReadData(object sender, NodeLoadEventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
//if (!X.IsAjaxRequest)
//{
// this.Store1.DataSource = this.Data;
// this.Store1.DataBind();
//}
}
protected void Refresh(object sender, DirectEventArgs e)
{
}
bool flag = false;
protected void Click(object sender, DirectEventArgs e)
{
GP.GetStore().Reload();
flag = true;
}
protected override void OnPreRender(EventArgs e)
{
if (flag)
{
TF.Value = "asdasd";
}
base.OnPreRender(e);
}
protected void WebFormTest_ReadData(object sender, StoreReadDataEventArgs e)
{
}
private object[] Data
{
get
{
return new object[]
{
new object[] { "3m Co", 71.72, 0.02, 0.03, "9/1 12:00am" },
};
}
}
}
you also can discuss in Ext.net Forums
We committed the change to the SVN trunk. It will go to the next release (v2.3).
The change is similar to your one, but we decided not to change RawValue as well. Thank you for the report and suggested fix.
Fix (ComboBoxBase LoadPostData)
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();

monotouch dialog multiple radiogroups on a single view (single rootelement)

I would like to use multiple radio groups within a single rootelelement with monotouch dialog. Each radiogroup would have its own section. I can't find a way to make this work because a single radiogroup can only be assigned to the rootelement
svn!
Here is my solution
public class CustomRootElement : RootElement
{
private RadioGroup _defaultGroup = new RadioGroup(0);
private Dictionary<string, RadioGroup> _groups = new Dictionary<string, RadioGroup>();
public CustomRootElement(string caption = "") : base(caption , new RadioGroup("default",0))
{
}
public CustomRootElement(string caption, Group group, Func<RootElement, UIViewController> createOnSelected) : base(caption, group)
{
var radioGroup = group as RadioGroup;
if(radioGroup != null)
{
_groups.Add(radioGroup.Key.ToLower(), radioGroup);
}
this.createOnSelected = createOnSelected;
}
public override UITableViewCell GetCell(UITableView tv)
{
var cell = base.GetCell(tv);
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
return cell;
}
public int Selected(string group)
{
if (string.IsNullOrEmpty(group))
{
throw new ArgumentNullException("group");
}
group = group.ToLower();
if (_groups.ContainsKey(group))
{
return _groups[group].Selected;
}
return 0;
}
public void Select(string group, int selected)
{
if (string.IsNullOrEmpty(group))
{
throw new ArgumentNullException("group");
}
var radioGroup = GetGroup(group);
radioGroup.Selected = selected;
}
internal RadioGroup GetGroup(string group)
{
if (string.IsNullOrEmpty(group))
{
throw new ArgumentNullException("group");
}
group = group.ToLower();
if (!_groups.ContainsKey(group))
{
_groups[group] = new RadioGroup(group , 0);
}
return _groups[group];
}
internal NSIndexPath PathForRadioElement(string group, int index)
{
foreach (var section in this)
{
foreach (var e in section.Elements)
{
var re = e as SlRadioElement;
if (re != null
&& string.Equals(re.Group, group,StringComparison.InvariantCultureIgnoreCase)
&& re.Index == index)
{
return e.IndexPath;
}
}
}
return null;
}
}
public class CustomRadioElement : RadioElement
{
public event Action<CustomRadioElement> ElementSelected;
private readonly static NSString ReuseId = new NSString("CustomRadioElement");
private string _subtitle;
public int? Index { get; protected set; }
public CustomRadioElement(string caption, string group = null, string subtitle = null) :base(caption, group)
{
_subtitle = subtitle;
}
protected override NSString CellKey
{
get
{
return ReuseId;
}
}
public override UITableViewCell GetCell(UITableView tv)
{
EnsureIndex();
var cell = tv.DequeueReusableCell(CellKey);
if (cell == null)
{
cell = new UITableViewCell(UITableViewCellStyle.Subtitle , CellKey);
}
cell.ApplyStyle(this);
cell.TextLabel.Text = Caption;
if (!string.IsNullOrEmpty(_subtitle))
{
cell.DetailTextLabel.Text = _subtitle;
}
var selected = false;
var slRoot = Parent.Parent as CustomRootElement;
if (slRoot != null)
{
selected = Index == slRoot.Selected(Group);
}
else
{
var root = (RootElement)Parent.Parent;
selected = Index == root.RadioSelected;
}
cell.Accessory = selected ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None;
return cell;
}
public override void Selected(DialogViewController dvc, UITableView tableView, NSIndexPath indexPath)
{
var slRoot = Parent.Parent as CustomRootElement;
if (slRoot != null)
{
var radioGroup = slRoot.GetGroup(Group);
if (radioGroup.Selected == Index)
{
return;
}
UITableViewCell cell;
var selectedIndex = slRoot.PathForRadioElement(Group, radioGroup.Selected);
if (selectedIndex != null)
{
cell = tableView.CellAt(selectedIndex);
if (cell != null)
{
cell.Accessory = UITableViewCellAccessory.None;
}
}
cell = tableView.CellAt(indexPath);
if (cell != null)
{
cell.Accessory = UITableViewCellAccessory.Checkmark;
}
radioGroup.Selected = Index.Value;
var handler = ElementSelected;
if (handler != null)
{
handler(this);
}
}
else
{
base.Selected(dvc, tableView, indexPath);
}
}
private void EnsureIndex()
{
if (!Index.HasValue)
{
var parent = Parent as Section;
Index = parent.Elements.IndexOf(this);
}
}
}
Hope this help!

Blackberry - How if addElement() doesn't work?

I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.

Dynamically create node in lwuit for tree view

TreeModel model = new TreeModel() {
Node[] sillyTree = {
new Node("X", new Node[] {
new Node("Child 1", new Node[] {
}),
new Node("Child 2", new Node[] {
}),
new Node("Child 3", new Node[] {
}),
}),
new Node("Y", new Node[] {
new Node("A", new Node[] {
})
}),
new Node("Z", new Node[] {
new Node("A", new Node[] {
}),
}),
};
I want to create a node as dynacially,above sample code for static
plz help
See the TreeDemo class in UIDemo application. Here dynamically retrieve the values from file root and add that values into vector. See the FileTreeModel inner class from TreeDemo class. You can follow the same thing and add the dynamic values like that.
This might help -
class Node {
Vector children;
String value; // Name of the nodeā€¦.
public Node(String value, Vector children) {
this.children = children;
this.value = value;
}
public String toString() {
return value;
}
}
And -
Node[] nodeArray = generateRootNode();
TreeModel model = new TreeModel() {
Node[] sillyTree = nodeArray;
public Vector getChildren(Object parent) {
Node n = (Node) parent;
Object[] nodes = null;
Vector v = new Vector();
if (parent == null) {
nodes = sillyTree;
} else {
v = n.children;
}
if (nodes != null) {
for (int iter = 0; iter < nodes.length; iter++) {
v.addElement(nodes[iter]);
}
}
return v;
}
public boolean isLeaf(Object node) {
boolean returnValue = false;
try {
Node n = (Node) node;
returnValue = n.children == null || n.children.size() == 0;
} catch (ClassCastException ex) {
// It means its a child node or a leaf...
returnValue = true;
}
return returnValue;
}
};

Resources