Combobox refresh value and listview when object content change - combobox

I would like to update my combobox when the content of the object used to display text in combo changes.
Here is a sample:
package com.javafx.example.combobox;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class ComboboxSample extends Application {
class Sequence {
public StringProperty name = new SimpleStringProperty();
public Sequence(String name) {
super();
this.name.set(name);
}
#Override
public String toString() {
return "null";
}
}
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("ComboBoxSample");
ComboBox<Sequence> combo = new ComboBox<>();
combo.setItems(FXCollections.observableArrayList(
new Sequence("Toto"),
new Sequence("Titi")));
combo.getSelectionModel().selectFirst();
combo.setConverter(new StringConverter<ComboboxSample.Sequence>() {
#Override
public String toString(Sequence sequence) {
return sequence.name.get();
}
#Override
public Sequence fromString(String string) {
System.out.println("call fromString");
return null;
}
});
TextField text = new TextField();
Button renameButton = new Button("Rename");
renameButton.setOnAction(evt -> combo.getValue().name.set(text.getText()));
HBox root = new HBox(combo, text, renameButton);
HBox.setHgrow(text, Priority.ALWAYS);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String... args) {
launch(args);
}
}
The combobox contains objects with a property name. If i rename this property, the display do not change or sometimes it changes but not all the time. It is the standard behavior as the combobox update when the object changes, and not when its content changes.
How can i do to force the combobox to refresh its value and the listview on change?
Thanks
EDIT1:
Using a callback in an observaleList seems to be a solution.
package com.javafx.example.combobox;
import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class ComboboxSample extends Application {
ObservableList<Sequence> sequences;
class Sequence {
public StringProperty name = new SimpleStringProperty();
public Sequence(String name) {
super();
this.name.set(name);
}
#Override
public String toString() {
return "null";
}
}
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("ComboBoxSample");
Callback<Sequence, Observable[]> extractor = new Callback<Sequence, Observable[]>() {
#Override
public Observable[] call(Sequence s) {
return new Observable[] {s.name};
}
};
sequences = FXCollections.observableArrayList(extractor);
sequences.addAll(
new Sequence("Toto"),
new Sequence("Titi"));
ComboBox<Sequence> combo = new ComboBox<>();
combo.setItems(sequences);
combo.getSelectionModel().selectFirst();
combo.setConverter(new StringConverter<ComboboxSample.Sequence>() {
#Override
public String toString(Sequence sequence) {
return sequence.name.get();
}
#Override
public Sequence fromString(String string) {
System.out.println("call fromString");
return null;
}
});
combo.valueProperty().addListener((obs, oldValue, newValue) -> System.out.println("Change from " + oldValue.name.get() + " to " + newValue.name.get()));
TextField text = new TextField();
Button renameButton = new Button("Rename");
renameButton.setOnAction(evt -> {
combo.getValue().name.set(text.getText());
});
HBox root = new HBox(combo, text, renameButton);
HBox.setHgrow(text, Priority.ALWAYS);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String... args) {
launch(args);
}
}

Everytime a new value is added to the object list, set the combobox value again. Works for me. I did a small example to show this. Hope it is helpful
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ComboTest extends Application {
int i =0;
ObservableList<String> list = FXCollections.observableArrayList("A","B");
ComboBox<String> combo = new ComboBox();
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
combo.setPromptText("Testing combobox");
combo.setPrefWidth(300);
btn.setText("Add items to list");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
list.add(String.valueOf(i));
System.out.println("size of list " + list.size() );
i++;
combo.setItems(list);
}
});
combo.setItems(list);
VBox root = new VBox();
root.getChildren().addAll(btn,combo);
root.setSpacing(20);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

Related

Remove item from a RecyclerView list based on status of a checkbox

