Monday, 25 February 2013

Java Swing Components and Creating a Program Part 1



Interface construction is an important part of any programming language. This post is designed as a quick introduction to some of the basics of the swing library in Java. Swing is a collection of useful components that can be used to create graphical user interfaces. 

First we’ll start with a description of our program. Our clients want (for some reason) a Java program that is able to load and display a file, edit this file and save it again on the hard drive. The program should have menu options as well as buttons for controlling it. The program should also be able to send an email to the eas_pso email address for help if required. If something goes wrong the program should pop up error messages with some useful information. The program should also have an ‘about’ popup which tells the user about the program and how to use it. 

This isn’t a very complex program, though it may sound like it to start with. We start by designing our layout and making a list of things we need to implement:


  1.  A frame is displayed on the screen
  2. Menu Bar
  3. Buttons
  4. Options in the menu and buttons for:
    1. Open File
    2. Save File
    3. Exit
    4. Email
    5. About
  5. Load text from a file
  6. Edit the text
  7. Save text to a file
  8. Email for help
  9. About box


The first thing our GUI needs to be able to do is display a frame on the screen. Our initial Java program for this uses the following:
public class GUIElementsExample {

       /**
        * Main method, runs the example
        *
        * @param args command line arguments
        */
       public static void main(String[] args) {
              new GUIElementsExample();
       }

       // global variables

       //the main frame in the program
       private JFrame frame;
       // constructors
       /**
        * Default Constructor, opens a frame with several gui elements.
        */
       public GUIElementsExample() {

              // first we set up the frame with a title
              frame = new JFrame("GUI Elements Example Program");
              frame.setSize(800, 800); // this line sets the size of the frame in
                                                              // pixels     // the default close operation refers to what happens when the X in the
              // corner is pressed
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

              // finally we make the frame visible, drawing everything on the screen
              frame.setVisible(true);

       }
}

This program current runs the main method, creating a new instance of our GUIElementsExample Object. The constructor for the GUIElementsExample creates a new frame, sets the size of the frame, the default close operation  and makes the frame visible. The default close operation is what happens when the X in the corner of the window is selected and set to dispose of the frame by default, rather than quit the program. We override this with EXIT_ON_CLOSE so the program exits completely when the frame is closed. We’ll see an example where we don’t want to do this later for the ‘about’ popup. The frame is set to be visible last, after all the components have been added to the frame; this ensures that they are all displayed correctly. The frame is only updated when it is moved, resized or frame.validate() is called, so if we display it before adding the components we then have to validate it later. 

Now we have a frame that draws on the screen.





Part 2: Adding menus to our frame!

Friday, 22 February 2013

Learning Python - Quite a good link

Just a quick post to mention this website:
http://www.learnpython.org/
It goes through step by step and teaches the basics of python with examples and checking your code output.

Friday, 15 February 2013

Introduction to objects and accessibility in Java



Over the last few years I have found myself trying to explain how objects and accessibility works for different groups of students. Understanding is a fairly fundamental part of any object oriented language and they should be simple enough to explain and use.

So we started with an analogy: An object is a box. Each box describes a single object. It contains all the facts about this object as variables, and all the things we can do with those facts as methods. An object can also include other objects; the same was as you can put one box inside another box.


So using a very (boring) standard example we can look at a bank account object. (Note: At this stage we do not have a very good example of a class, later we will look at how we can protect out objects from outside tampering)

class BankAccount {
       //variables
       double balance;
       //Constructor for the class, default balance is 0
              BankAccount(){
                     balance = 0;
       }
}

A class is a description of an object, what it contains and what it can do. To create an instance of an object we need to declare it elsewhere in the code. The example below creates a BankAccount object in a different method.

       public static void main(String[] args) {
              BankAccount account = new BankAccount();
       }

We can break this down into separate parts. The public keyword states that this method is publically accessible. Any object, anywhere can access and run and change this piece of code. Our main method in java has to be publically accessible otherwise we would never be able to start a program running.
Next we have the static keyword. This means that we can run this method without needing to create an instance of the object first. Static methods and variables are usually used for references. If there is a single number that will never change, such as pi (3.141……etc), or a method for converting temperature from Celsius to Fahrenheit we know this will never change. These methods can be run as stand along pieces of code. The main method also works like this. We want to run this before creating objects, otherwise the program would be unable to start. 

Third we have void, this is the return type for the method. The main method here does not return anything. 

