How to add item to ObservableList in onMessage event listenerHow to add local jar files to a Maven project?OGNL setValue target is nullJms in a swing application best practices when sending message?ActiveMQ some consumers not picking up tasks if they arrive after producerSend SMS on AndroidWorking on a java based chatting application using threadingHow exactly works JMS queue (point to point message)?check server is available in network or not, using JSCHJavaMail - multiple sendersWildFly 10 with WebSphere MQ 9 : onMessage MDB deploy error

Should I include salary information on my CV?

Does squid ink pasta bleed?

Why does the numerical solution of an ODE move away from an unstable equilibrium?

How to add multiple ip address in destination ip in acl rule

How to perform Login Authentication at the client-side?

Hot coffee brewing solutions for deep woods camping

How does a blind passenger not die, if driver becomes unconscious

MH370 blackbox - is it still possible to retrieve data from it?

Brick or set ID for part?

Can White Castle?

Alphabet completion rate

Why do some professors with PhDs leave their professorships to teach high school?

What sort of mathematical problems are there in AI that people are working on?

Intuitively, why does putting capacitors in series decrease the equivalent capacitance?

Using “sparkling” as a diminutive of “spark” in a poem

When is it ok to add filler to a story?

Has there been any indication at all that further negotiation between the UK and EU is possible?

How to reply to small talk/random facts in a non-offensive way?

Is this one of the engines from the 9/11 aircraft?

Do hotel cleaning personnel have any benefit from leaving empty bottles in the room as opposed to returning them to the store?

Links to webpages in books

Can I compare DFT calculations with different grids?

First-year PhD giving a talk among well-established researchers in the field

Can the negators "jamais, rien, personne, plus, ni, aucun" be used in a single sentence?



How to add item to ObservableList in onMessage event listener


How to add local jar files to a Maven project?OGNL setValue target is nullJms in a swing application best practices when sending message?ActiveMQ some consumers not picking up tasks if they arrive after producerSend SMS on AndroidWorking on a java based chatting application using threadingHow exactly works JMS queue (point to point message)?check server is available in network or not, using JSCHJavaMail - multiple sendersWildFly 10 with WebSphere MQ 9 : onMessage MDB deploy error






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am making two simple JMS application with JavaFx (one for sender and the other one is receiver).



But, I could not refresh the GUI of the receiver with the new arriving message from the sender.



From debugging, I noticed that the receiver received the message from the server, but the receiver could not add it to my ObservableList (which, of course, resulted in no refreshing in the GUI of the ListView).



I looked up on the internet with onMessage event, and override it (to add an item to the ObservableList there), but it is not working. After the event is raised, no element was added to the ObservableList.



This is my receiver:



public class Administrator extends Application 
private ObservableList<String> observableList;
private final String DESTINATION_TYPE = "queue";
private final String RECEIVE_CHANNEL = "askDestination";
private final String SEND_CHANNEL = "answerDestination";
private MessageConsumer messageConsumer;
private MessageProducer messageProducer;
private Session session;
private Destination destination;
private Connection connection;

@FXML
public TextField tfMessage;

@FXML
public ListView<String> lvMessage;

@FXML
public Button btnSend;

@Override
public void start(Stage stage) throws IOException
Parent root = FXMLLoader.load(getClass().getResource("administratorUI.fxml"));
stage.setTitle("Administrator");
stage.setScene(new Scene(root, 640, 480));
stage.setResizable(false);
stage.show();


@Override
public void init() throws Exception
super.init();
lvMessage = new ListView<>();
tfMessage = new TextField();
//questionList = new ArrayList<>();
observableList = FXCollections.observableArrayList();
lvMessage.setItems(observableList);
initService(RECEIVE_CHANNEL, DESTINATION_TYPE);
getMessage(RECEIVE_CHANNEL);
//Platform.runLater(this::updateLV);


public static void main(String[] args)
launch();


public void onButtonAnswerClick()
String message = tfMessage.getText();

if (message.equals(""))
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please enter your message!!");
alert.show();
return;


if (replyToQuestion(message, SEND_CHANNEL))
tfMessage.clear();
else
handleServiceError("Service Error", "Could not send the message to the service");



private void handleServiceError(String errorTitle, String errorText)
Alert error = new Alert(Alert.AlertType.ERROR);
error.setTitle(errorTitle);
error.setContentText(errorText);


private void updateLV()
lvMessage.getItems().clear();
lvMessage.setItems(observableList);


private void initService(String targetDestination, String destinationType) JMSException e)
e.printStackTrace();



private boolean replyToQuestion(String message, String sendDestination)
try
initService(sendDestination, DESTINATION_TYPE);

// for sending messages
messageProducer = session.createProducer(destination);

// create a text message
Message msg = session.createTextMessage(message);

msg.setJMSMessageID("222");
System.out.println(msg.getJMSMessageID());