I have a list application what is uses RecyclerView.
Each line has got a button, a checkbox and 2 textview.
All object is defined the RecyclerView clas, but I would like to check the checkbox status in the Main class and evaluate the status and remove the item from the list and from the SharedPreferences where the checkbox is checked
Main class is here:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
}
#Override
public void onItemClick(View view, int position) {
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
At now the item is removed when the whole line is touched. I would like to exchange to if only the Checkbox is "true".
At now the remove method is in the public void onItemClick(View view, int position) function.
I would like to put the content of the OnItemClick method to "if" part of CheckBox status.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
holder.myTextView.setText(meta_data);
holder.subtext.setText(meta_subdata +" "+ meta_subdata2);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = holder.myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView myTextView, subtext;
public Button add;
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done = itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
if(adapter.done.isChecked())should work I think, but I got null opbject reference exception.
Maybe the problem is that the checkbox is in the RecyclerView layout and not in Main class layout, but I am not sure.
Is it possible to handle the Checkbox methods from other class, and if yes, then where should I improve the code?

Not able to read data from Firebase Database in Android Studio

I have an application that is getting price,title etc. data from website. I get data with using jsoup with html parsing. I use a different class for html parsing. I also added membership system from Firebase Authentication to my application. Each user have different product lists. Products are located with user id in database. I want app to get values from database table but it gets titles of tables. My problem is getting titles from database table.
You can see the problem at this photo.
You can see another class at this photo
How can i get values ?
package com.example.lkuygulama;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
public class UrunEklemeActivity extends AppCompatActivity {
FirebaseDatabase firebaseDatabase;
DatabaseReference reference;
private String userId;
private FirebaseAuth.AuthStateListener mAuthlistener;
public ArrayList<String> goster = new ArrayList<String>();
ListView view;
ArrayAdapter<String> arrayAdapter;
public Button aramam,bildirim,liste;
private FirebaseAuth mAuth;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_urun_ekleme);
Urun urun = new Urun();
bildirim=(Button) findViewById(R.id.bildirimButon);
liste = (Button) findViewById(R.id.urunListeButon);
view=(ListView)findViewById(R.id.listele);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,goster);
view.setAdapter(arrayAdapter);
mAuthlistener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = mAuth.getCurrentUser();
userId = user.getUid();
}
};
tanimla();
listele();
bildirim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gonderBildirim();
}
});
}
private void tanimla() {
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference();
}
private void listele() {
reference.child("urunler").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String valeu =dataSnapshot.getKey();
goster.add(valeu);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void gonderBildirim() {
Intent intent = new Intent(this, BildirimActivity.class);
startActivity(intent);
}
private void gonderAra() {
Intent intent = new Intent(this,AramaActivity.class);
startActivity(intent);
}
private void gonderListe() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
You should use getValue(String.class).
Like this :
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String valeu =dataSnapshot.getValue(String.class);
goster.add(valeu);
arrayAdapter.notifyDataSetChanged();
}
I recommend addListenerForSingleValueEvent instead of addChildEventListener.

JAVAFX Text Animation From Array

This is very much a work in progress so I apologize for my code needing to be cleaned up, but I thought it best to include everything I have so far.
I'm trying to figure how to animate text by looping through an array of images. My code loops through the array and displays just the last image. I need to display one image at a time and repeat to give the desired animation effect. What am I doing wrong or not doing?
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.event.EventHandler;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
public class ImageAnimatorWithAudio extends Application {
private final static int NUMBER_OF_SLIDES = 10;
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
Image[] images = new Image[NUMBER_OF_SLIDES];
Timeline animation = new Timeline(new KeyFrame(Duration.millis(5000)));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.TOP_RIGHT);
Button btStartPause = new Button("Start Animation");
hBox.getChildren().add(btStartPause);
//Create border pane
BorderPane borderPane = new BorderPane();
borderPane.setTop(hBox); //Add hBox to borderPane
BorderPane.setAlignment(hBox, Pos.TOP_RIGHT); //Align hBox
btStartPause.setOnAction(e -> {
if (btStartPause.getText().equals("Start Animation")) {
btStartPause.setText("Pause Animation");
animation.play();
} else {
btStartPause.setText("Start Animation");
animation.pause();
}
});
GridPane pane = new GridPane();
pane.setPadding(new Insets(5,5,5,5));
for (int i = 0; i < NUMBER_OF_SLIDES; i++) {
images[i] = new Image("image_path" + i + ".png"); //file names are numerically named(i)
pane.getChildren().add(new ImageView(images[i]));
}
pane.getChildren().add(borderPane);
Scene scene = new Scene(pane, 450, 450);
primaryStage.setTitle("TextAnimation"); //Set the stage title
primaryStage.setScene(scene); //Place the scene in the stage
primaryStage.show(); //Display the stage
}
public static void main(String[] args){
Application.launch(args);
}
}
Any help is appreciated.
Here is an app that demonstrates how to add Images to an ArrayList(similar approach for an Array). It also demonstrates how to load those Images into an ImageView and change them using Timeline.
Main
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author Sedrick
*/
public class JavaFXApplication1 extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="371.0" prefWidth="607.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.60" fx:controller="javafxapplication1.FXMLDocumentController">
<children>
<Button fx:id="btnMain" layoutX="263.0" layoutY="326.0" onAction="#handleButtonAction" text="Click Me!" />
<Label fx:id="lblMain" layoutX="269.0" layoutY="28.0" minHeight="16" minWidth="69" />
<ImageView fx:id="ivMain" fitHeight="201.0" fitWidth="278.0" layoutX="165.0" layoutY="85.0" pickOnBounds="true" preserveRatio="true" />
</children>
</AnchorPane>
Controller
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.util.Duration;
/**
*
* #author Sedrick
*/
public class FXMLDocumentController implements Initializable {
#FXML private Label lblMain;
#FXML private ImageView ivMain;
#FXML private Button btnMain;
Timeline timeline;
List<Image> imageContainer;
int currentImageBeingDisplayed;
#FXML
private void handleButtonAction(ActionEvent event) {
lblMain.setText("Animation started!");
currentImageBeingDisplayed = 0;
timeline.play();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
//Load images
imageContainer = new ArrayList();
for(int i = 1; i <= 12; i++)
{
try
{
System.out.println("/images/Slide" + i + ".PNG");
imageContainer.add(new Image(getClass().getResource("/images/Slide" + i + ".PNG").toURI().toString()));
} catch (URISyntaxException ex) {
System.out.println(ex.toString());
}
}
//Change the image every second
timeline = new Timeline(
new KeyFrame(
Duration.seconds(1),
new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
Platform.runLater(()->{
ivMain.setImage(imageContainer.get(currentImageBeingDisplayed++));
});
}
}
)
);
timeline.setCycleCount(12);
}
}
Output:(looks similar to below)

