set combobox value javafx dynamicaly - javafx

i hava probleme to fil a combobox ,
i create buttons dynamicaly where i set a event , whre i use a methode (from where i creat my list ) where i change the view , and set a combobox ,
createButton
private Button createButton(String text) {
Button button = new Button(text);
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button.setPrefSize(100, 100);
button.setOnAction(e -> {
try {
getImprByProduct(text);
} catch (IOException ex) {
Logger.getLogger(DuplicataController.class.getName()).log(Level.SEVERE, null, ex);
}
});
button.setId("btn");
System.out.println("************************** fin creation bouton");
return button;
}
getImprByProduct give me a list of my product wich i want to set in the combobox ,
public List<String> getImprByProduct(String prd) throws IOException {
//afficher Viewdupcontroller
ViewDupController dupController = new ViewDupController();
FXMLLoader fXMLLoader = new FXMLLoader();
fXMLLoader.load(getClass().getResource("/view/application/duplicata/ViewDuplicata.fxml").openStream());
if ((startPage1.global_Session.isOpen()) || (startPage1.global_Session.isConnected())) {
startPage1.global_Session.close();
}
startPage1.global_Session = HibernateUtil.getSessionFactory().openSession();
startPage1.global_Session.beginTransaction();
List<Impression> listImpr = impressionUse.getListImpression_SS();
for (Impression i : listImpr) {
Voucher v = new VoucherUse().getVoucherById(startPage1.global_Session, i.getIdVoucherDebutFk());
if (v.getProduit().getDesignation().equals(prd)) {
result.add(i);
}
}
startPage1.global_Session.getTransaction().commit();
startPage1.global_Session.close();
int p = 0;
for (Impression i : result) {
System.out.println("list des ID impression : " + i.getIdImpression());
list.add(i.getIdImpression().toString());
p++;
}
ListIterator li = list.listIterator();
while(li.hasNext()){
System.out.println("contenu list : " + li.next());
}
System.out.println("*********************************avant add fxml getroot affichage");
anch.getChildren().clear()
anch.getChildren().add(fXMLLoader.getRoot());
dupController.com(list); // i where i call the the methode in the controller of the new view ( of combobox )
return list;
}
dupController.com(list);
ObservableList obList = FXCollections.observableList(list);
combo1.getItems().clear();//where error is
combo1.setItems(obList);

Related

How can i press a button in headerbar and do things in window in vala

How to make a button in headerbar and do things in window i've tried:
public class headerbar : Gtk.HeaderBar {
construct {
title = "Quiz";
subtitle = "You can solve this!";
show_close_button = true;
Gtk.Button button = new Gtk.Button.with_label ("Quit");
button.get_style_context ().add_class ("suggested-action");
button.set_valign (Gtk.Align.CENTER);
button.clicked.connect (() => {
var label = new Gtk.Label ("Hi");
main.add (label);
label.show ();
});
pack_start (button);
}
}
I got a sample as follow, hope it could help you:
public class AppTitleBar : Gtk.HeaderBar {
private Gtk.Button m_new_tab_button;
private Gtk.Box m_app_title_gui_box;
private Gtk.MenuButton m_main_menu_button;
public weak Workbench workbench { get; construct; }
public AppTitleBar (Workbench workbench) {
Object ( workbench: workbench );
}
construct {
set_show_close_button (true);
this.build_title_bar_layout();
}
public void add_new_tab(Widget title_widget)
{
m_app_title_gui_box.pack_start(title_widget);
title_widget.focus.connect(() => {
this.update_tab_inactive_all();
return true;
});
}
public void update_tab_inactive_all()
{
m_app_title_gui_box.foreach ((widget) => {
widget.set_opacity(0.3);
});
}
public void remove_tab_widget(Widget tab_bar)
{
m_app_title_gui_box.remove(tab_bar);
}
private void build_title_bar_layout()
{
m_main_menu_button = new Gtk.MenuButton ();
var menu_image = new Gtk.Image.from_icon_name ("open-menu-symbolic", Gtk.IconSize.BUTTON);
m_main_menu_button.set_image (menu_image);
m_main_menu_button.tooltip_text = ("Main Menu");
// create title bar box
m_app_title_gui_box = new Box(Orientation.HORIZONTAL, 2);
// create add new tab button
m_new_tab_button = new Gtk.Button.from_icon_name("list-add", Gtk.IconSize.BUTTON);
m_new_tab_button.get_style_context ().add_class ("back-button");
m_new_tab_button.valign = Gtk.Align.CENTER;
m_new_tab_button.always_show_image = true;
m_new_tab_button.can_focus = false;
m_new_tab_button.action_name = WorkbenchActions.ACTION_PREFIX + WorkbenchActions.ACTION_TAB_NEW;
m_new_tab_button.has_tooltip = true;
m_new_tab_button.tooltip_text = "Open a new connection (Ctrl+N)";
this.pack_end(m_main_menu_button);
this.pack_start(m_app_title_gui_box);
this.pack_start(m_new_tab_button);
}
}

