Chat Tutorial in NetBeans/GUI Client

From Arianne
Jump to navigation Jump to search

Introduction

These instructions are a continuation of the Chat Tutorial. As the client requires the creation of a new screen, we can use the GUI editor in NetBeans instead of writing that code manually. Be careful of which parts of the code you do manually edit, as the GUI section is edited in the GUI window and it can be corrupted if you are not careful.

NetBeans Project

Open the client Project; close any other Projects. Right click on the project and select Properties. In the Run section, change the Main Class to client.Chat.

Right click on the client package and select New and Java Class. Enter Class Name as Chat and click Finish.

Delete the Test.java entry (right click, select delete).

The following files need to be created.

Chat.java

This has been created above, but has only the template contents. Change the file to:

/*
 * 
 */

package client;

/**
 *
 */
final class Chat {
  private Chat() {}
 
  public static void main( String[] args ) {
    new View();
  }
}

Ignore errors for the moment (we have not defined the View object).

View.java (part 1)

This may appear to be a bit messy, as we are combining manual file editing with the automatic GUI generation method. Please take care to follow the instructions carefully.

Right-click on the client package and select New, JFrame Form. Give the Class Name as View, and click Finish. You may have to wait a while; NetBeans will open View.java in the edit window. This window now shows a blank grey box that will be your window layout and additional panes on the right.

Click the Source button on the top of the editor window. Modify the class line so that it shows ...extends JFrame implements ActionListener. The top of the code should now be:

/*
 * 
 */

package client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import marauroa.common.game.RPObject;

/**
 *
 */
public class View extends JFrame implements ActionListener{

  /** Creates new form View */
  public View() {
    initComponents();
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
    [_Generated_Code_]

The last line is shown as a box of "Generated Code", which can be expanded using the + on the left but MUST NOT be changed in this screen, only in the GUI editor. Delete the code belonging to the main method, up to the line showing the Variables declaration. Again DO NOT delete these last two lines.

The rest of the code should now be:

    // Variables declaration - do not modify
    // End of variables declaration
}

If you have edited this correctly, you can save the file, close it and open it again. It will still show as the form you had before. If you look at the files it has created, using the files explorer, there is a View.java and a View.form and these two files must be consistent for the View class to show correctly in NetBeans. If it does not, delete the View class and start again; it is too difficult to try to edit both files manually.

GUI Form

Add the following components to the GUI form. Note that the sizes given are suggestions; feel free to experiment with sizes and positions.

  • Click on the blank window. In the Properties list, change title to Chat 0.1 and name to main.
  • Add a Label from the Swing Controls section of the Palette, by clicking on Label in the Palette, and dragging it to the top left of the form, leaving a suitable margin to the edge. In Properties, change the text to Username.
  • Add a second label (select and drag) below the first. Change the text to Password.
  • Add a third label (select and drag) below the second. Change the text to eMail.
  • Add a Text Field (Palette, Swing Controls section), to the right of the Username label. In the Code list change variable to jUsername. In Properties, clear the text value and change horizontal size to 210.
  • Add a second Text Field below the first field and to the right of the Password label. In the Code list change variable to jPassword. In Properties, clear the text value and change horizontal size to 210.
  • Add a third Text Field below the second field. In the Code list change variable to jEmail. In Properties, clear the text value and change horizontal size to 210.
  • Add a Button (Swing Controls section) below these fields, aligned to the right. In the Code list change variable to jConnectButton. In the Properties, change the text to Connect.
  • Add a Scroll Pane (Swing Containers) positioned below the previous elements. Scroll down the Properties list and change horizontal size to 280 and the vertical size to 200.
  • Add a Text Area (Controls), dragged into the Scroll Pane. In the Code list change variable to jChatArea. In the Properties, untick editable.
  • Add a Text Field (Controls), below the Text Area. In the Code list change variable to jInputField. In Properties, untick enabled, clear the text value and change horizontal size to 210.
  • Add a Button (Controls) to the right of the Text Field. In the Code list change variable to jSayButton. In Properties, untick enabled and change text to Say. You could drag the right hand side to align with the text area.

Note that the shaded window area may resize as you add these elements; you can drag this to a larger size if it makes adding elements easier, then drag it to nicely surround the elements when you have finished.

View.java (part 2)

Click the Source button. Below the class definition line, add the following code to create the action controls for the form. Note the the first and last lines already exist.

public class View extends JFrame implements ActionListener{

  private Client client = null;
  private javax.swing.Timer timer;

  /** Creates new form View */
  public View() {
    initComponents();
    jSayButton.addActionListener(
      new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
          String message = jInputField.getText();
          jInputField.setText("");
          client.SendMessage(message);
        }
      });
    jConnectButton.addActionListener(
      new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
          try {
            client = Client.get();
            client.connect("localhost", 5555);
            String sUsername = jUsername.getText();
            String sPassword = jPassword.getText();
            String sEmail = jEmail.getText();
            if (!"".equals(sEmail)) {
              client.createAccount(sUsername, sPassword, sEmail);
            }
            client.login(sUsername, sPassword);
            if (client.GetAvailableCharacters().length == 0) {
              RPObject character = new RPObject();
              client.createCharacter(sUsername, character);
            }
            client.chooseCharacter(sUsername);
            jConnectButton.setEnabled(false);
            jSayButton.setEnabled(true);
            jInputField.setEnabled(true);
          } catch (Exception exception) {
            JOptionPane.showMessageDialog(
              View.this, "Error", exception.toString(), JOptionPane.WARNING_MESSAGE);
            client = null;
          }
        }
      });
    timer = new javax.swing.Timer(300, this);
    timer.setInitialDelay(500);
    timer.start();
    setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if (client != null) {
      client.loop(0);
      String s = client.popQuote();
      while (s != null) {
        jChatArea.append(s + "\n");
        s = client.popQuote();
      }
    }
  }

  /** This method is called from within the constructor to

Some of this code has come from the Test class we deleted at the start of this page. Save this file.

Client.java

The Client.java file that existed previously is used in this part of the tutorial. It remains the same.

Building

If there are no errors in the package, select Run, Build Project from the NetBeans menu bar. This will create client.jar in the dist directory. That file is required for the deployment.