Saturday, October 29, 2011

GUI and event-driven programming

This week A-Track (with B-Track to follow later) students will start using one important Java technology hidden in special object communications and behaviors provided with Java – GUI. GUI is not just a graphical interface but a whole different concept of communications and program logic. It makes threads of interactions with chains of questions obsolete and instead creates a set of windows and controls (buttons for now) that offer the user a choice of how to interact. GUI runs some internal loops waiting for various user actions and responds to any of such actions (mouseover, buttonpress, mouse down, etc.). For example instead of asking if the player wants to play again in a loop that you had to program manually – there is a rich choice of communication controls that user can initiate (like the button “Play Game” as one example) with event (like buttonpress) being passed to the listener waiting behind the scene.
Another important aspect to notice is that you are starting “event-driven” programming when code is executed not when you write your java command on console and even not when logic of one object calls method code to be executed from another object, but when some interface event happens that is passed to the listener object AND TRIGGERS its execution. AWT, that you include in the beginning of the program supports such event driven mechanism allowing various listener objects to subscribe for notification about some possible events happening to certain controls (text boxes, buttons, check boxes, radio buttons, etc.). When the event that the listener subscribed for occurs – Java “notifies” the listener by sending an event class with rich information about the event and allowing to trigger the code execution.
This shifted the method of program communication with the user from program-initiated one, with lots of loops polling the user for required information forcing to write complex logic fitting this loops in special sequences and nesting constructions, to user-controlled or event driven as described above. The benefit of MVC model and previous separation of Account and GameMachine classes from the Interface is that the new changes to GUI are done ONLY in the Interface class (if you PROPERLY separated it). If not – it is time to move the remaining game and accounting and possible other supporting actions into the Model section, which can consist of several classes interacting with each other or with Control components (listeners). In this case it is also good to clear the Application class with main() method from everything else just letting it start the Interface Window and instantiate the Interface class, which in turn will instantiate other necessary classes. It is not necessary to such clean-up of the Application class now but this is what you be doing later. In your first GUI driven program is important just to get rid of all user polling and allow for necessary windows and buttons to be properly placed on the main Window

Monday, October 17, 2011

Object-Oriented Design Part 1 (the beginning)

Congratulations! Now you know Java enough to write any program (as an algorithm)! As of now you know three sufficient language constructs: sequence, selection, and repetition. See the theorem ( http://en.wikipedia.org/wiki/Structured_program_theorem )  proving sufficiency of these constructs  for the design of any algorithm.
Then what is left in learning Java? Although we will pick a few small language enhancements – the main task will be in learning software engineering  as assembling (designing) increasingly complex software systems. The leading industrial approach to such engineering is called Object-Oriented design and programming. According to this approach (which we will be learning in more detail) – nobody writes programs. What do they do instead – is create classes (that will be instantiated as objects at runtime) and organize their interaction when the task triggers such collective attempt to solve the problem or just to be aware of the situation and react when necessary.  
This week gives you an introduction to the concept of classes and objects with some demonstration of data that an object can store and methods (work like local code libraries) that an object can invoke or that can be invoked by other objects in communication attempts.
A few good ideas for good design (many more to follow):
  1. A class should capture one and only one key abstraction/concept/responsibility. For example Student, Professor, Course, etc. are responsible for the behavior of particular entities with their data and methods (behaviors).  Thus a student can get a grade, be transferred, enroll into a course or drop one, pay the required tuition, can change the room in the dorm, etc. as well as have an assigned ID, name, address, telephone, and other data. Of course the program will work if to place these methods in, say, Course class, but following life modifications, updates, and relationships with other entities will become increasingly difficult.  Therefore an object is a special software construct combining properties of data types (allowing for information storage = state) and software libraries capable of executing the called process. Together they create a powerful combination capable of behaving as an entity (like Student) in a specific situation and state. They say that objects have state and behaviors. But in order to unleash their full capabilities – objects need to collaborate with other objects/entities providing necessary services and enriching overall system’s behavior.
  2. All data should be hidden within its class (called encapsulation): For now you might have direct access to data in a class, but in later designs should start avoiding such exposure allowing only access to the methods responsible for data reading/modifications (accessors and mutators”). We create private fields that hold the state of an object (like assigning a grade, a name, and address) and public methods that deal with them (in addition to other functions).  

Wednesday, October 12, 2011

Story about Java packages...

Once upon a time my son had a girlfriend (now she is “ex” and not because of poor programming skills). She graduated from college focusing on Java which she saw as a job and good salary guarantee with almost no need to use anything else. After graduation she got a job in a company which worked with sound processing and speech recognition using Java. Her initial salary (10 years ago) was $70K. Company over time developed a bunch of useful classes (just like the ones used in sound processing in week 6) but documented only using automated class documentation methods (just like in the package that A-stream students saw) that are difficult to understand and use. Just look at APSoundClip class packing a lot of free software in it, and imagine the time it would take you to create it from scratch. So she spent the first year struggling with such packages, learning what they can do and thus rapidly increasing her productivity and creative thinking (by knowing what ready-made blocks are available). Since it is a hard task in trying to understand and testing the classes – she, actually, was the only one who new almost all of their packages... and her boss. At some point her boss wanted to start another company (or blackmail the old one?) and invited her to join him. When the BIG boss learned about it he got really scared and offered her $95K and much more to her boss since if they would've left nobody could develop new products fast enough and all had to learn the packages for at least a year. And she was only 1 year after college and it was over 10 years ago... The moral of the story is that the experience that A-stream had in week 6 was tough but very interesting and important.

Sunday, October 9, 2011

Solution to problem 3-7

// Solution to Project 3.7
// Displays coordinates of the center point of the panel. Notice that there are two separate classes
// here that can be compiled separately but work together if are in the same folder
// When both classes are compiled - run this one (the first shown)
//since it has  " public static void main(... "
import javax.swing.*;   
import java.awt.*;      
public class GUIWindow{
   public static void main(String[] args){
      JFrame theGUI = new JFrame();
      theGUI.setTitle("GUI Program");
      theGUI.setSize(300, 200);
      theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      ColorPanel panel = new ColorPanel(Color.white);
      Container pane = theGUI.getContentPane();
      pane.add(panel);
      theGUI.setVisible(true);
   }
}

//Example 3.7: used together with the GUIWindow class but compiled
//as a separate class

import javax.swing.*;
import java.awt.*;
public class ColorPanel extends JPanel{
  
   public ColorPanel(Color backColor){
      setBackground(backColor);
   }
   public void paintComponent(Graphics g){
      super.paintComponent(g);
      int x = getWidth() / 2 - 60;
      int y = getHeight() / 2;
      g.setColor(Color.blue);
      g.drawRect(x, y, 120, 20);
      g.setColor(Color.red);
      g.drawString("Hello world!", x + 10, y + 15);
   }
}