JAVAFX ListView chatting

前端 未结 1 1434
一生所求
一生所求 2020-12-12 07:07

I need to insert values in list view in one by one like chatting. now my code is

@FXML
private ListView messageList;    

private ObservableLi         


        
1条回答
  •  醉话见心
    2020-12-12 07:28

    This may be similar to what you are asking.

    Main:

    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    
    public class ChatApp 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);
        }
    
    }
    

    Controller:

    import java.net.URL;
    import java.util.ResourceBundle;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.ListView;
    import javafx.scene.control.TextField;
    
    public class FXMLDocumentController implements Initializable {
    
        @FXML private ListView lvChatWindow;
        @FXML private TextField tfUser1, tfUser2;
    
        ObservableList chatMessages = FXCollections.observableArrayList();//create observablelist for listview
    
    
        //Method use to handle button press that submits the 1st user's text to the listview.
        @FXML
        private void handleUser1SubmitMessage(ActionEvent event) {
            chatMessages.add("User 1: " + tfUser1.getText());//get 1st user's text from his/her textfield and add message to observablelist
            tfUser1.setText("");//clear 1st user's textfield
        }
    
        //Method use to handle button press that submits the 2nd user's text to the listview.
        @FXML
        private void handleUser2SubmitMessage(ActionEvent event) {
            chatMessages.add("User 2: " + tfUser2.getText());//get 2nd user's text from his/her textfield and add message to observablelist
            tfUser2.setText("");//clear 2nd user's textfield
        }
    
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            // TODO
            lvChatWindow.setItems(chatMessages);//attach the observablelist to the listview
        }      
    }
    

    FXML:

    
    
    
    
    
    
    
    
    
        
            

    This app simulates two different users sending messages to one listview. Similar to a chat. More comments in Controller

    0 讨论(0)
提交回复
热议问题