// send the message
messageProducer.send(msg);

//questionList.add(message);
updateLV();
return true;
catch (JMSException e)
e.printStackTrace();
return false;



private void getMessage(String receiveDestination)
try
initService(receiveDestination, DESTINATION_TYPE);

// this is needed to start receiving messages
connection.start();

// for receiving messages
messageConsumer = session.createConsumer(destination);
MessageListener listener = message ->
try
observableList.add(((TextMessage)message).getText());
catch (JMSException e)
e.printStackTrace();

;

messageConsumer.setMessageListener(listener);
catch (JMSException e)
e.printStackTrace();





And my sender:



 public class User extends Application implements MessageListener 
private static List<String> questions;
private final String DESTINATION_TYPE = "queue";
private final String RECEIVE_CHANNEL = "answerDestination";
private final String SEND_CHANNEL = "askDestination";
private String requestId;
private MessageConsumer messageConsumer;
private MessageProducer messageProducer;
private Session session;
private Destination destination;
private Connection connection;

@FXML
public Button btnSend;

@FXML
public TextField tfMessage;

@FXML
public ListView lvMessage;

@Override
public void start(Stage stage) throws IOException
Parent root = FXMLLoader.load(getClass().getResource("userUI.fxml"));
stage.setTitle("Sender");
stage.setScene(new Scene(root, 640, 480));
stage.setResizable(false);
stage.show();


@Override
public void init() throws Exception
super.init();
btnSend = new Button();
tfMessage = new TextField();
lvMessage = new ListView();
questions = new ArrayList<>();
initService(RECEIVE_CHANNEL, DESTINATION_TYPE);
getAnswer(RECEIVE_CHANNEL);


public static void main(String[] args)
launch(args);


public void onButtonSendClick(javafx.event.ActionEvent actionEvent)
String message = tfMessage.getText();

if (message.equals(""))
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please enter your question!!");
alert.show();
return;


if (sendQuestion(message, SEND_CHANNEL))
tfMessage.clear();
else
handleServiceError("Service Error", "Could not send the message tot the service");



private void handleServiceError(String errorTitle, String errorText)
Alert error = new Alert(Alert.AlertType.ERROR);
error.setTitle(errorTitle);
error.setContentText(errorText);


private void updateLV()
lvMessage.getItems().clear();
lvMessage.getItems().addAll(questions);


private void initService(String targetDestination, String destinationType)
try
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");

// connect to the Destination called “myFirstChannel”
// queue or topic: “queue.myFirstDestination” or “topic.myFirstDestination”
props.put((destinationType + "." + targetDestination), targetDestination);
Context jndiContext = new InitialContext(props);
ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");

