Package server

Source Code of server.ServerFrame

package server;

import java.awt.Font;
import java.awt.Image;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JScrollPane;

import CustomEvents.CustomEventSource;
import CustomEvents.ICustomEventListener;

import server.CustomEvents.ServerConnectEvent;
import server.CustomEvents.ServerDisconnectEvent;

import chatown.Client;
import chatown.Globals;

import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Dimension;

/**
*
* @author MK
*/
public class ServerFrame extends javax.swing.JFrame {

  private static final long serialVersionUID = -7377951246301373656L;
  private ClientsTableModel clientsTM;
    private Random generator = new Random();
    private SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
    private Boolean isTableBottom = false;
    private CustomEventSource[] _events = new CustomEventSource[2];
   
    /**
     * Creates new form ServerFrame
     */
    public ServerFrame() {
      loadIcon();
      setMinimumSize(new Dimension(600, 400));
   
        init_look();
        initComponents();
       
        // port
    Image image = getToolkit().getImage(getClass().getResource("/resources/exclamation.png"));
    Image scaledImage = image.getScaledInstance(20, 20, Image.SCALE_DEFAULT)
    lblPort.setIcon(new ImageIcon(scaledImage));
       
    jTFPort.getDocument().addDocumentListener(new DocumentListener() {
      public void changedUpdate(DocumentEvent e) { // text was changed
        PortChanged();
      }
      public void removeUpdate(DocumentEvent e) { // text was deleted
        PortChanged();
      }
      public void insertUpdate(DocumentEvent e) { // text was inserted
        PortChanged();
      }
    });
    jTFPort.setText(Integer.toString(Globals.DEFAULT_SERVER_PORT));
       
        // clients table
        clientsTM = new ClientsTableModel();
        jTClients.setModel(clientsTM);
               
        clientsTM.addColumn((Object)"IP");
        clientsTM.addColumn((Object)"nickname")
        clientsTM.addColumn((Object)"ID");
        clientsTM.addColumn((Object)"# Open msgs");
        clientsTM.addColumn((Object)"last communication time");
       
        //table scroll
        Image imageLock = getToolkit().getImage(getClass().getResource("/resources/lock_open.png"));  
    lblTableLock.setIcon(new ImageIcon(imageLock.getScaledInstance(20, 27, Image.SCALE_DEFAULT)));
   
    // set events
    _events[Globals.SERVER_CONNECT] = new CustomEventSource();
    _events[Globals.SERVER_DISCONNECT] = new CustomEventSource();
    }
   
  private void loadIcon() {   
    Image img = getToolkit().getImage(getClass().getResource("/resources/chat.png"));
    this.setIconImage(img);
  }

  public void registerConnectServerEvent(ICustomEventListener listener) {
    _events[Globals.SERVER_CONNECT].addEventListener(listener);
  }
 
  public void registerDisconnectServerEvent(ICustomEventListener listener) {
    _events[Globals.SERVER_DISCONNECT].addEventListener(listener);
  }
 
  private void serverConnected() {
    int port;
    try {
            port = Integer.parseInt(jTFPort.getText());  
        } catch (Exception e){ return; }
       
    _events[Globals.SERVER_CONNECT].fireEvent(new ServerConnectEvent(this, port));
   
    btnConnect.setVisible(false);
   
    jTFPort.setEnabled(false);
   
    //btnConnect.setBackground(new Color(240, 240, 240));
    //btnDisconnect.setBackground(new Color(244, 164, 96));
  }
 
  private void serverDisconnected() {
    _events[Globals.SERVER_CONNECT].fireEvent(new ServerDisconnectEvent(this));
   
    btnDisconnect.setBackground(new Color(240, 240, 240));
    btnConnect.setBackground(new Color(60, 179, 113));
  }
 
   
    public void newClientConnected(Client newClient) {
      clientsTM.addRow(new Object[] {newClient.get_IP(), newClient.get_nickName(), newClient.get_ID() ,newClient.get_numOpenMsgs(), formatter.format(new Date())});
    }
   
    public void handleOpenMsg(Client newClient) {
      clientsTM.addRow(new Object[] {newClient.get_IP(), newClient.get_nickName(), newClient.get_ID() ,newClient.get_numOpenMsgs(), formatter.format(new Date())});
    }

    private static void init_look() {

        try {
          UIManager.setLookAndFeel(new NimbusLookAndFeel() {

        private static final long serialVersionUID = 1L;

        @Override
          public UIDefaults getDefaults() {
             UIDefaults ret = super.getDefaults();
             ret.put("defaultFont", new Font(Font.SANS_SERIF, Font.PLAIN, 13));
             return ret;
          }
      });
        //} catch (UnsupportedLookAndFeelException e) {
        } catch (Exception e) {
      e.printStackTrace();
    }
    }   
   