Fill JavaFX combobox by javascript class (Nashorn)

I try to use my custom class which I have created in my script (the script is written in Nashorn) and after that I try to use this custom class to fill in as items in combobox. I know that if I want to see correct values in combobox that the class has to override method toString, but in this case I do not know much how can be overriden this method in my custom class written in Nahorn.
Below I provide my code where the variables cmbCategories is JavaFX combobox and CategoryItem which I try to use as object to fill in the items in combobox and display as category name.
I would appreciate any suggestion or ideas how can be this problem resolved.
var ClientBuilder = Java.type("javax.ws.rs.client.ClientBuilder")
var Platform = Java.type("javafx.application.Platform")
var Executors = Java.type("java.util.concurrent.Executors")
var Response = Java.type("javax.ws.rs.core.Response")
var String = Java.type("java.lang.String")
var List = Java.type("java.util.ArrayList")
Executors.newSingleThreadExecutor().execute(function () {
print("Calling for category data...")
var categoryData = ClientBuilder
.newClient()
.target(String.format("%s%s", "http://localhost:8080", "/client/action/categories"))
.request()
.get()
if(categoryData.getStatus() == Response.Status.OK.getStatusCode()) {
var categories = JSON.parse(categoryData.readEntity(String.class))
var categoryItems = new List();
for each (var category in categories) {
categoryItems.add(new CategoryItem(category.id, category.category))
}
Platform.runLater(function() {
cmbCategory.getItems().addAll(categoryItems);
});
} else {
print(categoryData.getEntity().toString());
}
})
function CategoryItem(id, name) {
this.id = id;
this.name = name;
this.toString = function () {
return this.name;
}
}
Use the ScriptEngine to retrieve an appropriate string in the cellValueFactory of the ComboBox.
Simplified example
#Override
public void start(Stage primaryStage) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByMimeType("application/javascript");
ComboBox<Object> comboBox = new ComboBox();
comboBox.setCellFactory(c -> new ListCell<Object>() {
#Override
protected void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText("");
} else {
Bindings bindings = new SimpleBindings();
bindings.put("a", item);
try {
// use script engine to retrieve text
setText(Objects.toString(engine.eval("a.name", bindings)));
} catch (ScriptException ex) {
setText("Error");
}
}
}
});
comboBox.setButtonCell(comboBox.getCellFactory().call(null));
Bindings b = new SimpleBindings();
b.put("cmbCategory", comboBox);
engine.eval("function CategoryItem(id, name) {this.id = id;this.name = name;}\n"
+"var Platform = Java.type(\"javafx.application.Platform\")\n"
+ "var categories = [new CategoryItem(1, 'a'), new CategoryItem(2, 'b'), new CategoryItem(3,'c')]\n"
+ "for each (var category in categories) {cmbCategory.getItems().add(category);}", b);
Scene scene = new Scene(new StackPane(comboBox));
primaryStage.setScene(scene);
primaryStage.show();
}
I don't see the purpose of using JavaScript for this though. Everything you do in the javascript code could be done from java code more efficiently...

Unable to modify xaml controls following NFC tag read