// to connect to the JMS
connection = connectionFactory.createConnection();
// session for creating consumers
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// connect to the receiver destination
//reference to a queue/topic destination
destination = (Destination) jndiContext.lookup(targetDestination);
catch (NamingException

private boolean sendQuestion(String message, String sendDestination)
try
initService(sendDestination, DESTINATION_TYPE);

// for sending messages
messageProducer = session.createProducer(destination);

// create a text message
Message msg = session.createTextMessage(message);

msg.setJMSMessageID("111");
System.out.println(msg.getJMSMessageID());

// send the message
messageProducer.send(msg);

//questionList.add(message);
updateLV();
return true;
catch (JMSException e)
e.printStackTrace();
return false;



private void getAnswer(String receiveDestination)
try
initService(receiveDestination, DESTINATION_TYPE);

// for receiving messages
messageConsumer = session.createConsumer(destination);
messageConsumer.setMessageListener(this);


// this is needed to start receiving messages
connection.start();
catch (JMSException e)
e.printStackTrace();



@Override
public void onMessage(Message message)
try
questions.add(((TextMessage)message).getText());
requestId = message.getJMSMessageID();
System.out.println(requestId);
updateLV();
catch (JMSException e)
e.printStackTrace();





The FXML of the receiver:



 <GridPane hgap="10" prefHeight="400.0" prefWidth="600.0" vgap="10" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Administrator">
<padding>
<Insets bottom="10" left="10" right="10" top="10" />
</padding>
<Label text="Current question:" textFill="cornflowerblue" GridPane.columnIndex="0" GridPane.rowIndex="0">
<font>
<Font name="System Bold" size="15.0" />
</font>
</Label>
<ListView fx:id="lvMessage" prefWidth="600" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="1">

</ListView>

<HBox spacing="10" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="2">
<TextField fx:id="tfMessage" prefHeight="61.0" prefWidth="504.0" promptText="Type your answer here...">
<font>
<Font size="15.0" />
</font>
</TextField>
<Button fx:id="btnSend" onAction="#onButtonAnswerClick" prefHeight="61.0" prefWidth="88.0" text="Send">
</Button>
</HBox>
<columnConstraints>
<ColumnConstraints />
<ColumnConstraints />
</columnConstraints>
<rowConstraints>
<RowConstraints />
<RowConstraints />
<RowConstraints />
</rowConstraints>
</GridPane>


After the receiver received the message, the event is raised so I expected the ListView to be updated with the new message. However, no element was added to the ObservableList => no update in the ListView.



So, I would like to ask if what I did is wrong or correct?










share|improve this question
























  • @kleopatra Sorry for this inconvenience. I've updated the problem

    – Huy Phạm
    Mar 25 at 11:52






  • 1





    looks like the listView you are setting the items to is not the listView you are injecting via fxml: either have a @fxml annotation on the field or instantiate it manually, not both. Same for all your controls ..

    – kleopatra
    Mar 25 at 11:56












  • @kleopatra I tried to instantiate it manually, but I still got the same problem! Right after that, I tried with fxml annotation, but I got a compile error (NullPointerException for the ListView)

    – Huy Phạm
    Mar 25 at 12:07

















0















I am making two simple JMS application with JavaFx (one for sender and the other one is receiver).



But, I could not refresh the GUI of the receiver with the new arriving message from the sender.



From debugging, I noticed that the receiver received the message from the server, but the receiver could not add it to my ObservableList (which, of course, resulted in no refreshing in the GUI of the ListView).



I looked up on the internet with onMessage event, and override it (to add an item to the ObservableList there), but it is not working. After the event is raised, no element was added to the ObservableList.



This is my receiver:



public class Administrator extends Application 
private ObservableList<String> observableList;
private final String DESTINATION_TYPE = "queue";
private final String RECEIVE_CHANNEL = "askDestination";
private final String SEND_CHANNEL = "answerDestination";
private MessageConsumer messageConsumer;
private MessageProducer messageProducer;
private Session session;
private Destination destination;
private Connection connection;

@FXML
public TextField tfMessage;

@FXML
public ListView<String> lvMessage;

@FXML
public Button btnSend;

@Override
public void start(Stage stage) throws IOException
Parent root = FXMLLoader.load(getClass().getResource("administratorUI.fxml"));
stage.setTitle("Administrator");
stage.setScene(new Scene(root, 640, 480));
stage.setResizable(false);
stage.show();


@Override
public void init() throws Exception
super.init();
lvMessage = new ListView<>();
tfMessage = new TextField();
//questionList = new ArrayList<>();
observableList = FXCollections.observableArrayList();
lvMessage.setItems(observableList);
initService(RECEIVE_CHANNEL, DESTINATION_TYPE);
getMessage(RECEIVE_CHANNEL);
//Platform.runLater(this::updateLV);


public static void main(String[] args)
launch();


public void onButtonAnswerClick()
String message = tfMessage.getText();

if (message.equals(""))
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please enter your message!!");
alert.show();
return;


if (replyToQuestion(message, SEND_CHANNEL))
tfMessage.clear();
else
handleServiceError("Service Error", "Could not send the message to the service");



private void handleServiceError(String errorTitle, String errorText)
Alert error = new Alert(Alert.AlertType.ERROR);
error.setTitle(errorTitle);
error.setContentText(errorText);


private void updateLV()
lvMessage.getItems().clear();
lvMessage.setItems(observableList);


private void initService(String targetDestination, String destinationType) JMSException e)
e.printStackTrace();



private boolean replyToQuestion(String message, String sendDestination)
try
initService(sendDestination, DESTINATION_TYPE);

// for sending messages
messageProducer = session.createProducer(destination);

// create a text message
Message msg = session.createTextMessage(message);

msg.setJMSMessageID("222");
System.out.println(msg.getJMSMessageID());

// send the message
messageProducer.send(msg);

//questionList.add(message);
updateLV();
return true;
catch (JMSException e)
e.printStackTrace();
return false;



private void getMessage(String receiveDestination)
try
initService(receiveDestination, DESTINATION_TYPE);

// this is needed to start receiving messages
connection.start();

// for receiving messages
messageConsumer = session.createConsumer(destination);
MessageListener listener = message ->
try
observableList.add(((TextMessage)message).getText());
catch (JMSException e)
e.printStackTrace();

;

messageConsumer.setMessageListener(listener);
catch (JMSException e)
e.printStackTrace();





And my sender:



 public class User extends Application implements MessageListener 
private static List<String> questions;
private final String DESTINATION_TYPE = "queue";
private final String RECEIVE_CHANNEL = "answerDestination";
private final String SEND_CHANNEL = "askDestination";
private String requestId;
private MessageConsumer messageConsumer;
private MessageProducer messageProducer;
private Session session;
private Destination destination;
private Connection connection;

@FXML
public Button btnSend;

@FXML
public TextField tfMessage;

@FXML
public ListView lvMessage;