    private void jButtonAddClientMouseClicked(java.awt.event.MouseEvent evt) {
       
        int ip1 = generator.nextInt(255) + 1;
        int ip2 = generator.nextInt(255) + 1;
        int ip3 = generator.nextInt(255) + 1;
        int ip4 = generator.nextInt(255) + 1;
        String ip = String.format("%d.%d.%d.%d", ip1, ip2, ip3, ip4);       
        clientsTM.addRow(new Object[] {ip, ip, Integer.toString(generator.nextInt(Integer.MAX_VALUE)), generator.nextInt(100), formatter.format(new Date())});
       
        //clientsTM.addRow(new Object[] {"127.0.0.1", "MK", Integer.toString(generator.nextInt(Integer.MAX_VALUE)), generator.nextInt(100), formatter.format(new Date())});       
    }   
   
    private void PortChanged() {
      boolean isValid = false;
        try {
            String text = jTFPort.getText();                      
            if (Integer.parseInt(text) > 0 && text.length() <= 6) {isValid = true;}  
        } catch (Exception e){isValid = false;}
       
        lblPort.setVisible(!isValid);   
        btnConnect.setEnabled(isValid);
    }
      
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jScrollPane1.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {     
      @Override
      public void adjustmentValueChanged(AdjustmentEvent e) {
        if (isTableBottom) {
          e.getAdjustable().setValue(e.getAdjustable().getMaximum());
        }
      }
    });

        jTClients = new javax.swing.JTable();
        jButtonAddClient = new javax.swing.JButton();
        jButtonAddClient.setVisible(false);
        jTFPort = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("port:");
        jLabel2.setText("connected clients:");
        jScrollPane1.setViewportView(jTClients);
        jButtonAddClient.setText("Add client");
        jButtonAddClient.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButtonAddClientMouseClicked(evt);
            }
        });
       
        lblPort = new JLabel(" ");
       
        btnConnect = new JButton("Connect");       
        btnConnect.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            serverConnected();
          }
        });
        btnConnect.setBackground(new Color(60, 179, 113));
       
        btnDisconnect = new JButton("Disconnect");
        btnDisconnect.setVisible(false);
        btnDisconnect.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            serverDisconnected();
          }
        });
        btnDisconnect.setBackground(new Color(244, 164, 96));
       
        lblTableLock = new JLabel(" ");
        lblTableLock.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {           
            isTableBottom = !isTableBottom;
            Image imageLock;
            if (isTableBottom) {
              JScrollBar vertical = jScrollPane1.getVerticalScrollBar();
              vertical.setValue(vertical.getMaximum());
              imageLock = getToolkit().getImage(getClass().getResource("/resources/lock_close.png"));                
            } else {
              imageLock = getToolkit().getImage(getClass().getResource("/resources/lock_open.png"));                
            }
            lblTableLock.setIcon(new ImageIcon(imageLock.getScaledInstance(20, 27, Image.SCALE_DEFAULT)));
          }
        });
       
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
          layout.createParallelGroup(Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
              .addGap(25)
              .addGroup(layout.createParallelGroup(Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                  .addComponent(jLabel2)
                  .addPreferredGap(ComponentPlacement.RELATED, 461, GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                  .addComponent(jLabel1)
                  .addPreferredGap(ComponentPlacement.RELATED)
                  .addComponent(jTFPort, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(ComponentPlacement.RELATED)
                  .addComponent(lblPort)
                  .addPreferredGap(ComponentPlacement.RELATED, 260, Short.MAX_VALUE)
                  .addComponent(jButtonAddClient))
                .addGroup(layout.createSequentialGroup()
                  .addComponent(btnConnect, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(ComponentPlacement.RELATED)
                  .addComponent(btnDisconnect))
                .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 548, Short.MAX_VALUE))
              .addPreferredGap(ComponentPlacement.RELATED)
              .addComponent(lblTableLock)
              .addContainerGap())
        );
        layout.setVerticalGroup(
          layout.createParallelGroup(Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup()
                  .addContainerGap()
                  .addComponent(lblTableLock))
                .addGroup(layout.createSequentialGroup()
                  .addGroup(layout.createParallelGroup(Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                      .addGap(28)
                      .addGroup(layout.createParallelGroup(Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTFPort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblPort))
                      .addPreferredGap(ComponentPlacement.UNRELATED)
                      .addGroup(layout.createParallelGroup(Alignment.BASELINE)
                        .addComponent(btnConnect)
                        .addComponent(btnDisconnect))
                      .addGap(34)
                      .addComponent(jLabel2))
                    .addGroup(layout.createSequentialGroup()
                      .addContainerGap()
                      .addComponent(jButtonAddClient)))
                  .addGap(25)
                  .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE)))
              .addGap(25))
        );
        getContentPane().setLayout(layout);

        pack();
    }
 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAddClient;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTable jTClients;
    private javax.swing.JTextField jTFPort;
    private JLabel lblPort;
    private JButton btnConnect;
    private JButton btnDisconnect;
    private JScrollPane jScrollPane1;
    private JLabel lblTableLock;
}
TOP

Related Classes of server.ServerFrame

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.