I have a method that adds a label with some text to an existing xaml StackLayout.
The method is called from a couple of places, an event fired by xaml ListView and an NFC tag read. In both scenarios, the method is hit in the code-behind.
The methods both call another method that creates the label and adds it on screen. The one that originates from the ListView event works fine but the one from the NFC tag does nothing. It passes over each row of code without causing an exception but does not add anything to the screen. I can see after this that the child count of the StackLayout is 1 and remains as 1 if you do it again.
The NFC method:
public async void HandleNFC(string convertedtag)
{
int result = 0;
try
{
var mp = (MainPage)App.Current.MainPage;
Label sl1 = mp.CurrentPage.FindByName<Label>("timeLabel");
}
catch (Exception e)
{ }
Label sl = timeLabel;
string time = sl.Text;
PeopleLocationsForUserRoot peoplelocationforuser = await WebDataAccess.GetPeopleLocationForUser(UserInfoRepository.GetUserName(), _locationID);
DateTime dt = Convert.ToDateTime(time);
long timeticks = (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
getServerTime();
string name = "";
try
{
foreach (var person in peoplelocationforuser.locationPeople)
{
if (person.TATokenValue == convertedtag)
{
var action = await DisplayActionSheet(person.FirstName + " " + person.LastName, "Cancel", null, "IN", "OUT");
string act = action;
string formattedact = act;
int swipedirection = 0;
name = person.FirstName + " " + person.LastName;
if (act == "IN")
{
formattedact = "in";
swipedirection = 1;
}
if (act == "OUT")
{
formattedact = "out";
swipedirection = 0;
}
if (act != "Cancel")
{
result = SwipeRepository.ClockUserInOut(person.EB_Counter, _locationID, swipedirection, dt, timeticks, 1, UserInfoRepository.GetLatt(), UserInfoRepository.GetLongi());
addToReadout(name, time, formattedact);
}
}
}
if (name == "")
{
await DisplayAlert("Tag Error", "Tag not recognised", "cancel");
}
}
catch (Exception ex)
{
ErrorRepository.InsertError(ex.ToString());
}
await WebDataAccess.SaveSwipesToCloud();
}
The 'addToReadOut' method that it calls:
public void addToReadout(string name, string time, string inout)
{
try
{
Label label1 = new Label { Text = name + " Successfully clocked " + inout + " # " + time, TextColor = Color.Black };
try
{
readOut.Children.Add(label1);
StackLayout sl = this.FindByName<StackLayout>("readOut");
sl.Children.Add(label1);
sl.Focus();
timeLabel.Text = "test";
}
catch (Exception e)
{ }
// StackLayout sl = mp.CurrentPage.FindByName<StackLayout>("readOut");
if (readOut.Children.Count() < 6)
{
readOut.Children.Add(label1);
readOut.Children.Count();
}
else
{
readOut.Children.RemoveAt(0);
readOut.Children.Add(label1);
readOut.Children.Count();
}
}
catch (Exception ex)
{
ErrorRepository.InsertError(ex.ToString());
}
}
You can see that I have also tried to modify the object called 'timelabel' but does also does not change on screen.
The must be something different happening following the NFC event which is causing an issue here but I can't find what's causing it.
You NFC event is firing on a background thread; your UI updates need to happen on the UI thread
Device.BeingInvokeOnMainThread( () => {
// UI Code goes here
});

using CSS to change node design

I dont know what I'am doing wrong with adding CSS style to node.
I have a main application window. Then I click menu item and another modal window opens as below(ModalWindow extends Stage):
FXMLLoader loader = new FXMLLoader(getClass().getResource(CONSTANTS.ROOT_USER_EDIT.string));
BorderPane editPane;
try {
editPane = new BorderPane(loader.load());
ModalWindow editWindow = new ModalWindow(Main.mainStage, editPane, "Edit user");
//its new stage with new scene, so we need to load this file again
editWindow.getScene().getStylesheets().add(getClass().getResource(CONSTANTS.CSS_PATH.string).toExternalForm());
UserData userData = (UserData)usersTable.getSelectionModel().getSelectedItem();
UserEditWindowController userEditWindowController = loader.getController();
userEditWindowController.fillWithData(userData);
editWindow.initModality(Modality.APPLICATION_MODAL);
editWindow.showAndWait();
} catch (IOException exception) {
ExceptionDialog exceptionDialog = new ExceptionDialog("Couldn't load UserEditWindow",exception);
exceptionDialog.showAndWait();
}
this CSS file is added:
#greenInfoTip {
-fx-graphic-text-gap: 20;
-fx-font-size: 44.0px ;
-fx-background: green;
-fx-background-color: rgb(128,255,128);
}
And I try to do this in root controller class:
infoTip.setId("greenInfoTip");
but with no effect. Is there something I'm doing wrong?
EDIT ItachiUchiha here is precisely what it looks like:
method is inside UserEditWindowController class:
#FXML
private void buttSaveAction(ActionEvent event){
//check if login and password doesn't contain spaces and is 4-16 characters long
String login = textFLogin.getText();
String password = textFPassword.getText();
boolean hasLoginWhiteSpace = isContainingWhiteSpace(login);
boolean hasPasswordWhiteSpace = isContainingWhiteSpace(password);
boolean isLoginMoreThan3 = (login.length() > 3)? true : false;
boolean isLoginLessThan17 = (login.length() < 17)? true : false;
boolean isPasswordMoreThan3 = (password.length() > 3)? true : false;
boolean isPasswordLessThan17 = (password.length() < 17)? true : false;
InfoTip infoTip = new InfoTip();
if( hasLoginWhiteSpace == false){
if( hasPasswordWhiteSpace == false ){
if( isLoginMoreThan3 == true && isLoginLessThan17 == true){
if( isPasswordMoreThan3 == true && isPasswordLessThan17 == true ){
//========login and password are correct
String query = "UPDATE users SET login = ?, password = ? WHERE employee_id = ?;";
try( Connection connection = Main.dataSource.getConnection() ){
try( PreparedStatement preparedStatement = connection.prepareStatement(query) ){
preparedStatement.setString(1, login);
preparedStatement.setString(2, password);
preparedStatement.setInt(3, currentUser.getiD());
preparedStatement.executeUpdate();
currentUser.setLogin(login);
currentUser.setPassword(password);
infoTip.getInfoTip().setId("greenInfoTip");
infoTip.showTip((Button)event.getSource(), "Saved");
}
}catch(Exception exception){
ExceptionDialog exceptionDialog = new ExceptionDialog("Error while loading data from database",exception);
exceptionDialog.showAndWait();
};
}else{ //password has less than 4 or more than 16 characters
infoTip.showTip(textFPassword, "no more than 16 and no less than 4 characters!");
}
}else{ //login has less than 4 or more than 16 characters
infoTip.showTip(textFLogin, "no more than 16 and no less than 4 characters!");
}
}else{ //password has white space
infoTip.showTip(textFPassword, "no spaces!");
}
}else{ //login has white space
infoTip.showTip(textFLogin, "no spaces!");
}
}
public class InfoTip {
private Tooltip infoTip;
public InfoTip(){
infoTip = new Tooltip();
}
private static Point2D getNodePos(Node node){ //getting node coordination on screen
Scene nodeScene = node.getScene();
final Point2D windowPos = new Point2D(nodeScene.getWindow().getX(), nodeScene.getWindow().getY());
final Point2D scenePos = new Point2D(nodeScene.getX(), nodeScene.getY());
final Point2D nodePos = node.localToScene(0.0, 0.0);
final Point2D nodePosOnScreen = new Point2D(windowPos.getX() + scenePos.getX() + nodePos.getX(),
windowPos.getY() + scenePos.getY() + nodePos.getY());
return nodePosOnScreen;
}
public void showTip(Node node, String text){
Point2D nodePosOnScreen = getNodePos(node);
infoTip = new Tooltip(text);
infoTip.setFont(new Font(15));
infoTip.setOpacity(0.9);
infoTip.setAutoFix(true);
infoTip.setAutoHide(true);
infoTip.show(node, nodePosOnScreen.getX()-30, nodePosOnScreen.getY() - 40);
}
public Tooltip getInfoTip(){
return infoTip;
}
}
The issue is with
infoTip = new Tooltip(text);
inside howTip(Node node, String text).
You are over-writing the old tooltip with id with a new object. Try using
infoTip.setText(text);

