im trying to display a boolean value as a string in a tableview so instead of true i want to display male.
i'm a bit lost with it to be honest. i cant find anything on the internet to help.
the error ecilpse is giving me is The method " setCellValueFactory(Callback,ObservableValue>) in the type TableColumn is not applicable for the arguments (( cellData) -> {})"
heres my code. its probably wrong
TableColumn<Animal, String > genColumn = new TableColumn<>("Male");
genColumn.setMinWidth(50);
genColumn.setCellValueFactory(cellData -> {
boolean gender = cellData.getValue().getGender();
String genderAsString;
if(gender == true)
{
genderAsString = "Male";
}
else
{
genderAsString = "Female";
}
new ReadOnlyStringWrapper(genderAsString);
});
i would be grateful for any help thanks
Keep the type as boolean and use a cell factory to change the way you display it:
TableColumn<Animal, Boolean> genColumn = new TableColumn<>("Gender");
genColumn.setCellValueFactory(cellData -> cellData.getValue().genderProperty());
// or cellData -> new SimpleBooleanProperty(cellData.getValue().getGender())
// if your model class doesn't use JavaFX properties
genColumn.setCellFactory(col -> new TableCell<Animal, Boolean>() {
#Override
protected void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty) ;
setText(empty ? null : item ? "Male" : "Female" );
}
});
i managed to get it working i was just missing the return statement.
heres the code
TableColumn<Animal, String > genColumn = new TableColumn<>("Gender");
genColumn.setMinWidth(50);
genColumn.setCellValueFactory(cellData -> {
boolean gender = cellData.getValue().getGender();
String genderAsString;
if(gender == true)
{
genderAsString = "Male";
}
else
{
genderAsString = "Female";
}
return new ReadOnlyStringWrapper(genderAsString);
});
Related
How can i handle the following code
List books = ['book1', book2]
String getTextWidget() {
return // here i need to only return the element which is 'book1' such as if books.contains('book1') return this element as String ;
}
the i need to put it in Text Widget like so
Container(
child Text(getTextWidget())
)
i tried the following code , it is work but it does not accept String Widget
getTextWidget() {
books .forEach((element) {
if(element.contains('book1')){
'book1'
}
});
}
I think you'd benefit from the .firstWhere method on your list.
void main() {
// an arbitrary object that is not type String
final book2 = Object();
List books = ['book1', book2];
print(getTextElement(books)); // book1
}
String? getTextElement(List list) {
return list.firstWhere((e) => e is String);
}
try this , give "book1" to the methode as a parameter
String getTextWidget(String nameofbook) {
if(books.contains(nameofbook)==true){
return nameofbook;
}
else return null;
}
edit: The ArrayList wasn't needed to reproduce the "error". Sorry for this delay, but know it should be much clearer.
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
package com.example.mypackage;
import java.util.ArrayList;
import java.util.Scanner;
class Contact {
public String name;
public String number;
public Contact(String name, String number) {
this.name = name;
this.number = number;
}
public void print(){
System.out.println(name+number);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj == null) {
return false;
} else if (obj instanceof Contact) {
Contact contact = (Contact) obj;
if ((contact.name == this.name && contact.number == this.number)) {
return true;
}
}
return false;
}
}
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Contact c1 = new Contact("ben", "1");
c1.print();
Contact c2 = new Contact("ben", "1");
c2.print();
System.out.println("name : ");
String name=scanner.nextLine();
System.out.println("number");
String number=scanner.nextLine();
Contact c3=new Contact(name, number);
c3.print();
System.out.println("c1.equals(c2) = "+c1.equals(c2));
System.out.println("c3 instanceof Contact = "+(c3 instanceof Contact));
System.out.println("c2.name.equals(c3.name) = "+c2.name.equals(c3.name));
System.out.println("c2.number.equals(c3.number) = "+c2.number.equals(c3.number));
System.out.println("c2.number.equals(c3.number) = "+c3.equals(c2));
}
}
Output is:
ben1
ben1
name :
ben
number
1
ben1
c1.equals(c2) = true
c3 instanceof Contact = true
c2.name.equals(c3.name) = true
c2.number.equals(c3.number) = true
c2.number.equals(c3.number) = false
Process finished with exit code 0
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
Ah finally I got it. The error is in the equals method.
I must use "equals()" instead of "==" there. For some reason this comparison does work with c1 and c2 but not with c3.
-1 is returned if it wasn't found in the list.
Did you forget to myList.add() it?
The only add I see is when you added c1.
You need to myList.add(c3) after you get the input, or it won't be in the list to find an index of.
This program accesses a text file with text elements separated by commas. The elements register in the variables I created. Except for the last one. The error then occurs. The program works fine with the default whitespace delimitor for the scanner class (the text file is adjusted accodingly) but fails when I use a comma as the delimitor. Could someone please supply some insight.
Text Data:
smith,john,10
stiles,pat,12
mason,emrick,12
Code:
public void openFile(String f)
{
try{
x = new Scanner(new File(f));
x.useDelimiter(",");
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNext())
{
String lName = x.next().trim();
**String fName = x.next().trim();**
String grade = x.next().trim();
if(fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}
The problem relies on the fact that you called x.useDelimiter(","); on your Scanner in function openFile().
Since your text data is:
smith,john,10
stiles,pat,12
mason,emrick,12
the Scanner sees it as:
"smith,john,10\nstiles,pat,12\nmason,emrick,12"
So what happens when you execute your code is:
1: x.hasNext() ? Yes
x.next().trim() => "smith"
x.next().trim() => "john"
x.next().trim() => "10\nstiles"
2: x.hasNext() ? Yes
x.next().trim() => "pat"
x.next().trim() => "12\nmason"
x.next().trim() => "emrick"
3: x.hasNext() ? Yes
x.next().trim() => "12"
x.next().trim() => Error!
To fix this you can either edit the file and change all the \n with ,, or use a first Scanner to get all the lines, and another one to get the tokens, as shown here:
public void openFile(String f)
{
try{
x = new Scanner(new File(f)); // Leave default delimiter
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNextLine()) // For each line in your file
{
Scanner tk = new Scanner(x.nextLine()).useDelimiter(","); // Scan the current line
String lName = x.next().trim();
String fName = x.next().trim();
String grade = x.next().trim();
if (fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}
I have class in groovy
class WhsDBFile {
String name
String path
String svnUrl
String lastRevision
String lastMessage
String lastAuthor
}
and map object
def installFiles = [:]
that filled in loop by
WhsDBFile dbFile = new WhsDBFile()
installFiles[svnDiffStatus.getPath()] = dbFile
now i try to sort this with custom Comparator
Comparator<WhsDBFile> whsDBFileComparator = new Comparator<WhsDBFile>() {
#Override
int compare(WhsDBFile o1, WhsDBFile o2) {
if (FilenameUtils.getBaseName(o1.name) > FilenameUtils.getBaseName(o2.name)) {
return 1
} else if (FilenameUtils.getBaseName(o1.name) > FilenameUtils.getBaseName(o2.name)) {
return -1
}
return 0
}
}
installFiles.sort(whsDBFileComparator);
but get this error java.lang.String cannot be cast to WhsDBFile
Any idea how to fix this? I need to use custom comparator, cause it will be much more complex in the future.
p.s. full source of sample gradle task (description of WhsDBFile class is above):
project.task('sample') << {
def installFiles = [:]
WhsDBFile dbFile = new WhsDBFile()
installFiles['sample_path'] = dbFile
Comparator<WhsDBFile> whsDBFileComparator = new Comparator<WhsDBFile>() {
#Override
int compare(WhsDBFile o1, WhsDBFile o2) {
if (o1.name > o2.name) {
return 1
} else if (o1.name > o2.name) {
return -1
}
return 0
}
}
installFiles.sort(whsDBFileComparator);
}
You can try to sort the entrySet() :
def sortedEntries = installFiles.entrySet().sort { entry1, entry2 ->
entry1.value <=> entry2.value
}
you will have a collection of Map.Entry with this invocation. In order to have a map, you can then collectEntries() the result :
def sortedMap = installFiles.entrySet().sort { entry1, entry2 ->
...
}.collectEntries()
sort can also take a closure as parameter which coerces to a Comparator's compare() method as below. Usage of toUpper() method just mimics the implementation of FilenameUtils.getBaseName().
installFiles.sort { a, b ->
toUpper(a.value.name) <=> toUpper(b.value.name)
}
// Replicating implementation of FilenameUtils.getBaseName()
// This can be customized according to requirement
String toUpper(String a) {
a.toUpperCase()
}
I would like to create a method that orders an IEnumerable List by a given property where the property is passed into the method by a string i.e. (Mind you the first code example does not work, but the second does and is what I am trying to emulate dynamically).
string sortName = "SerialNumber";
IEnumerable<PartSummary> partList = FunctionToCreateList();
partOrderedList = partList.OrderBy(what do I stick in here);
that would be equivalent to
IEnumerable<PartSummary> partList = FunctionToCreateList();
partOrderedList = partList.OrderBy(p => p.SerialNumber);
How can I accomplish this?
Are you saying you want to pass the order by in to your method? If so, you can use this:
Expression<Func<PartSummary, bool>> orderByClause
Then you can do this:
partOrderedList = partList.OrderBy(orderByClause);
Then you can handle your order by in your business layer or wherever you wish.
Okay, update: If you want to pass in the column name as a string you can do something like as follows:
Create a static class for an extension method (reference: http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/39028ad2-452e-409f-bc9e-d1b263e921f6/):
static class LinqExtensions
{
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortingColumn, bool isAscending)
{
if (String.IsNullOrEmpty(sortingColumn))
{
return source;
}
ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty);
MemberExpression property = Expression.Property(parameter, sortingColumn);
LambdaExpression lambda = Expression.Lambda(property, parameter);
string methodName = isAscending ? "OrderBy" : "OrderByDescending";
Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName,
new Type[] { source.ElementType, property.Type },
source.Expression, Expression.Quote(lambda));
return source.Provider.CreateQuery<T>(methodCallExpression);
}
}
Then you can create your method:
static IQueryable<PartSummary> FunctionToCreateList()
{
IList<PartSummary> list = new List<PartSummary>();
list.Add(new PartSummary
{
Id = 1,
SerialNumber = "A",
});
list.Add(new PartSummary
{
Id = 2,
SerialNumber = "B",
});
return list.AsQueryable();
}
And then call your method:
static void Main(string[] args)
{
IQueryable<PartSummary> partOrderedList = FunctionToCreateList();
PartSummary partSummary = new PartSummary();
string sortBy = "Id";
partOrderedList = partOrderedList.OrderBy(sortBy, false);
foreach (PartSummary summary in partOrderedList)
{
Console.WriteLine(summary.Id + ", " + summary.SerialNumber);
}
Console.ReadLine();
}
Now you can pass in the column name as a string and sort.
Hope this helps!
You can also avoid extending and just use a compiled expression tree to accomplish this:
public Func<T, object> ResolveToProperty<T>(String propertyName)
{
Type t = typeof(T);
var paramExpression = Expression.Parameter(t, "element");
var propertyExpression = Expression.Property(paramExpression, propertyName);
return Expression.Lambda<Func<T, object>>(propertyExpression, paramExpression).Compile();
}
string sortName = "SerialNumber";
IEnumerable<PartSummary> partList = FunctionToCreateList();
var partOrderedList = partList.OrderBy(ResolveToProperty<PartSummary>(sortName));