How to create an array of TextFields in JavaFX - arrays

I am converting an app written using Swing to JavaFX. I need an array of TextFields that I can manipulate collectively and as individual array members addressed by the array index. The following code works in Swing but I cannot find the equivalent in JavaFX, using TextField instead of JTextField. How can I achieve this in JavaFX?
private ArrayList<JTextField> fieldList= new ArrayList<JTextField>();
fieldList.add(fldCompletion);
fieldList.add(fldHrsToDate);
fieldList.add(fldHrsToComplete);
for(JTextField fl : fieldList) {
fl.setText("");
fl.setEnabled(true); //FX equivalent is setDisable(false)
}
fieldList.get(var).setText("");

I also don't understand your question because this part of the code should work in JavaFX in the same way as it works in Java(Swing) and you are not telling us what your actual problem is. So I just make a wild guess. Maybe you have just forgotten to add your text field to the scene graph too and therefore your are seeing nothing.

Apologies - it's my first post.
I can instantiate the ArrayList -
private ArrayList<TextField> fieldList = new ArrayList<TextField>();
but when I try to add a TextField object to the array I get syntax errors:
fieldList.add(fldCompletion);
Multiple markers at this line
- Syntax error, insert ")" to complete MethodDeclaration
- Syntax error on token ".", # expected after this token
- Syntax error, insert "SimpleName" to complete QualifiedName
- Syntax error, insert "Identifier (" to complete
MethodHeaderName
This particular field is declared thus:
#FXML private TextField fldCompletion;

This will do just fine
TextField[] txt = new TextField[beanFields.length];
for (int i=0; i<=beanFields.length-1; i++) {
TextField textField = new TextField();
txt[i] = textField;
textField.setPrefWidth(200);
textField.setPrefHeight(32);
}

Related

Displaying text from an array into text box

First off, I'd like to apologize for the newbie question, I'm trying to learn as I go with this. I've made a couple basic iOS apps but this is my first venture into macOS Storyboard apps with no formal training in programming.
I'm trying to create a program to help my partner (a writer by profession) with their creative blocks by displaying character, setting, and action attributes that can be used in a story. (Screenshots attached for a better representation)
I believe I have the basic window formatting down but I'm getting stuck on how to link the "Attribute" buttons to the text fields to display elements in the array. I just have placeholder elements until I get it working but ideally you would click the attribute button and it would display a random attribute from the array into the text box.
I've included what I was able to piece together so far but it's failing to build at the line to output to the text box and I can't seem to figure it out.
The error is:
Cannot assign value of type () to type String
Any assistance is appreciated!
import Cocoa
class SecondViewController: NSViewController {
#IBOutlet weak var CharAtt1: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func CharAttBut1(_ sender: NSButton) {
let array = ["Swift", "SwiftUI", "UIKit"]
let randomElement = array.randomElement()!
CharAtt1.stringValue = print("\(randomElement)")
}
}
Obviously, the offending line of code is:
CharAtt1.stringValue = print("\(randomElement)")
It's got a fair number of issues. The most prudent is that print has a type of (approximately, I'm simplifying) (Any) -> Void. You're calling it, passing it a string ("\(randomElement)"). This will print the string to the console, but it will also return back a () (a.k.a. the empty Tuple, of type Void). As the error message suggests, this can't be assigned to CharAtt1.stringValue, which is expecting a String.
The fix is simple, don't call print:
// If you do want to print it, do it in a separate expression
print("\(randomElement)")
CharAtt1.stringValue = "\(randomElement)"
But there's another issue: "\(randomElement)" is useless. randomElement is already a String. You could just write:
print(randomElement)
CharAtt1.stringValue = randomElement
I'd say that "\(anything)" is kind of anti-pattern. If you need to convert something to a string, I think it's better to do so in a way that's more explicit about the conversion you want. E.g. using String(anything) (if such an initializer exists), or String(describing: anything), or String(reflecting: anything) (depending on your usecase)

Displaying Parse Data to ContainerList

I want to display data from Parse in a list from GamesScores class using Container in Codename One, this is what I've tried so far and it's not showing anything nor giving any errors:
Container container = findListCont();
container.setLayout(BoxLayout.y());
container.setScrollableY(true);
ParseQuery<ParseObject> query = ParseQuery.getQuery("GameScore");
List<ParseObject> results = (List<ParseObject>) query.find();
System.out.println("Size: " + results.size());
container.addComponent(results, f);
Please help me out, I'm a new in Codename One. If there tutorials on it, please share or anything to help me achieve the desired results.
I'm actually shocked this isn't failing. You are using the add constraint to place the object result as a constraint and you add the form object into the container...
You need to loop over the results and convert them to components to add into the layout. It also seems that you are using the old GUI builder which I would recommend against.
Generally something like this rough pseudo code should work assuming you are using a box Y layout:
for(ParseObject o : results) {
MultiButton mb = new MultiButton(o.getDisplayValue());
f.add(mb);
}
f.revalidate();