Caliburn.micro : Bind two views of ViewModel with tab Control

I am trying to bind two views of viewmodel to two tabs of tab control by editing sample source code Caliburn.Micro.SimpleMDI included with Caliburn.Micro source. This project contains ShellViewModel and TabViewModel with TabView. I added one View named TabViewDetails. I edited ShellViewModel as follows.
public class ShellViewModel : Conductor<IScreen>.Collection.OneActive
{
int count = 1;
public void OpenTab()
{
TabViewModel vm = null;
if (Items.Count != 0)
{
vm = new TabViewModel() { DisplayName = "Detail Tab " + count++ };
var secondView = new TabViewDetails();
ViewModelBinder.Bind(vm, secondView , null);
}
else
{
vm = new TabViewModel() { DisplayName = "Tab " + count++ };
}
ActivateItem(vm);
}
}
First tab is Ok. But the second tab shows nothing.Can anybody help to figure out the problem?.
I haven't used Caliburn.Micro much but the simple solution is one view, one view model. If you change your code to something like:
public class ShellViewModel : Conductor<IScreen>.Collection.OneActive {
int count = 1;
public void OpenTab()
{
Screen screen;
if (count != 0)
{
screen = new TabViewModel
{
DisplayName = "Tab " + _count++
};
}
else
{
screen = new TestViewModel
{
DisplayName = "Tab " + _count++
};
}
ActivateItem(screen);
}
}
where TestViewModel can be a TabViewModel
public class TestViewModel : TabViewModel
{
}
then this works ok.
The Caliburn docs does have a section multiple views over the same viewmodel but I haven't figured that out yet.

Resources