Next we have the method name, main. The parameters given to the method are enclosed in the brackets after the method name - (String[] args). This is information passed to the method for it to use however it wants. In the case of the main method this is information passed in from the command line. The signature of the main method never changes, we always use the exact same wording.

The interesting part of our program is the single line:
                BankAccount account = new BankAccount();

This creates a new BankAccount object called account. The keyword new means that java looks up how to create this particular object. It looks for a constructor in the code. 

       //Constructor for the class, default balance is 0
       BankAccount(){
              balance = 0;
       }

So here the balance stored inside the bank account object is set to 0. 

If we look at this in terms of boxes our code has:

  1. Created a new box
  2. Called this box “account”
  3. Put a number on the side the box called “balance” and set this equal to 0.

Now, it might make sense to have the balance on the side of the box. This way we can read how much money we have in our account, add and remove money as it is spent. By default all variables, methods and classes are declared to be public. Any other object in the same package can change these values! By convention we should always use the public keyword so we are aware of what our code is doing.



public class BankAccount {

       //our main method that creates the object      
       public static void main(String[] args) {
              BankAccount account = new BankAccount();
       }
      
       //variables
       public double balance;
             
//Constructor for the class, default balance is 0
       public BankAccount(){
              balance = 0;
       }
}

The problem with setting everything to be public is that a malicious program could come along and change the balance to be anything they like. To protect against doing this we can make the variable private. This is the equivalent to writing the balance on a piece of paper and putting it inside the box. Only the account object would be able to access the balance and change it from that point on. Much more secure!


private double balance;

We now need to create some accessor methods. These allow us to get and change the value of the private variable indirectly. The object is able to validate requests to change the value of balance, for instance, not allowing the account balance to go below 0.

The convention for these type of methods is to use getVariable() and setVariable(…) methods. Get methods return the value currently held in a variable. Set methods set the value to another number. For our bank account we don’t want to just be able to set the current balance to be anything, we want to increment and decrement it as required.

First lets write the method for getting the value of the balance.

public double getBalance(){
              return balance;
       }

The public keyword tells us that this method is public, it is written on the side of our box. We can access it from any other methods. The return type for this method is double. This method will run some code and return a number formatted as a “double”. The variable name is using the convention, getBalance(). We don’t need to pass this method any additional information so the parenthesis are empty.

This method comprises just a single line: return balance; This returns the value of the balance variable. As the method and the variable are both in the same object, this method is able to return the value without any trouble.

Now we want to increase and decrease the balance.

//increase the balance
       public void addMoney(double amount){
              balance = balance + amount; //increase the balance
       }
      
       //decrease the balance
       public boolean takeOutMoney(double amount){
//If there is enough money in the account
              if (balance > amount){           
                     //update the balance and return that it worked 
balance = balance - amount;
                     return true;
              }
              //else we return false to say this method didn’t work
              return false;
       }

Adding money to the balance is a simple process that doesn’t require any checks. We declare this method to be public (written on the side of the box for all to see), the return type is void as this method doesn’t need to send any information back and we pass it a value, the double amount. This is then added to our current balance.

Decreasing the balance requires a check. This method returns a boolean value, a true or false value based on whether the method was able to complete as intended. If the balance is greater than the amount being removed then we update the balance to reflect this and return true, that the money was able to be removed. Otherwise we return false, stating that the operation was not able to be completed.

So our final class looks like this:


public class BankAccount {

       // our main method that creates the object
       public static void main(String[] args) {
              BankAccount account = new BankAccount();
       }

       // variables
       private double balance;

       // methods

       // Constructor for the class, default balance is 0
       public BankAccount() {
              balance = 0;
       }

       public double getBalance() {
              return balance;
       }

       // increase the balance
       public void addMoney(double amount) {
              balance = balance + amount; // increase the balance
       }

       // decrease the balance
       public boolean takeOutMoney(double amount) {
              // If there is enough money in the account
              if (balance > amount) {
                     // update the balance and return that it worked
                     balance = balance - amount;
                     return true;
              }
              // else we return false to say this method didn’t work
              return false;
       }

}


In our box equivalent we have a single box called account. On the side of the box we have written the methods getBalance, addMoney and takeOutMoney. These all manipulate or return the value of the private variable balance, hidden inside the box. Any other object can be included in this scenario and they will be able to use the publically available methods, but not see the private information inside the other box.