Swift 3 - set the key when appending to array

I have this array where I set the keys on the creation. Now in some point in my view I load some more information based on ids (the keys).
var colors = [
"37027" : UIColor(red:150/255, green:57/255, blue:103/255, alpha:1),
"12183" : UIColor(red:234/255, green:234/255, blue:55/255, alpha:1),
"44146" : UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
]
I want to add more colors to this array dynamically. How can I insert new items in the array setting the key? Something like
colors["25252"] = UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
The line above doesn't work, it is just to illustrate what I need.
Thanks for any help
Update: the code above is an example. Below the real code:
var placedBeacons : [BeaconStruct] = []
BeaconModel.fetchBeaconsFromSqlite(completionHandler: {
beacons in
for item in beacons{
self.placedBeacons["\(item.major):\(item.minor)"] = item
}
})
Error: Cannot subscript a value of type '[BeaconStruct]' with an index of type String
To match the key subscripting
self.placedBeacons["\(item.major):\(item.minor)"] = item
you have to declare placedBeacons as dictionary rather than an array
var placedBeacons = [String:BeaconStruct]()
It requires that item is of type BeaconStruct
The code you wrote, it should work. I have used such kind of code and was able to implement successfully. I just tested your code in my end and it's working for me. I declared colors variable globally in my class file and in view did load method added the second code to add another item in my colors array. After printing it out. My output shows full list of array with 4 items and the number of array count return 4 as well.
Please let me know, more details of your scenario so i can help you to figure it out the issue. but looks like it should work.

Null reference when using a variable with findcontrol

I have a .aspx page with several textboxes, including textboxes with IDs of txtID1, txtID2, txtID3... and so on.
I am attempting populate the textboxes with a data from an XML file by looping through a node list. With each loop, I want to use the FindControl method to locate txtID1 and set its .Text to the value of the id attribute of the first node; then locate txtID2 and its .Text to the value of the id attribute of the second node, and so on.
When the following line of code is run, I get a null reference error for TextBox txtID, so it appears that I am doing something wrong with the FindControl method. Is my syntax incorrect? Do I need to use a different method?
int x = 1;
XmlNodeList getAuthors = getItem.SelectNodes("item/authors");
foreach (XmlNode getAuthor in getAuthors)
{
TextBox txtID = (TextBox)Page.FindControl("txtID" + x.ToString());
txtID.Text = getAuthor.Attributes["id"].Value.ToString();
x = x + 1;
}
After further research (that is, lots of Googling), it appears that I may be running into this problem because I am using a master page. Neither (TextBox)FindControl nor (TextBox)Page.FindControl was working so I have abandoned this approach. Here is an old article that seems to explain my problem.
http://weblog.west-wind.com/posts/2006/Apr/09/ASPNET-20-MasterPages-and-FindControl

Trouble with basic arrays

I am fairly new to programming, and I'm trying to do some work with arrays, but I'm getting an error that I don't know how to fix. Any help would be great!
Error: 1084: Syntax error: expecting colon before leftbracket.
Source: hockeyPP({hockeyPlayers[i]});
Error: 1084: Syntax error: expecting identifier before rightbrace.
Source: hockeyPP({hockeyPlayers[i]});
function eliminateAbsentees():void{
for(var i:int=0; i<=hockeyPlayers.length; i++){
if(hockeyPlayers[i].attendance==true){
hockeyPP.push({hockeyPlayers[i]});
}
}
}
remove { and } surrounding hockeyPlayers[i]. Why you want to used it in this way?
function eliminateAbsentees():void{
for(var i:int = 0; i <= hockeyPlayers.length; i++){
if(hockeyPlayers[i].attendance == true){
hockeyPP.push(hockeyPlayers[i]);
}
}
}
As mentioned by Azzy Elvul, your issue was the curly brackets ( "{}" ) around the array item. You'll see curly brackets in a few places:
Function Declarations
Object Declarations
Class Declarations
Loops
Conditionals
I think there is one more, but that is what I came up with off the top of my head. Basically, when you tried to use this line:
hockeyPP.push({hockeyPlayers[i]});
you tried to declare hockeyPlayers[i] as a new Object (the most basic class in ActionScript, and most languages). You can instantiate the Object class by two ways:
var obj:Object = new Object(); and
var obj:Object = {};
You tried to do the second one, the lazy instantiation. So you tried to declare an object with a property of hockeyPlayers[i] without associating a value with it (the basis of all OOP is property:value pairs).
As that first error said, you are missing a colon for that type of instantiation. If you were to try
hockeyPP.push({hockeyPlayers[i] : null}); //null is what an object is when it has no value
you would not have gotten any errors, as that is the correct way to instantiate an Object. For your needs, though, you just want to push an item from one array to another array. So you do
array2.push( array1[ selectedIndex ] );
I would definitely give the LiveDocs some reading. They can seem daunting, but they are incredibly well written and easy to understand once you start going through them.
LiveDocs - Array
LiveDocs - Object

Resources