How to save entire object for a checkbox in javafx

I have number of objects. Let's say i have 10 Books object and i want user to select any number of the book. When user press the submit button i want to retrieve all the books "object" that user selected.
As of now, while showing screen to user i use
CheckBox cb= new CheckBox(book.getName());
this shows bookname to user and user selects the book. But on runtime i will be needing bookid and other properties of book object as well.
Is there anyway through which i can save the book object in the checkbox?
Basic Examle. if you want more sepecifc you need to post your code, we can set object to node using setUserDate, then we can use that object when we need. here i am using object id for example, in yor case save that object i hope this will solve your problem ,?s post a comment
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class UserData extends Application {
public void start(Stage primaryStage) {
VBox root = new VBox();
Book book = new Book(22, "firstBok");
Book book1 = new Book(2, "secondBok");
CheckBox checkB = new CheckBox(book.getName());
checkB.setUserData(book);
CheckBox checkB1 = new CheckBox(book1.getName());
checkB1.setUserData(book1);
Button btn = new Button("Submit");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (checkB.isSelected()) {
int firstCheckBxId = ((Book) checkB.getUserData()).getId();
System.out.println("id:" + firstCheckBxId);
}
if (checkB1.isSelected()) {
int secondCheckBxId = ((Book) checkB1.getUserData()).getId();
System.out.println("id:" + secondCheckBxId);
}
}
});
root.getChildren().addAll(checkB, checkB1, btn);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
class Book {
int id;
private String name;
Book(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return name;
}
}
public static void main(String[] args) {
launch(args);
}
}
Consider using a control with built-in selection functionality, such as a ListView. Then you can just check the selection model.
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BookSelection extends Application {
#Override
public void start(Stage primaryStage) {
ListView<Book> bookList = new ListView<>();
bookList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
bookList.setCellFactory(lv -> new ListCell<Book>() {
#Override
public void updateItem(Book book, boolean empty) {
super.updateItem(book, empty);
if (empty) {
setText(null);
} else {
setText(book.getTitle());
}
}
});
IntStream.rangeClosed(1, 10).mapToObj(i -> new Book("Book "+i)).forEach(bookList.getItems()::add);
Button submit = new Button("Submit selection");
submit.setOnAction(e ->
bookList.getSelectionModel().getSelectedItems().forEach(book -> System.out.println(book.getTitle())));
BorderPane root = new BorderPane(bookList, null, null, submit, null);
BorderPane.setAlignment(submit, Pos.CENTER);
BorderPane.setMargin(submit, new Insets(10));
Scene scene = new Scene(root, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Book {
private final StringProperty title = new SimpleStringProperty() ;
public Book(String title) {
setTitle(title);
}
public final StringProperty titleProperty() {
return this.title;
}
public final java.lang.String getTitle() {
return this.titleProperty().get();
}
public final void setTitle(final java.lang.String title) {
this.titleProperty().set(title);
}
}
public static void main(String[] args) {
launch(args);
}
}
If for some reason you really want to implement this with check boxes, you can keep a Set<Book> representing the selected books, and update it when each check box is selected/unselected. Note this is similar to #user99370's answer, but is more robust as it avoids downcasting the (essentially unknown-type) userData to your data type.
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class BookSelection extends Application {
#Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10 ));
List<Book> books = IntStream.rangeClosed(1, 10).mapToObj(i -> new Book("Book "+i)).collect(Collectors.toList());
Set<Book> selectedBooks = new HashSet<>();
int row = 0 ;
for (Book book : books) {
CheckBox checkBox = new CheckBox();
checkBox.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
selectedBooks.add(book);
} else {
selectedBooks.remove(book);
}
});
grid.addRow(row, checkBox, new Label(book.getTitle()));
row++ ;
}
Button submit = new Button("Submit selection");
submit.setOnAction(e ->
selectedBooks.forEach(book -> System.out.println(book.getTitle())));
GridPane.setHalignment(submit, HPos.CENTER);
grid.add(submit, 0, row, 2, 1);
Scene scene = new Scene(grid, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Book {
private final StringProperty title = new SimpleStringProperty() ;
public Book(String title) {
setTitle(title);
}
public final StringProperty titleProperty() {
return this.title;
}
public final java.lang.String getTitle() {
return this.titleProperty().get();
}
public final void setTitle(final java.lang.String title) {
this.titleProperty().set(title);
}
}
public static void main(String[] args) {
launch(args);
}
}
This is just a simplified version of the accepted answer.
We can use setUserData(Object) to set data and getUserData() to retrieve the previously set data of any JavaFX node (including CheckBox).
Reference:
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#setUserData-java.lang.Object-

