com.cerebro.provevaadin.ChatOnGame.java Source code

Java tutorial

Introduction

Here is the source code for com.cerebro.provevaadin.ChatOnGame.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cerebro.provevaadin;

import com.vaadin.event.ShortcutAction;
import com.vaadin.external.org.slf4j.Logger;
import com.vaadin.external.org.slf4j.LoggerFactory;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

/**
 *
 * @author matteo
 */
public class ChatOnGame extends VerticalLayout implements BroadcasterOnGame.BroadcastListener {

    String FROM = "onGame";

    Logger logger = LoggerFactory.getLogger(ChatOnGame.class);
    VerticalLayout messages = new VerticalLayout();

    public ChatOnGame(User user) {
        if (user.getUltimoLuogoPG() != null) {
            logger.info("Luogo: " + user.getUltimoLuogoPG());
        } else {
            logger.info("Nessun luogo selezionato");
        }
        Panel messagesPanel = new Panel();
        messagesPanel.setSizeFull();
        messagesPanel.setContent(messages);
        this.addComponent(messagesPanel);
        this.setExpandRatio(messagesPanel, 1.0f);

        HorizontalLayout sendBar = new HorizontalLayout();
        sendBar.setWidth("100%");
        final TextField input = new TextField();
        input.setWidth("100%");
        sendBar.addComponent(input);
        sendBar.setExpandRatio(input, 1.0f);

        Button send = new Button("Send");
        send.setClickShortcut(ShortcutAction.KeyCode.ENTER, null);
        send.addClickListener((Button.ClickEvent event) -> {
            logger.info("Invio del messaggio al server");
            BroadcasterOnGame.broadcast(input.getValue(), FROM);
            input.setValue("");
        });
        sendBar.addComponent(send);
        this.addComponent(sendBar);

        BroadcasterOnGame.register(this);
    }

    @Override
    public void receiveBroadcast(String from, String message) {
        UI.getCurrent().access(new Runnable() {
            @Override
            public void run() {
                if (from.equals(FROM)) {
                    messages.addComponent(new Label(message));
                }
            }

        });
    }

}