@Override
public void start(Stage stage) throws IOException
Parent root = FXMLLoader.load(getClass().getResource("userUI.fxml"));
stage.setTitle("Sender");
stage.setScene(new Scene(root, 640, 480));
stage.setResizable(false);
stage.show();


@Override
public void init() throws Exception
super.init();
btnSend = new Button();
tfMessage = new TextField();
lvMessage = new ListView();
questions = new ArrayList<>();
initService(RECEIVE_CHANNEL, DESTINATION_TYPE);
getAnswer(RECEIVE_CHANNEL);


public static void main(String[] args)
launch(args);


public void onButtonSendClick(javafx.event.ActionEvent actionEvent)
String message = tfMessage.getText();

if (message.equals(""))
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please enter your question!!");
alert.show();
return;


if (sendQuestion(message, SEND_CHANNEL))
tfMessage.clear();
else
handleServiceError("Service Error", "Could not send the message tot the service");



private void handleServiceError(String errorTitle, String errorText)
Alert error = new Alert(Alert.AlertType.ERROR);
error.setTitle(errorTitle);
error.setContentText(errorText);


private void updateLV()
lvMessage.getItems().clear();
lvMessage.getItems().addAll(questions);


private void initService(String targetDestination, String destinationType)
try
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");

// connect to the Destination called “myFirstChannel”
// queue or topic: “queue.myFirstDestination” or “topic.myFirstDestination”
props.put((destinationType + "." + targetDestination), targetDestination);
Context jndiContext = new InitialContext(props);
ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");

// to connect to the JMS
connection = connectionFactory.createConnection();
// session for creating consumers
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// connect to the receiver destination
//reference to a queue/topic destination
destination = (Destination) jndiContext.lookup(targetDestination);
catch (NamingException

private boolean sendQuestion(String message, String sendDestination)
try
initService(sendDestination, DESTINATION_TYPE);

// for sending messages
messageProducer = session.createProducer(destination);

// create a text message
Message msg = session.createTextMessage(message);

msg.setJMSMessageID("111");
System.out.println(msg.getJMSMessageID());

// send the message
messageProducer.send(msg);

//questionList.add(message);
updateLV();
return true;
catch (JMSException e)
e.printStackTrace();
return false;



private void getAnswer(String receiveDestination)
try
initService(receiveDestination, DESTINATION_TYPE);

// for receiving messages
messageConsumer = session.createConsumer(destination);
messageConsumer.setMessageListener(this);


// this is needed to start receiving messages
connection.start();
catch (JMSException e)
e.printStackTrace();



@Override
public void onMessage(Message message)
try
questions.add(((TextMessage)message).getText());
requestId = message.getJMSMessageID();
System.out.println(requestId);
updateLV();
catch (JMSException e)
e.printStackTrace();





The FXML of the receiver:



 <GridPane hgap="10" prefHeight="400.0" prefWidth="600.0" vgap="10" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Administrator">
<padding>
<Insets bottom="10" left="10" right="10" top="10" />
</padding>
<Label text="Current question:" textFill="cornflowerblue" GridPane.columnIndex="0" GridPane.rowIndex="0">
<font>
<Font name="System Bold" size="15.0" />
</font>
</Label>
<ListView fx:id="lvMessage" prefWidth="600" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="1">

</ListView>

<HBox spacing="10" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="2">
<TextField fx:id="tfMessage" prefHeight="61.0" prefWidth="504.0" promptText="Type your answer here...">
<font>
<Font size="15.0" />
</font>
</TextField>
<Button fx:id="btnSend" onAction="#onButtonAnswerClick" prefHeight="61.0" prefWidth="88.0" text="Send">
</Button>
</HBox>
<columnConstraints>
<ColumnConstraints />
<ColumnConstraints />
</columnConstraints>
<rowConstraints>
<RowConstraints />
<RowConstraints />
<RowConstraints />
</rowConstraints>
</GridPane>


After the receiver received the message, the event is raised so I expected the ListView to be updated with the new message. However, no element was added to the ObservableList => no update in the ListView.



So, I would like to ask if what I did is wrong or correct?










share|improve this question
























  • @kleopatra Sorry for this inconvenience. I've updated the problem

    – Huy Phạm
    Mar 25 at 11:52






  • 1





    looks like the listView you are setting the items to is not the listView you are injecting via fxml: either have a @fxml annotation on the field or instantiate it manually, not both. Same for all your controls ..

    – kleopatra
    Mar 25 at 11:56












  • @kleopatra I tried to instantiate it manually, but I still got the same problem! Right after that, I tried with fxml annotation, but I got a compile error (NullPointerException for the ListView)

    – Huy Phạm
    Mar 25 at 12:07













0












0








0








I am making two simple JMS application with JavaFx (one for sender and the other one is receiver).



But, I could not refresh the GUI of the receiver with the new arriving message from the sender.



From debugging, I noticed that the receiver received the message from the server, but the receiver could not add it to my ObservableList (which, of course, resulted in no refreshing in the GUI of the ListView).



I looked up on the internet with onMessage event, and override it (to add an item to the ObservableList there), but it is not working. After the event is raised, no element was added to the ObservableList.



This is my receiver:



public class Administrator extends Application 
private ObservableList<String> observableList;
private final String DESTINATION_TYPE = "queue";
private final String RECEIVE_CHANNEL = "askDestination";
private final String SEND_CHANNEL = "answerDestination";
private MessageConsumer messageConsumer;
private MessageProducer messageProducer;
private Session session;
private Destination destination;
private Connection connection;

@FXML
public TextField tfMessage;

@FXML
public ListView<String> lvMessage;

@FXML
public Button btnSend;

@Override
public void start(Stage stage) throws IOException
Parent root = FXMLLoader.load(getClass().getResource("administratorUI.fxml"));
stage.setTitle("Administrator");
stage.setScene(new Scene(root, 640, 480));
stage.setResizable(false);
stage.show();


@Override
public void init() throws Exception
super.init();
lvMessage = new ListView<>();
tfMessage = new TextField();
//questionList = new ArrayList<>();
observableList = FXCollections.observableArrayList();
lvMessage.setItems(observableList);
initService(RECEIVE_CHANNEL, DESTINATION_TYPE);
getMessage(RECEIVE_CHANNEL);
//Platform.runLater(this::updateLV);


public static void main(String[] args)
launch();


public void onButtonAnswerClick()
String message = tfMessage.getText();

if (message.equals(""))
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please enter your message!!");
alert.show();
return;


if (replyToQuestion(message, SEND_CHANNEL))
tfMessage.clear();
else
handleServiceError("Service Error", "Could not send the message to the service");



private void handleServiceError(String errorTitle, String errorText)
Alert error = new Alert(Alert.AlertType.ERROR);
error.setTitle(errorTitle);
error.setContentText(errorText);


private void updateLV()
lvMessage.getItems().clear();
lvMessage.setItems(observableList);


private void initService(String targetDestination, String destinationType) JMSException e)
e.printStackTrace();



