Unknown size of TextFields Array JavaFX - arrays

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);
});

Related

How do I call a control that was created dynamically in c#

First, a great thank you to those who asked/responded to questions. You were able to get me this far.
I wanted to help a young Belgian entrepreneur by taking on a challenge, build a Media managing software to display various media types (Images, Videos, links, text) on huge LED screens.
I have limited coding experience as I work in EDI.
My issue is that I create playlists dynamically based on the number of playlists in the DB (see screenshot), but I cannot trigger the playing of the right playlist when pressing the play button.
Warning, my code is noob code.
PlayList ScreenShot
Label playListLbl = new Label();
GroupBox playListGrp = new GroupBox();
public GroupBox addplayListGrp(int i, int start, int end)
{
GroupBox playListGrp = new GroupBox();
playListGrp.Name = "playListGrp"+ Convert.ToString(1 + i);
playListGrp.Text = "Play list " + Convert.ToString(1 + i);
playListGrp.Font = new Font("Century Gothic", 12F,
FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
playListGrp.Width = 425;
playListGrp.Height = 525;
playListGrp.Margin = new Padding(1);
playListGrp.Location = new Point(start, end);
return playListGrp;
}
Button addPlayBtn(int i)
{
Button PlayBtn = new Button();
PlayBtn.Font = new Font("Century Gothic", 9.75F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point, ((byte)(0)));
PlayBtn.ForeColor = Color.Black;
PlayBtn.Location = new Point(10, 467);
PlayBtn.Name = "playBtn" + Convert.ToString(1 + i);
PlayBtn.Size = new Size(100, 30);
PlayBtn.TabIndex = 6;
PlayBtn.Text = "Play";
PlayBtn.UseVisualStyleBackColor = true;
PlayBtn.Click += new EventHandler(playBtn1_Click);
return PlayBtn;
}
public BMS_main()
{
int startPos = 5;
int endPos = 5;
for (int i = 1; i <= playlistCountInc; i++)
{
playListGrp = addplayListGrp(i, startPos, endPos);
playListLbl = addLabel(i);
Label playListLblTime = addLabelTime(i);
Button PlayBtn = addPlayBtn(i);
}
playListGrp.Controls.Add(playListLbl);
playListGrp.Controls.Add(playListLblTime);
playListGrp.Controls.Add(playlistView);
playListGrp.Controls.Add(PlayBtn);
}
private void playBtn1_Click(object sender, EventArgs e)
{
if (ScreenStatus)
{
Playing = true;
DisplayTimer.Stop();
DisplayTimer.Enabled = false;
InitialScreenTimer.Stop();
InitialScreenTimer.Enabled = false;
PlayListTimer.Enabled = true;
PlayListTimer.Start();
}
else
{
message = "Veuillez alimenter les panneaux";
result = MessageBox.Show(message, caption, buttons);
}
public void PlayListTimer_Tick(object sender, EventArgs e)
{
Label lblAcessorio4 =
(Label)playListLbl.Controls.Find("playLbl4",
true).FirstOrDefault();
if (lblAcessorio4 != null)
{
lblAcessorio4.Text = "Test lblAcessorio4";
}
else
{
message = "Label is null";
result = MessageBox.Show(message, caption, buttons);
}
Set the Tag property of your button with something which will help you decide later on which song to play:
playListGrp = addplayListGrp(i, startPos, endPos);
playListLbl = addLabel(i);
Label playListLblTime = addLabelTime(i);
Button PlayBtn = addPlayBtn(i);
// You can do this
PlayBtn.Tag = playListGrp; // or anything else
Then in the button click handler, get the value of the Tag and make a decision based on that. Just keep in mind that whatever you set the Tag to, you will need to cast it back to that type. For example, in the above I set it GroupBox so I will cast it to a GroupBox:
private void playBtn1_Click(object sender, EventArgs e)
{
GroupBox gb = ((Button)(sender)).Tag as GroupBox;
// Now make the decision
if(gb.Name == "whatever you need to put here"){ // do whatever }
}
I would put the lisbox and then get the selected item and play that.

Codenameone list adding functionality

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();

Combobox in Toolbar

Sorry for the dump(?) question.How do I add a GTK Combobox to a Toolbar? I have googled it, but did not find an answer. It compiles without error, but when I run the application the following message is printed to the console:
Gtk-CRITICAL **: gtk_toolbar_insert: assertion 'GTK_IS_TOOL_ITEM (item)' failed
Here is an example of the Toolbar+Combobox:
using Gtk;
public class Example : Object {
private Window _win;
private Toolbar _tb;
public Example() {
_win = new Window();
_win.title = "Test";
_win.window_position = WindowPosition.CENTER;
_win.set_default_size(800, 600);
_win.destroy.connect(Gtk.main_quit);
_tb = new Toolbar();
var img = new Image.from_icon_name("document-new", Gtk.IconSize.SMALL_TOOLBAR);
var btn = new ToolButton(img, "New");
_tb.add(btn);
add_zoombox();
var vbox = new Box(Orientation.VERTICAL, 0);
vbox.pack_start(_tb, false, true, 0);
_win.add(vbox);
}
private void add_zoombox() {
ListStore list = new ListStore(1, typeof (int));
for(int i = 25; i<= 400; i*=2) {
TreeIter iter;
list.append(out iter);
list.set(iter, 0, i);
}
ComboBox cb = new ComboBox.with_model(list);
CellRendererText r = new CellRendererText();
cb.pack_start(r, false);
cb.set_active(0);
_tb.add(cb);
cb.show();
}
public void show_window() {
_win.show_all();
}
}
public static int main (string[] args) {
Gtk.init(ref args);
Example ex = new Example();
ex.show_window();
Gtk.main();
return 0;
}
Solved the problem on my own. After reading the doc again, I found out that a Toolbar can only contain only ToolButtons, ToggleToolButtons and RadioToolButtons. To add a Combobox or any other item to the Toolbar it must be added to a ToolItem first. Here is the code that changed:
ToolItem container = new ToolItem();
_tb.add(container);
container.add(cb);
cb.show();

ImageDownloadServices in codenameone

I am trying below mention code for download image from server but it's not working and not giving me any error. Please suggest if any thing wrong which i used.When i am accessing URL from browser it's displaying image to me.
int pos;
public void DisplayContent()
{
f = (Form)createContainer(GlobalVariables.Theme, "ContentPageWise");
body = (Container) findByName("Containerbody", f);
Display_Image = new Image[Page_Details.size()];
for(int i=0;i<Page_Details.size();i++)
{
Hashtable<String,String> hash_page = Page_Details.get(i);
Log.p("imagepath:"+hash_page.get("imgPage"));
pos=i;
GetImagesFromserver(hash_page.get("imgPage"));
Container Cpage = new Container(new BoxLayout(BoxLayout.Y_AXIS));
Label pic = new Label();
pic.setIcon(Display_Image[i]);
Cpage.addComponent(pic);
body.addComponent(Cpage);
}
}
void GetImagesFromserver(String Imagepath)
{
//eg. url like this: http://lmsasr.gizmosupport.com/presentation/tele/internet.jpg
ImageDownloadService imageDownloadService =
new ImageDownloadService(Imagepath, actionListener);
InfiniteProgress ip = new InfiniteProgress();
imageDownloadService.setDisposeOnCompletion(ip.showInifiniteBlocking());
NetworkManager.getInstance().addToQueue(imageDownloadService);
}
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
NetworkEvent n = (NetworkEvent) evt;
Display_Image[pos] = ((Image)n.getMetaData());
}
};

Windows phone 7.1 can I change font size on a shell tile?

I'm trying to display a tweet on the backside of a live tile, when I set it as BackContent it's way too big.... Is there any way to lower the font size?
EDIT:
Claus, Now i'm having trouble getting the tile to display and I can't get any info on why it's not working due to the nature of your ImageOpened call, I can't step through it with the debugger....
In my TileGenerator class, this works:
public static void GenerateTestTile(string strTweet, string strScreenName, string tileTitle)
{
// Define the tile's address. This is where you navigate, when the tile is clicked.
var address = "/MainPage.xaml?TileID=6";
// Check if a tile with the same address already exists
//var tile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString() == address);
var tile = ShellTile.ActiveTiles.First();
// Define our tile data.
var tileData = new StandardTileData
{
BackTitle = strScreenName,
BackContent = strTweet
};
// If the file already exists, update it.
if (tile != null)
{
tile.Update(tileData);
}
else
{
// Otherwise, create a new tile.
ShellTile.Create(new Uri(address, UriKind.Relative), tileData);
}
}
But this doesn't (exact method taken from your example), it doesn't do anything to the tile at all...
public static void GenerateExampleTile(string timeOfDay, string temperature, Uri cloudImagePath, string tileTitle)
{
// Setup the font style for our tile.
var fontFamily = new FontFamily("Segoe WP");
var fontForeground = new SolidColorBrush(Colors.White);
var tileSize = new Size(173, 173);
// Create a background rectagle for a custom colour background.
var backgroundRectangle = new Rectangle();
backgroundRectangle.Width = tileSize.Width;
backgroundRectangle.Height = tileSize.Height;
backgroundRectangle.Fill = new SolidColorBrush(Colors.Blue);
// Load our 'cloud' image.
var source = new BitmapImage(cloudImagePath);
source.CreateOptions = BitmapCreateOptions.None;
source.ImageOpened += (sender, e) => // This is important. The image can't be rendered before it's loaded.
{
// Create our image as a control, so it can be rendered to the WriteableBitmap.
var cloudImage = new Image();
cloudImage.Source = source;
cloudImage.Width = 100;
cloudImage.Height = 64;
// TextBlock for the time of the day.
TextBlock timeOfDayTextBlock = new TextBlock();
timeOfDayTextBlock.Text = timeOfDay;
timeOfDayTextBlock.FontSize = 20;
timeOfDayTextBlock.Foreground = fontForeground;
timeOfDayTextBlock.FontFamily = fontFamily;
// Temperature TextBlock.
TextBlock temperatureTextBlock = new TextBlock();
temperatureTextBlock.Text = temperature + '°';
temperatureTextBlock.FontSize = 30;
temperatureTextBlock.Foreground = fontForeground;
temperatureTextBlock.FontFamily = fontFamily;
// Define the filename for our tile. Take note that a tile image *must* be saved in /Shared/ShellContent
// or otherwise it won't display.
var tileImage = string.Format("/Shared/ShellContent/{0}.jpg", timeOfDay);
// Define the path to the isolatedstorage, so we can load our generated tile from there.
var isoStoreTileImage = string.Format("isostore:{0}", tileImage);
// Open the ISF store,
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
// Create our bitmap, in our selected dimension.
var bitmap = new WriteableBitmap((int)tileSize.Width, (int)tileSize.Height);
// Render our background. Remember the renders are in the same order as XAML,
// so whatever is rendered first, is rendered behind the next element.
bitmap.Render(backgroundRectangle, new TranslateTransform());
// Render our cloud image
bitmap.Render(cloudImage, new TranslateTransform()
{
X = 8, // Left margin offset.
Y = 54 // Top margin offset.
});
// Render the temperature text.
bitmap.Render(temperatureTextBlock, new TranslateTransform()
{
X = 124,
Y = 63
});
// Render the time of the day text.
bitmap.Render(timeOfDayTextBlock, new TranslateTransform()
{
X = 12,
Y = 6
});
// Create a stream to store our file in.
var stream = store.CreateFile(tileImage);
// Invalidate the bitmap to make it actually render.
bitmap.Invalidate();
// Save it to our stream.
bitmap.SaveJpeg(stream, 173, 173, 0, 100);
// Close the stream, and by that saving the file to the ISF.
stream.Close();
}
// Define the tile's address. This is where you navigate, when the tile is clicked.
var address = "/MainPage.xaml?TileID=" + timeOfDay;
// Check if a tile with the same address already exists
var tile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString() == address);
// Define our tile data.
var tileData = new StandardTileData
{
BackgroundImage = new Uri(isoStoreTileImage, UriKind.Absolute),
Title = tileTitle,
};
// If the file already exists, update it.
if (tile != null)
{
tile.Update(tileData);
}
else
{
// Otherwise, create a new tile.
ShellTile.Create(new Uri(address, UriKind.Relative), tileData);
}
};
}
Both methods are being called in this way....
public class ScheduledAgent : ScheduledTaskAgent
{
...
/// <summary>
/// Agent that runs a scheduled task
/// </summary>
/// <param name="task">
/// The invoked task
/// </param>
/// <remarks>
/// This method is called when a periodic or resource intensive task is invoked
/// </remarks>
protected override void OnInvoke(ScheduledTask task)
{
LoadWatchList();
}
//WATCH LIST
private void LoadWatchList()
{
if (HasConnectivity)
{
GetWatchListTweetsFromTwitter(CurrentWatchListID);
}
}
public void GetWatchListTweetsFromTwitter(int list_id)
{
WebClient wcWatchListTimeline = new WebClient();
wcWatchListTimeline.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wcWatchListTimeline_DownloadStringCompleted);
wcWatchListTimeline.DownloadStringAsync(new System.Uri("https://api.twitter.com/1/lists/statuses.xml?per_page=1&list_id=" + list_id));
}
void wcWatchListTimeline_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String strTweet = "content";
String strScreenName = "title";
if (e.Error != null)
{
strScreenName = "error";
strTweet = e.Error.Message;
}
else
{
XElement tweet = XElement.Parse(e.Result);
Tweet thisTweet = GetTweet(tweet);
if (thisTweet != null)
{
strTweet = thisTweet.text;
strScreenName = thisTweet.screen_name;
}
}
// TAKEN FROM EXAMPLE FOR TESTING - NOT WORKING
string timeOfday = "morning";
string temperature = "99";
string location = "San Antonio";
Uri cloudImagePath = new Uri("Images/tweetEmpty.png", UriKind.Relative);
Deployment.Current.Dispatcher.BeginInvoke(() => TileGenerator.GenerateExampleTile(timeOfday, temperature, cloudImagePath, "mainTile"));
//WORKING
//Deployment.Current.Dispatcher.BeginInvoke(() => TileGenerator.GenerateTile(strTweet, strScreenName, "mainTile"));
NotifyComplete();
}
protected Tweet GetTweet(XElement Xdata)
{
List<Tweet> listTweets = (from tweet in Xdata.Descendants("status")
select new Tweet
{
screen_name = tweet.Element("user").Element("screen_name").Value,
text = tweet.Element("text").Value
}).ToList<Tweet>();
if (listTweets.Count > 0)
{
return listTweets[0];
}
else
{
return null;
}
}
}
Only by creating a custom image, and using that as the background for the tile.
Updated: How To: Live Tile with Scheduled Agent

Resources