My app crashes when i try to launch it

My app crashes when i tried to launch it.
I'm trying to learn how to make the app cycle through an array of strings and then repeats once everything has been picked. This is done with a press of a button. But it crashes when i try to launch it on my phone. Any suggestions or help would be greatly appreciated.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity {
TextView textOne = (TextView) findViewById(R.id.TextView1);
Button pushMe = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textOne.setText(pick());
}
List<String> myStrings = new ArrayList<String>() {{
add("b");
add("a");
add("z");
add("y");
add("x");
}};
List<String> dupeList = new ArrayList<String>() {{
addAll(myStrings);
}};
Random r = new Random();
public String pick() {
String retval = "";
int pos;
switch (dupeList.size()) {
case 1:
retval = dupeList.get(0);
dupeList.clear();
dupeList.addAll(myStrings);
return retval;
default:
pos = r.nextInt(dupeList.size());
retval = dupeList.get(pos);
dupeList.remove(pos);
return retval;
}
}
});
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//this opens another activity
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.RulesButton:
startActivity(new Intent(this, RulesActivity.class));
break;
}
return true;
}
}
found the problem. i just needed to change "TextView textOne...." to "final TextView textOne..." and place it below the onCreate method.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.TextView1);
Button pushMe = (Button) findViewById(R.id.button);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textOne.setText(pick());
}
List<String> myStrings = new ArrayList<String>() {{
add("b");
add("a");
add("z");
add("y");
add("x");
}};
List<String> dupeList = new ArrayList<String>() {{
addAll(myStrings);
}};
Random r = new Random();
public String pick() {
String retval = "";
int pos;
switch (dupeList.size()) {
case 1:
retval = dupeList.get(0);
dupeList.clear();
dupeList.addAll(myStrings);
return retval;
default:
pos = r.nextInt(dupeList.size());
retval = dupeList.get(pos);
dupeList.remove(pos);
return retval;
}
}
});
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//this opens another activity
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.RulesButton:
startActivity(new Intent(this, RulesActivity.class));
break;
}
return true;
}
}
Just for information as you are new in Android logs will help you more.
Log will be in eclipse tool (developing tool you are using) not on your device.
Change perspective to DDMS -> Go to LogCat.
There will be error logs in it.

Resources