I'm working on a project where the TableView looks like this:
The datas are inside are a MySQL database, and I use a modell and an observableArrayList to get them.
I want to make an initialize method which read the whole selected Line and save it into the TextFields (like Name-Name, Address - Address etc). I tried with this, and now I can Select the Whole Line data, but can't split it into Strings to set the TextField texts:
ListViewerModell details = (ListViewerModell) table.getSelectionModel().getSelectedItem();
//Checking if any row selected
if (details != null) {
//??? - split
editName.setText("*Name*");
editAddress.setText("*Address*");
}
Tried with the modell getName(), getAdress() methods but I got NullPointerException and TablePos methods.
// create table
TableView<Person> table = new TableView<Person>();
// create columns
TableColumn<Person, String> nameCol = new TableColumn<Person, String>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory("name"));
TableColumn<Person, Address> addressCol = new TableColumn<Person, String>("Address");
addressCol.setCellValueFactory(new PropertyValueFactory("address"));
// add columns
table.getColumns().setAll(nameCol, addressCol);
// get data from db, return object List<Person> from DB
ObservableList<Person> persons = getPersonsFromDB();
table.setItems(persons);
tableView.setOnMouseClicked((MouseEvent event) -> {
if (event.getClickCount() > 1) {
onEdit();
}
});
public void onEdit() {
// check the table's selected item and get selected item
if (table.getSelectionModel().getSelectedItem() != null) {
Person selectedPerson = table.getSelectionModel().getSelectedItem();
nameTextField.setText(selectedPerson.getName());
addressTextField.setText(selectedPerson.getAddress());
}
}
One way could be extracting the value of the columns of the selected row, like so :
Object selectedItems = table.getSelectionModel().getSelectedItems().get(0);
String first_Column = selectedItems.toString().split(",")[0].substring(1);
System.out.println(first_Column);
Related
I have a MultiSelectComboBox but when trying to select some items through its select() method nothing happens.
My code looks as follows:
Binder<Technology> binder = new BeanValidationBinder<>(Technology.class);
MultiSelectComboBox<TechnologyLabel> multiComboBox = new MultiSelectComboBox<>("Labels");
binder
.forField(this.multiComboBox)
.bind(Technology::getLabels, Technology::setLabels);
List<TechnologyLabel> labelList = technologyLayout.technologyLabelService.getTechnologyLabels(technology);
List<Label> containedLabels = new ArrayList<>();
for (var tl : labelList) {
containedLabels.add(tl.getLabel());
}
List<Label> labels = labelService.findAllLabels();
for (var label : labels) {
if (!containedLabels.contains(label)) {
labelList.add(new TechnologyLabel(technology, label));
}
}
multiComboBox.setItems(labelList);
multiComboBox.setItemLabelGenerator(TechnologyLabel::getLabelName);
note.setMaxHeight("10em");
multiComboBox.select(labelList.get(0);
What I do above is querying my ManyToMany relation to find all labels given the technology. Then I find all the labels and create a list from that. Lastly, I try to select first item of the list, but it does not show a tick next to it.
Okey so my problem is next: I use web scraping to take some data from web page IMDB in this case, that data is titles of movies, and I already tried to print it in console and that works fine. My problem is that I can not save that titles in my table columns, I put all needed codes for this problem, and I cant find where I made mistake and why titles wont show in table columns. At the and, user need to pick one title and that title need to be stored in text field. Have someone any idea, please?
I have table:
TableColumn izborAuta = new TableColumn("Izbor auta");
TableColumn lokacijaPreuzimanja = new TableColumn("Lokacija
preuzimanja");
TableColumn lokacijaVracanja = new TableColumn("Lokacija Vracanja");
TableColumn cena = new TableColumn("Cena");
I have this code to setup columns:
izborAuta.setCellValueFactory(new PropertyValueFactory<Vozila, String>
("izborAuta"));
lokacijaPreuzimanja.setCellValueFactory(new
PropertyValueFactory<Vozila, String>("lokacijaPreuzimanja"));
lokacijaVracanja.setCellValueFactory(new
PropertyValueFactory<Vozila, String>("lokacijaVracanja"));
cena.setCellValueFactory(new PropertyValueFactory<Vozila, String>
("cena"));
tableView.setItems(Baza.baza.prikazBaze());
tableView.getColumns().addAll(izborAuta, lokacijaPreuzimanja,
lokacijaVracanja, cena);
I have this code, so when I pick one item from table that item need to be stored in textField:
tableView.setOnMouseClicked((e) -> {
Vozila v = (Vozila)
tableView.getSelectionModel().getSelectedItem();
txIzborAuta.setText(v.getIzborAuta());
txLokacijaPreuzimanja.setText(v.getLokacijaPreuzimanja());
txLokacijaVracanja.setText(v.getLokacijaVracanja());
txCena.setText(v.getCena());
});
And at the end I use web scraping to save items in table:
Document doc = Jsoup.connect("https://www.imdb.com/chart/top?
ref_=nv_mv_250").get();
Elements elems = doc.select("table.chart.full-width");
for (Element e : elems) {
String izborAuta = e.select(".titleColumn").text();
String lokacijaPreuzimanja = e.select(".titleColumn").text();
String lokacijaVracanja = e.select(".titleColumn").text();
String cena = e.select(".titleColumn").text();
Vozila v = new Vozila();
v.setIzborAuta(izborAuta);
v.setLokacijaPreuzimanja(lokacijaPreuzimanja);
v.setLokacijaVracanja(lokacijaVracanja);
v.setCena(cena + " " + "RSD");
Baza.insertVozila(v);
}
Is there a way to get an mouse-click on an Header of a Table?
Why i need this?
I have a Table with many Columns. But only a specific witdth for the whole Table.
To avoid scrolling, i want to give each Column an specific width (50 or so), and just if you click on an header, this column will expand so you can read the content. If you click on another header, the previous one collapse.
Hopefully someone can help me:)
Unfortunately there isn't a nice way to do this. The only public API option is to replace the "graphic" of the column with your own label, and then add a mouse listener to that. For this to work you also need to clear any existing column text.
Note that columns by default have click listeners to implement sorting, it seems you don't want this behaviour, so you'll also need to call column.setSortable(false)
#Override
public void start(Stage primaryStage) throws Exception {
TableView<String> tableView = new TableView<>();
TableColumn<String, Object> x = new TableColumn<>("x");
tableView.getColumns().add(x);
TableColumn<String, Object> y = new TableColumn<>("");
tableView.getColumns().add(y);
x.setSortable(false);
y.setSortable(false);
makeHeader(x, "X", 0);
makeHeader(y, "Y", 1);
EventHandler<? super MouseEvent> handler = event -> {
System.out.println("Column clicked " + ((Node)event.getTarget()).getProperties().get("index"));
};
x.getGraphic().addEventFilter(MouseEvent.MOUSE_CLICKED, handler);
y.getGraphic().addEventFilter(MouseEvent.MOUSE_CLICKED, handler);
primaryStage.setScene(new Scene(tableView));
primaryStage.show();
}
private void makeHeader(TableColumn<?, ?> target, String name, int index) {
VBox vBox = new VBox(new Label(name));
vBox.setAlignment(Pos.CENTER);
vBox.getProperties().put("index", index);
target.setGraphic(vBox);
target.setText("");
}
// Step 0: call setOnShown(...).
stage.setOnShown(event -> {
setHeaderClickListeners(); // Call this method when the stage is shown.
});
And then you create a method setHeaderClickListeners(), as follows:
private void setHeaderClickListeners() {
// Step 1: Get the table header row.
TableHeaderRow headerRow = null;
for (Node n : ((TableViewSkin<?>) tableView.getSkin()).getChildren()) {
if (n instanceof TableHeaderRow) {
headerRow = (TableHeaderRow) n;
}
}
if (headerRow == null) {
return;
}
// Step 2: Get the list of the header columns.
NestedTableColumnHeader ntch = (NestedTableColumnHeader) headerRow.getChildren().get(1);
ObservableList<TableColumnHeader> headers = ntch.getColumnHeaders();
// Step 3: Add click listener to the header columns.
for (int i = 0; i < headers.size(); i++) {
TableColumnHeader header = headers.get(i);
final int index = i;
header.setOnMouseClicked(mouseEvent -> {
// Optional:
// Get the TableColumnBase (which is the object responsible
// for displaying the content of the column.)
TableColumnBase column = header.getTableColumn();
// Step 4: Handle double mouse click event.
if (mouseEvent.getButton() == MouseButton.PRIMARY && mouseEvent.getClickCount() == 2) {
P.x("Header cell " + index + " clicked! " + column.getText());
}
});
}
}
I need to make a programm in JavaFX where I need to manage a movie library. I have a tableview that is filled by an observable list. Then I made bindings between the Properties and the Textboxes or Labels next to the tableview. Now the problem is, I have also pictures that are related to the movies, like cinema posters. and at the moment I just use a hardcoded one:
imgPoster = new Image(getClass().getResourceAsStream("../resources/images/posters/" + 5 + ".jpg"));
In the datafile there is one column with the ID of the movie and the same number is also the picture for it. So I need to replace that "5" in the sample code with a binding or so that it actively changes the picture as soon as I click on a row in the tableview.
How do I do that?
edit:
After the first comment i did that:
imgOscars = new Image(getClass().getResourceAsStream("../resources/images/oscar/Oscar-logo.png"));
oscars = new ImageView(imgOscars);
oscars.setPreserveRatio(true);
oscars.setFitHeight(45);
but question stays
Either add a listener to the selected item property in the table (I am just guessing at the model you are using for the table):
TableView<Movie> table = ... ;
table.getSelectionModel().selectedItemProperty().addListener((obs, oldSelectedMovie, newSelectedMovie) -> {
if (newSelectedMovie == null) {
oscars.setImage(null);
} else {
// get image from new selection
Image image = new Image(getClass().getResourceAsStream("../resources/images/oscar/"+newSelectedMoviegetId()+".png"));
oscars.setImage(image);
}
});
or use a binding:
oscars.imageProperty().bind(Bindings.createObjectBinding(() -> {
if (table.getSelectionModel().getSelectedItem() == null) {
return null ;
} else {
Movie selected = table.getSelectionModel().getSelectedItem();
return new Image(getClass().getResourceAsStream("../resources/images/oscar/"+selected.getId()+".png")); ;
},
table.getSelectionModel().selectedItemProperty());
I want to add rows to a table depending on an ID i get earlier.
I have managed to do it in SWT but I do not know how to do it in javaFx.
Here is the code I wrote for SWT:
int availableDesings = designManagement.getNumberOfDesigns();
ArrayList<Design> designs = designManagement.getDesignArray();
for (int i = 0 ; i< availableDesings ; i++){
TableItem item = new TableItem(table, SWT.NONE);
item.setText (0, String.valueOf(designs.get(i).getId()));
item.setText (1, String.valueOf(designs.get(i).getPart_name()));
}
Can anyone help me translating the code to javaFx?
If you have a TableView in JavaFX and it is assigned to a ObservableList of items :
TableView<String> table = new TableView<>();
ObservableList<String> list = FXCollections.observableArrayList();
table.setItems(list);
Then you can add data to the Table, by adding data to the list :
table.getItems().add("New Item");
or, you can directly add data to the list :
list.add("New Item");
For more, information, check this link :
Adding New Rows
private ObservableList<Design> data = FXCollections.observableArrayList();
.....
....
data.addAll(designManagement.getDesignArray()); //all you items
TableView<Design> table = new TableView<>();
TableColumn<Design, String> column1 = new TableColumn<>();
column1.setCellValueFactory(new PropertyValueFactory<Design, String>("id"));
TableColumn<Design, String> column2 = new TableColumn<>();
column2.setCellValueFactory(new PropertyValueFactory<Design, String>("part_name"));
table.getColumns().add(column1);
table.getColumns().add(column2);
table.setItems(data);
you can actually add row to a tableview in javafx though i haven't tried using it. But i have done it with TableColumn.
This is some code that i have done for my small project
TableView<Person> personTable = new TableView<>();
TableColumn<Person,String> nameColumn=new TableColumn<>("Name");
nameColumn.setMinWidth(200);
nameColumn.setCellValueFactory(new PropertyValueFactory<>("Name"));
TableColumn<Person, Gender> genderColumn=new TableColumn<>("Gender");
genderColumn.setMinWidth(30);
genderColumn.setCellValueFactory(new PropertyValueFactory<>("gender"));
TableColumn<Person,String> mobileNumberColumn=new TableColumn<>("mobileNumber");
mobileNumberColumn.setMinWidth(150);
mobileNumberColumn.setCellValueFactory(new PropertyValueFactory<>("mobileNumber"));
TableColumn<Person, Blood> bloodColumn=new TableColumn<>("Blood Type");
bloodColumn.setMinWidth(30);
bloodColumn.setCellValueFactory(new PropertyValueFactory<Person, Blood>("blood"));
personTable.setItems(getPerson());//setting content retrieved from the database into the table
personTable.getColumns().addAll(nameColumn, genderColumn, mobileNumberColumn,bloodColumn);//adding all columns to table
so what it means is when i say
TableColumn mobileNumberColumn=new TableColumn<>("mobileNumber");
i mean mobileNumberColumn is using the class Person from which a string is assigned to the column. the mobile number in quotes is the name of the table.
mobileNumberColumn.setCellValueFactory(new PropertyValueFactory<>("mobileNumber"));
The above line say that the value of the column is the instance variable mobileNumber of the the class person.But for this to work you should have a getMobileNumber() method in person class. It has to be exactly like that for the tableView to work.
hope this helps