private boolean replyToQuestion(String message, String sendDestination)
try
initService(sendDestination, DESTINATION_TYPE);

// for sending messages
messageProducer = session.createProducer(destination);

// create a text message
Message msg = session.createTextMessage(message);

msg.setJMSMessageID("222");
System.out.println(msg.getJMSMessageID());

// send the message
messageProducer.send(msg);

//questionList.add(message);
updateLV();
return true;
catch (JMSException e)
e.printStackTrace();
return false;



private void getMessage(String receiveDestination)
try
initService(receiveDestination, DESTINATION_TYPE);

// this is needed to start receiving messages
connection.start();

// for receiving messages
messageConsumer = session.createConsumer(destination);
MessageListener listener = message ->
try
observableList.add(((TextMessage)message).getText());
catch (JMSException e)
e.printStackTrace();

;

messageConsumer.setMessageListener(listener);
catch (JMSException e)
e.printStackTrace();





And my sender:



 public class User extends Application implements MessageListener 
private static List<String> questions;
private final String DESTINATION_TYPE = "queue";
private final String RECEIVE_CHANNEL = "answerDestination";
private final String SEND_CHANNEL = "askDestination";
private String requestId;
private MessageConsumer messageConsumer;
private MessageProducer messageProducer;
private Session session;
private Destination destination;
private Connection connection;

@FXML
public Button btnSend;

@FXML
public TextField tfMessage;

@FXML
public ListView lvMessage;

@Override
public void start(Stage stage) throws IOException
Parent root = FXMLLoader.load(getClass().getResource("userUI.fxml"));
stage.setTitle("Sender");
stage.setScene(new Scene(root, 640, 480));
stage.setResizable(false);
stage.show();


@Override
public void init() throws Exception
super.init();
btnSend = new Button();
tfMessage = new TextField();
lvMessage = new ListView();
questions = new ArrayList<>();
initService(RECEIVE_CHANNEL, DESTINATION_TYPE);
getAnswer(RECEIVE_CHANNEL);


public static void main(String[] args)
launch(args);


public void onButtonSendClick(javafx.event.ActionEvent actionEvent)
String message = tfMessage.getText();

if (message.equals(""))
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please enter your question!!");
alert.show();
return;


if (sendQuestion(message, SEND_CHANNEL))
tfMessage.clear();
else
handleServiceError("Service Error", "Could not send the message tot the service");



private void handleServiceError(String errorTitle, String errorText)
Alert error = new Alert(Alert.AlertType.ERROR);
error.setTitle(errorTitle);
error.setContentText(errorText);


private void updateLV()
lvMessage.getItems().clear();
lvMessage.getItems().addAll(questions);


private void initService(String targetDestination, String destinationType)
try
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");

// connect to the Destination called “myFirstChannel”
// queue or topic: “queue.myFirstDestination” or “topic.myFirstDestination”
props.put((destinationType + "." + targetDestination), targetDestination);
Context jndiContext = new InitialContext(props);
ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");

// to connect to the JMS
connection = connectionFactory.createConnection();
// session for creating consumers
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// connect to the receiver destination
//reference to a queue/topic destination
destination = (Destination) jndiContext.lookup(targetDestination);
catch (NamingException

private boolean sendQuestion(String message, String sendDestination)
try
initService(sendDestination, DESTINATION_TYPE);

// for sending messages
messageProducer = session.createProducer(destination);

// create a text message
Message msg = session.createTextMessage(message);

msg.setJMSMessageID("111");
System.out.println(msg.getJMSMessageID());

// send the message
messageProducer.send(msg);

//questionList.add(message);
updateLV();
return true;
catch (JMSException e)
e.printStackTrace();
return false;



private void getAnswer(String receiveDestination)
try
initService(receiveDestination, DESTINATION_TYPE);

// for receiving messages
messageConsumer = session.createConsumer(destination);
messageConsumer.setMessageListener(this);


// this is needed to start receiving messages
connection.start();
catch (JMSException e)
e.printStackTrace();



@Override
public void onMessage(Message message)
try
questions.add(((TextMessage)message).getText());
requestId = message.getJMSMessageID();
System.out.println(requestId);
updateLV();
catch (JMSException e)
e.printStackTrace();





The FXML of the receiver:



 <GridPane hgap="10" prefHeight="400.0" prefWidth="600.0" vgap="10" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Administrator">
<padding>
<Insets bottom="10" left="10" right="10" top="10" />
</padding>
<Label text="Current question:" textFill="cornflowerblue" GridPane.columnIndex="0" GridPane.rowIndex="0">
<font>
<Font name="System Bold" size="15.0" />
</font>
</Label>
<ListView fx:id="lvMessage" prefWidth="600" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="1">

</ListView>

<HBox spacing="10" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="2">
<TextField fx:id="tfMessage" prefHeight="61.0" prefWidth="504.0" promptText="Type your answer here...">
<font>
<Font size="15.0" />
</font>
</TextField>
<Button fx:id="btnSend" onAction="#onButtonAnswerClick" prefHeight="61.0" prefWidth="88.0" text="Send">
</Button>
</HBox>
<columnConstraints>
<ColumnConstraints />
<ColumnConstraints />
</columnConstraints>
<rowConstraints>
<RowConstraints />
<RowConstraints />
<RowConstraints />
</rowConstraints>
</GridPane>


After the receiver received the message, the event is raised so I expected the ListView to be updated with the new message. However, no element was added to the ObservableList => no update in the ListView.



So, I would like to ask if what I did is wrong or correct?










share|improve this question
















I am making two simple JMS application with JavaFx (one for sender and the other one is receiver).



But, I could not refresh the GUI of the receiver with the new arriving message from the sender.



From debugging, I noticed that the receiver received the message from the server, but the receiver could not add it to my ObservableList (which, of course, resulted in no refreshing in the GUI of the ListView).



I looked up on the internet with onMessage event, and override it (to add an item to the ObservableList there), but it is not working. After the event is raised, no element was added to the ObservableList.



This is my receiver:



public class Administrator extends Application 
private ObservableList<String> observableList;
private final String DESTINATION_TYPE = "queue";
private final String RECEIVE_CHANNEL = "askDestination";
private final String SEND_CHANNEL = "answerDestination";
private MessageConsumer messageConsumer;
private MessageProducer messageProducer;
private Session session;
private Destination destination;
private Connection connection;

@FXML
public TextField tfMessage;

@FXML
public ListView<String> lvMessage;

@FXML
public Button btnSend;

@Override
public void start(Stage stage) throws IOException
Parent root = FXMLLoader.load(getClass().getResource("administratorUI.fxml"));
stage.setTitle("Administrator");
stage.setScene(new Scene(root, 640, 480));
stage.setResizable(false);
stage.show();


@Override
public void init() throws Exception
super.init();
lvMessage = new ListView<>();
tfMessage = new TextField();
//questionList = new ArrayList<>();
observableList = FXCollections.observableArrayList();
lvMessage.setItems(observableList);
initService(RECEIVE_CHANNEL, DESTINATION_TYPE);
getMessage(RECEIVE_CHANNEL);
//Platform.runLater(this::updateLV);


public static void main(String[] args)
launch();


public void onButtonAnswerClick()
String message = tfMessage.getText();

if (message.equals(""))
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please enter your message!!");
alert.show();
return;


if (replyToQuestion(message, SEND_CHANNEL))
tfMessage.clear();
else
handleServiceError("Service Error", "Could not send the message to the service");



private void handleServiceError(String errorTitle, String errorText)
Alert error = new Alert(Alert.AlertType.ERROR);
error.setTitle(errorTitle);
error.setContentText(errorText);


private void updateLV()
lvMessage.getItems().clear();
lvMessage.setItems(observableList);


private void initService(String targetDestination, String destinationType) JMSException e)
e.printStackTrace();



private boolean replyToQuestion(String message, String sendDestination)
try
initService(sendDestination, DESTINATION_TYPE);

// for sending messages
messageProducer = session.createProducer(destination);

// create a text message
Message msg = session.createTextMessage(message);

msg.setJMSMessageID("222");
System.out.println(msg.getJMSMessageID());

// send the message
messageProducer.send(msg);

//questionList.add(message);
updateLV();
return true;
catch (JMSException e)
e.printStackTrace();
return false;



private void getMessage(String receiveDestination)
try
initService(receiveDestination, DESTINATION_TYPE);

// this is needed to start receiving messages
connection.start();

// for receiving messages
messageConsumer = session.createConsumer(destination);
MessageListener listener = message ->
try
observableList.add(((TextMessage)message).getText());
catch (JMSException e)
e.printStackTrace();

;

messageConsumer.setMessageListener(listener);
catch (JMSException e)
e.printStackTrace();





And my sender:



 public class User extends Application implements MessageListener 
private static List<String> questions;
private final String DESTINATION_TYPE = "queue";
private final String RECEIVE_CHANNEL = "answerDestination";
private final String SEND_CHANNEL = "askDestination";
private String requestId;
private MessageConsumer messageConsumer;
private MessageProducer messageProducer;
private Session session;
private Destination destination;
private Connection connection;

@FXML
public Button btnSend;

@FXML
public TextField tfMessage;

@FXML
public ListView lvMessage;

@Override
public void start(Stage stage) throws IOException
Parent root = FXMLLoader.load(getClass().getResource("userUI.fxml"));
stage.setTitle("Sender");
stage.setScene(new Scene(root, 640, 480));
stage.setResizable(false);
stage.show();


@Override
public void init() throws Exception
super.init();
btnSend = new Button();
tfMessage = new TextField();
lvMessage = new ListView();
questions = new ArrayList<>();
initService(RECEIVE_CHANNEL, DESTINATION_TYPE);
getAnswer(RECEIVE_CHANNEL);


public static void main(String[] args)
launch(args);


public void onButtonSendClick(javafx.event.ActionEvent actionEvent)
String message = tfMessage.getText();

if (message.equals(""))
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please enter your question!!");
alert.show();
return;


if (sendQuestion(message, SEND_CHANNEL))
tfMessage.clear();
else
handleServiceError("Service Error", "Could not send the message tot the service");



private void handleServiceError(String errorTitle, String errorText)
Alert error = new Alert(Alert.AlertType.ERROR);
error.setTitle(errorTitle);
error.setContentText(errorText);


private void updateLV()
lvMessage.getItems().clear();
lvMessage.getItems().addAll(questions);


private void initService(String targetDestination, String destinationType)
try
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61616");

// connect to the Destination called “myFirstChannel”
// queue or topic: “queue.myFirstDestination” or “topic.myFirstDestination”
props.put((destinationType + "." + targetDestination), targetDestination);
Context jndiContext = new InitialContext(props);
ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");

// to connect to the JMS
connection = connectionFactory.createConnection();
// session for creating consumers
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// connect to the receiver destination
//reference to a queue/topic destination
destination = (Destination) jndiContext.lookup(targetDestination);
catch (NamingException

private boolean sendQuestion(String message, String sendDestination)
try
initService(sendDestination, DESTINATION_TYPE);

// for sending messages
messageProducer = session.createProducer(destination);

// create a text message
Message msg = session.createTextMessage(message);

msg.setJMSMessageID("111");
System.out.println(msg.getJMSMessageID());

// send the message
messageProducer.send(msg);

//questionList.add(message);
updateLV();
return true;
catch (JMSException e)
e.printStackTrace();
return false;



private void getAnswer(String receiveDestination)
try
initService(receiveDestination, DESTINATION_TYPE);

// for receiving messages
messageConsumer = session.createConsumer(destination);
messageConsumer.setMessageListener(this);


// this is needed to start receiving messages
connection.start();
catch (JMSException e)
e.printStackTrace();



@Override
public void onMessage(Message message)
try
questions.add(((TextMessage)message).getText());
requestId = message.getJMSMessageID();
System.out.println(requestId);
updateLV();
catch (JMSException e)
e.printStackTrace();





The FXML of the receiver:



 <GridPane hgap="10" prefHeight="400.0" prefWidth="600.0" vgap="10" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Administrator">
<padding>
<Insets bottom="10" left="10" right="10" top="10" />
</padding>
<Label text="Current question:" textFill="cornflowerblue" GridPane.columnIndex="0" GridPane.rowIndex="0">
<font>
<Font name="System Bold" size="15.0" />
</font>
</Label>
<ListView fx:id="lvMessage" prefWidth="600" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="1">

</ListView>

<HBox spacing="10" GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="2">
<TextField fx:id="tfMessage" prefHeight="61.0" prefWidth="504.0" promptText="Type your answer here...">
<font>
<Font size="15.0" />
</font>
</TextField>
<Button fx:id="btnSend" onAction="#onButtonAnswerClick" prefHeight="61.0" prefWidth="88.0" text="Send">
</Button>
</HBox>
<columnConstraints>
<ColumnConstraints />
<ColumnConstraints />
</columnConstraints>
<rowConstraints>
<RowConstraints />
<RowConstraints />
<RowConstraints />
</rowConstraints>
</GridPane>


After the receiver received the message, the event is raised so I expected the ListView to be updated with the new message. However, no element was added to the ObservableList => no update in the ListView.



So, I would like to ask if what I did is wrong or correct?







java javafx jms






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 11:52







Huy Phạm

















asked Mar 25 at 10:17









Huy PhạmHuy Phạm

13 bronze badges




13 bronze badges












  • @kleopatra Sorry for this inconvenience. I've updated the problem

    – Huy Phạm
    Mar 25 at 11:52






  • 1





    looks like the listView you are setting the items to is not the listView you are injecting via fxml: either have a @fxml annotation on the field or instantiate it manually, not both. Same for all your controls ..

    – kleopatra
    Mar 25 at 11:56












  • @kleopatra I tried to instantiate it manually, but I still got the same problem! Right after that, I tried with fxml annotation, but I got a compile error (NullPointerException for the ListView)

    – Huy Phạm
    Mar 25 at 12:07

















  • @kleopatra Sorry for this inconvenience. I've updated the problem

    – Huy Phạm
    Mar 25 at 11:52






  • 1





    looks like the listView you are setting the items to is not the listView you are injecting via fxml: either have a @fxml annotation on the field or instantiate it manually, not both. Same for all your controls ..

    – kleopatra
    Mar 25 at 11:56












  • @kleopatra I tried to instantiate it manually, but I still got the same problem! Right after that, I tried with fxml annotation, but I got a compile error (NullPointerException for the ListView)

    – Huy Phạm
    Mar 25 at 12:07
















@kleopatra Sorry for this inconvenience. I've updated the problem

– Huy Phạm
Mar 25 at 11:52





@kleopatra Sorry for this inconvenience. I've updated the problem

– Huy Phạm
Mar 25 at 11:52




1




1





looks like the listView you are setting the items to is not the listView you are injecting via fxml: either have a @fxml annotation on the field or instantiate it manually, not both. Same for all your controls ..

– kleopatra
Mar 25 at 11:56






looks like the listView you are setting the items to is not the listView you are injecting via fxml: either have a @fxml annotation on the field or instantiate it manually, not both. Same for all your controls ..

– kleopatra
Mar 25 at 11:56














@kleopatra I tried to instantiate it manually, but I still got the same problem! Right after that, I tried with fxml annotation, but I got a compile error (NullPointerException for the ListView)

– Huy Phạm
Mar 25 at 12:07





@kleopatra I tried to instantiate it manually, but I still got the same problem! Right after that, I tried with fxml annotation, but I got a compile error (NullPointerException for the ListView)

– Huy Phạm
Mar 25 at 12:07












1 Answer
1






active

oldest

votes


















0














Turn out that I was updating the ListView on the wrong thread. For those who is still interesting in the answer, I used: Platform.runLater() and registered the event listener in the start method (before stage.show())






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55335526%2fhow-to-add-item-to-observablelist-in-onmessage-event-listener%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Turn out that I was updating the ListView on the wrong thread. For those who is still interesting in the answer, I used: Platform.runLater() and registered the event listener in the start method (before stage.show())






    share|improve this answer



























      0














      Turn out that I was updating the ListView on the wrong thread. For those who is still interesting in the answer, I used: Platform.runLater() and registered the event listener in the start method (before stage.show())






      share|improve this answer

























        0












        0








        0







        Turn out that I was updating the ListView on the wrong thread. For those who is still interesting in the answer, I used: Platform.runLater() and registered the event listener in the start method (before stage.show())






        share|improve this answer













        Turn out that I was updating the ListView on the wrong thread. For those who is still interesting in the answer, I used: Platform.runLater() and registered the event listener in the start method (before stage.show())







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 18:22









        Huy PhạmHuy Phạm

        13 bronze badges




        13 bronze badges





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55335526%2fhow-to-add-item-to-observablelist-in-onmessage-event-listener%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해