Universidad Carlos III de Madrid

Ingeniería de Telecomunicación

Enero-Mayo 2010 / January-May 2010

Graphical User Interfaces

Lab Section1.  Session 2 (lab): Graphical User Interfaces

Exercise Section1.1.  Passive elements in GUIs

Probably one of the simplest graphic component is a text label (javax.swing.JLabel). The following code shows a simple GUI example: a window with a text label:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;

class HelloWorldGUI {

  public static void main(String args[]) {
    JFrame frame = new JFrame("HelloWorldGUI window title");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel contentPane = (JPanel) frame.getContentPane();
    JLabel label = new JLabel("Hello World!");
    contentPane.add(label);

    frame.setSize(100, 50);
    frame.setVisible(true);
  }
}

          

Download this code

  1. Compile and test this program.

  2. Enumerate, on a sheet of paper, the names of the classes of the objects that are created throughout the execution of the program.

  3. Open the Java API and find those classes. Which package can you find them in?

  4. Enumerate the methods that are invoked throughout the execution of the program and the classes to which they belong to (according to their hierarchical structure). Do not forget to enumerate the constructors.

  5. Try to explain, writing on a sheet of paper, what every line of code does in the execution of the code. When you have finished all the exercises of this session, return to this section and review your notes to see if you can add something new.

  6. Implement a HelloWorldGUIBig program similar to HelloWorldGUI where window's size is 4 times bigger.

  7. Write a HelloWorldGUIColor program similar to HelloWorldGUI where the background colour of the label is blue.

Exercise Section1.2.  Introduction to event management

The following code is a simple graphic interface which contains a javax.swing.JButton button that can be clicked. The rest of the elements of the interface should be well known by you.

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.BorderLayout;

class Simple00GUIEn {

  private static final String FRAME_TITLE = "Simple00GUI";
  private static final String BUTTON_TEXT = "Click me!";

  private void createGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame(FRAME_TITLE);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel contentPane = (JPanel) frame.getContentPane();
    JButton button = new JButton(BUTTON_TEXT);
    contentPane.add(button, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String args[]) {
    Simple00GUIEn p = new Simple00GUIEn();
    p.createGUI();
  }
}

          

Download this code

  1. Compile and execute this program. What happens when the button is pressed?

  2. Open the Java API and localize the JButton class (this is a good habit that you should always do when programming).

  3. Implement a program, Simple01GUIEn, based on Simple00GUIEn, in which a text message is printed to console when the button is pressed. You will find useful the javax.swing.AbstractButton.addActionListener(ActionListener l) method and the following code shell:

    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    
    class ButtonActionListenerEn implements ActionListener {
    
      public void actionPerformed(ActionEvent e) {
    
      }
    }
    
              

    Download this code

  4. Implement a program Simple02GUIEn, based on Simple00GUIEn, in which the program modify its text when the user clicks the button.

  5. Implement a program Simple03GUIEn, based on Simple00GUIEn, which also contains a JLabel which text appears after the first button press.

  6. Write a TwoButtons program that contains two buttons, A and B. When the program starts, only the A button must be active. When the A button is clicked, it must be disabled and B must turn into active. The behaviour of B button must be simmetric to A. Here you can find an example: TwoButtons.class. (Note: This example is composed of a single class, but you are not forced to follow the same pattern. Choose the more suitable way for you).

  7. Regarding the previous section, if you made the program with a single class, repeat the exercise using several classes. If you implemented several classes, make the necessary changes in order to have a single class (that is, only a .class file).

Exercise Section1.3.  Tic Tac Toe basic (I)

During this exercise, we are going to practice with the implementation of a complete example of a Graphic User Interface (GUI) that integrates the corresponding Event Management associated to the graphic elements that are composed of.

To do so, we will base on the Tic Tac Toe famous game. According to the Wikipedia, the Tic-tac-toe (also spelled tick tack toe, and alternatively called noughts and crosses, Xs and Os, and many other names) is a pencil-and-paper game for two players, O and X, who take turns marking the spaces in a 3×3 grid, usually X going first. The player who succeeds in placing three of his/her marks in a horizontal, vertical or diagonal row wins the game.

To simulate the game board, we will use the following graphic elements that belong to the javax.Swing package:

  • The cells of the board are simulated with graphic buttons (javax.swing.JButton) with an associated image (javax.swing.ImageIcon).

    • If the space is free, without having being marked, the button will have no image associated to it.

    • Marking a cell is simulated by associating an image to the button. The image is binded to each player's turn respectively: O and X

      Images are shown next so you can download them:

      Note

      When initialising an ImageIcon object with the path to the button image, make sure that such path is correct so that it can be shown to the user.

  • The board will be modelled as a javax.swing.Jpanel container element, whose associated layout will be java.awt.GridLayout (3x3). Additionally, a 3x3 bidimensional array will be used for storing the corresponding buttons associated to each of the cells of the board.

    • The 3x3 bidimensional array will be filled in with the previous buttons.

The following image shows the main window of the game, which consists of the following panels (JPanel): an upper panel (panel_info) that contains information about the turn of the current player; a central panel (panel_board) that initially contains the button's array without any associated image, that is, the initial empty game board that is ready to start playing:

As the turns of players turns succeed, each player “marks the space" by clicking the corresponding button. To simulate the space mark, the button image will be changed according to the symbol of each player as shown at the next figure:

In case of some space could not be marked (for example, if there are no symbols left for the player or if the player's turn is not correct), an error message should be displayed.

Finally, if a player wins the game, a congratulations message will be displayed as shown in the next figure:

The TicTacToeButton class.

Let's implement the TicTacToeButton class that represents the space or square each player can mark. To simulate the mark, the button will update its associated image according to whether it is free (it has no image) or marked (with the associated image of the corresponding player). To achieve that, the class has the following attributes:

  • An integer attribute (turnPlayer) to store the player's turn and it represents the state of the space (square).

  • Three integer constants (FREE, PLAYER_1, PLAYER_2) that indicate the possible states associated to the buttons.

  • An image array (javax.swing.ImageIcon[]) that stores the respective players' symbols: O y X

Download the class skeleton from the following link TicTacToeButton.java and implement the following methods:

  • The class constructor public TicTacToeButton() that initializes the button and let it in free state (FREE), that is, with no player's turn and, therefore, without any associated image to it.

  • The public void setPlayer(int newPlayer) method that updates the button's state with the turn of the new player and its corresponding image.

Test the operation by executing the main class method and passing it, as an argument, any of the three possible button's states (FREE(-1), PLAYER_1(0), PLAYER_2(1)) to see whether the result is correct or not.

The TicTacToe class.

In this section, we are not going to program anything, we just intend to observ how the Tic Tac Toe main board Graphic Interface has been built. Download the TicTacToe class skeleton from the following link TicTacToe.java and look at the following methods that allow building the Graphic Interface.

Note

The private void createEventListener() method that implements the Event Management configuration has been left empty until the next section.

  • The private void buildGraphicElements() method initializes all necessary graphic elements to build the Graphic Interface (labels and array of buttons) and initializes them to free state (FREE), as has been previously mentioned in the text.

  • The private void addElementsToContainers() method adds the previous graphic elements to their corresponding panels (information and board). Finally, it adds those panels to the window main container.

To make the main GUI window visible with the initial state of the game, execute the main methdod of the class. This method just creates, initializes and makes it visible by invoquing those previous methods.

The TicTacToeButtonListener class.

In this chapter we are going to "revive" the game so that it will be able to interact with the user according to the rules of the game. All this is achieved by the implementation of the GUI “Event Management” that involves, normally, the following tasks:

  1. To decide what kind of graphic components of the Graphic Interface constitute the "Event Source", that is, which components are going to generate events that we will want to treat later. In our case, such graphic components will be the board buttons (JButton) that represent the board spaces or squares.

  2. To decide what type of events, from all those that the components are able to generate, are going to be treated later by the corresponding listener or listeners. In this case, all events that we will treat are of ActionEvent type, related to the user clicking the button.

  3. To define the number of Listener classes that are going to react to the previous events. The number of classes is variable, it can be a unique class or serveral depending on the strategy of design for the Event Management. In this case, we will implement a unique listener class, TicTacToeButtonListener, that will be the responsible for the management of every ActionEvent event that is generated when a button (TicTacToeButton) is clicked. This is achieved by implementing the respective interface (interface) that is associated with that type of event, in our case, the ActionListener interface.

  4. For each graphic element that will act as an "Event Source" and wants to be treated later by one or several Listener classes, it is necessary previously register it (or them) at the compoment. In our case, once an instance object of our Listener class (TicTacToeButtonListener) has been created, it has to be registered on every board button by calling to the public void addActionListener(ActionListener l) method.

  5. Finally, to implement the Event Listener class, TicTacToeButtonListener, that is, implement both the constructor and all methods of the interface or interfaces that have to be implemented according to the previous selected strategy (point 2). The real event management associated to the GUI is realized in these methods.

Regarding the three first points (1. 2. and 3.), everything can be summed up in the fact that the only graphic components that are going to act as event sources will be the board buttons (JButton). Regarding the distinct types of events that can be treated, only events of ActionEvent type, that are generated when a button is clicked, will be managed. It has been decided to create only one listener class, TicTacToeButtonListener, that will take charge of the management of ActionEvent type events by implemmenting the ActionListener associated interface and, therefore, the following single method of it: public void actionPerformed(ActionEvent event).

In this section, we will implement the code of the two last points (4. and 5.).

  • The point 4. is implemented with the private void createEventListener() method of the TicTacToe class. It is in charge of the creation and the subsequent registry of the listener for each graphic element that generates events, that is, for each button of the board.

    Implement the code of the method in the TicTacToe skeleton class according to what has been specified in the text.

  • The point 5. force us to implement the public void actionPerformed(ActionEvent event) in the TicTacToeButtonListener listener class. In this method is where the actual GUI Event Management is realized. The generated event is passed as the event parameter to the method.

The flow diagram associated to the public void actionPerformed(ActionEvent event) method is described as follows. It is specific for a "PLAYER_X" player and it represents the program flow that it is realized when such player clicks the button that corresponds to the space (s)he wants to mark. In the flow diagram, basically three conditions are checked before verifying whether the player has won the game:

  • First, it is checked whether the player has enough free symbols to mark the space (remember, the player owns only three symbols to use).

    • In case of affirmative answer, it is checked whether the space is free (FREE) or not and, in that case, a message error should be displayed to the player.

    • In case of negative answer, it is checked whether the actual turn belongs to the "PLAYER_X" player or not and, in that case, a message error should be displayed to the player.

Note

To show a Dialog's Window with an error message, you can use the static showMessageDialog method from the javax.swing.JOptionPane class.

Homework Section2.  Homework

Exercise Section2.1. Practice with the Window Manager

A Window Manager is a program that controlls the windows in a graphic environment. Window Managers allow the user to manage windows without communicating with the programs that create them. This way, a Window Manager allows to perform the following tasks with windows on a graphic environment: to create and destroy windows, to move and resize windows, to change the active window (focus selection) and to hide and show hidden windows.

This is why programs that open windows, have to both communicate with the user and with the Window Manager; that is, a graphic program will have to provide the following communication interfaces:

  • An interface for the user to communicate with the program. It can be either the standard input and/or any graphic component (a button, etc.) that is located at the window.

  • An interface for the program to comnunicate with the user. It can be either the standard output and/or text labels and drawings that may be depicted at the window.

  • An interface for the window to communicate with the Window Manager and vice versa. For example, when the user communicates with the Window Manager asking for closing the window (by clicking the cross button of a window), the Window Manager passes the message to the window and this one passes it to the program that controls it to finish its execution.

Most graphic environments permit to execute different Window Managers on them, each one with distinct ways of working, some of them more comfortable than others, some of them nicer than others. Windows Operating System uses a single Window Manager by default. Probably, it is the only Window Manager you know, but there are a lot of them (hundreds).

Usually, Window Managers communicate with the user through a serie of gadgets added to windows (for example, a border, a title bar and some buttons). These gadgets, besides some key combinations (e.g., Alt-Tab), permit the user to send commands to the Window Manager about what to do with the window (maximize it hide it, etc.)

JFrame class has a set of methods that allows the window to communicate with the Window Manager and vice versa.

  • setVisible(boolean b)

    By default, new windows are not visible on the screen. Use this method to make a window visible. Do not do it right after its creation because probably you may want to configure some details before making it visible.

  • setLocation(int x, int y)

    By default, new windows are placed at position (0,0); that is the upper left corner of the screen. With this method, you can choose the position where the window will appear. X axis grows rigthwards and Y axis grows downwards.

  • setUndecorated(boolean b)

    By default, the Window Manager adds its own decoration to the windows you create (normally, a tittle bar and some buttons to manage the window). If you do not want it to do it, use this method. Note: It is illegal to change the window decoration once it is visible.

    Note

    Some Window Managers, like Windows XP one, communicate with the user mainly with these decorations; if you remove them, it could be difficult for the user to manage the window.

  • setExtendedEstate(int state)

    Windows can have different states for the Window Manager. They can be visible, iconified (hidden), maximized, etc. Use this method to modify such state, but note that not all systems admit all states.

  • setDefaultLookAndFeelDecorated(boolean b)

    By default, new windows are decorated according to the preferences of the Window Manager. This decoration can be overwritten by the "Look and Feel" we have choosen previously.

  • setDefaultCloseOperation(int operation)

    When a user asks the Window Manager to close a window, the Window Manager asks the window to execute a certain operation, normally to kill the process. By the use of this method, we can configure the behaviour of our window so that it performs some other operations, such as ignore the message or to make some alternative operation (e.g., showing a closing-confirmation dialogue).

To do this exercise, make the following tasks:

  1. Have a look to the Java API and try to understand the description of each of the previous methods.

  2. Write a HelloWorldGUIDeaf program similar to HelloWorldGUI that ignores the Window Manager's closing message. Test it. How can the window be closed now?

  3. Write a HelloWorldGUIUndecorated program similar to HelloWorldGUI that do not use any Window Manager decoration.

  4. Write a HelloWorldGUIDecoratedprogram similar to HelloWorldGUI that uses the Java's default "Look and Feel" instead of the Window Manager one.

Exercise Section2.2.  Introduction to different Layouts

Usually, graphic interfaces of a program have a great number of different components . This is why it is necessary to have a method to distribute them throughout the window that contains them.

Java Layout Managers cover this need. By means of standard positioning policies, some generic guidelines are established so that the LayoutManager carries these policies out accurately.

A JPanel has a positioning policy associated to it, but can be customized according to programmer's needs. In this exercise, we will work with a kind of Layout called BorderLayout ( "border" means "frontier" ) which is configured as the default border of the contentPane of a JFrame

  1. Implement a first version of a program called CompassSimple that should be like HelloWorldGUIColor but, in this case, it has to set the label with the background color to black and the foreground color to white. The window should be 400x200.

  2. Modify the program CompassSimple so that it shows 4 labels:

    • Text: "North", background colour: black, foreground colour: white

    • Text: "South", background colour: white, foreground colour: black

    • Text: "East", background colour: blue, foreground colour: red

    • Text: "West", background colour: red, foreground colour: blue

    Every label should be placed at the window, with a BorderLayout positioning policy, according to the guidelines that indicate its text ("East" label at the left of the panel, etc.). Do not make any aesthetic considerations about the result. It could be useful to go to the Java API, which provides information about attributes and methods of the following classes:

    java.awt.Container //Especially the different variations of add() method
    java.awt.BorderLayout //Especially the static attributes
    
              

    Using the window's handler, modify the size of the window and see how all labels are automatically positioned in the correct place.

  3. When you create a label, which horizontal alignment has its text by default? And which vertical alignment?

Exercise Section2.3. Practice with diferent Layout Managers

We will start from the introduction exercise about the different types of Layouts. To do so, perform the following tasks:

  1. Implement a CompassBetter program that centers the text of every label, set the background colour to black and the foreground colour to white.

  2. You know that labels can contain text; however they can also contain images. Write a CompassMuchBetter program similar to CompassBetter but with a label with this image, in centered alignment. Be careful with the path of the image.

    The result should be something like this (border colours can change in your system):

  3. The JFrame.pack() method calculates the minimal window size so that all components contained in it can be placed in a reasonable manner. It calls JFrame.setSize() method with that size. Implement a CompassMuchBetterSmall program similar to CompassMuchBetter but, in this case, the window size should be the smallest necessary to be shown.

  4. Write a HelloWorldGUICentered program similar to HelloWorldGUI that shows its window centered and has its size automatically calculated.

    Suggestion

    Screen size can be obtained using JFrame.getToolkit().getScreenSize() method and window size can also be calculated using JFrame.getWidth() and JFrame.getHeight().

  5. Implements a centerAndShowFrame(JFrame frame, double xScale, double yScale) method that centers the window at the screen, resizes it to the minimal size scaled by xScale and yScale values and finally, makes it visible. You can encapsulate this method in a FrameUtilities class to reuse it in the rest of the programs you make in the future.

Exercise Section2.4.  Tic Tac Toe with time counter (II)

To improve our knowledge about the Java Event Management model, we are going to propose the following exercise to do at home. We will be based on the TicTacToe GUI's code that we have programmed at the laboratory's session and we are going to add a new functionality that will permit to control the remaining turn's time for each player of the game. That's why we are going to incorporate a new component that is provided by the Java's graphics library (javax.swing) that acts as a "timer".

The component we are talking about is implemmented at the javax.swing.Timer class and, basically, it generates ActionEvent events periodically at constant intervals that can be configured previously. The way these events are managed by the component is seamlessly integrated on the Java's general "Event Delegated Management Model" that, let's remember, is based on the presence of three kinds of objects:

  • A set of Event Sources that generate events of a certain type as a consequence from user actions when interacting with them.

  • A set of Events that can be organised in a class hiereachy according to the stored information and the distinct origin of them. For example, ActionEvent type for user actions over a component; MouseEvent type for mouse movements; KeyEvent type for key strokes, etc..

  • A set of Listeners that react to of events that are generated by the precciding event sources according to the distinct types of events they are subscribed to. For that, they must implement the associated interface for the type of the event they want to manage: ActionListenter for ActionEvent events; MouseListenter for MouseEvent events; etc....

This model has many advantages: is understandable, flexible, extensible and robust. A good proof of this is how easy will result to add aditional Event Management logic code to our TicTacToe's GUI. To achieve that, let's make the corresponding Event Management analogy associated to the component that we are going to incorporate to the application:

  • The Source of Events will be the Timer component (javax.swing.Timer)

  • The Event type that is going to be generated and treated next is ActionEvent.

  • The Listener class (TimeListener), has to implement the associated interface of the Event's type: ActionListener.

The following image shows the initial window where the label with the player turn's time remaining information is located at the upper information's panel (10 seconds for this game).

The time counter starts discounting seconds until the player turn's time is over, in that case, a Dialog Window is shown with the corresponding error message to the user.

After the user has clicked the Accept button, the player's turn is changed and the time's counter is reset to the initial value, after that, it will start discounting seconds again.

Starting from the previous laboratory TicTacToe exericse's code you have implemented, make the following tasks to be able to incorporate the time counter to it:

  • Add the following attributes to the TicTacToe class that will be necessary to integrate the time counter:

    • A label (JLabel) that contains the text wiht the information of the remaining turn's time.

    • An integer constant (final static int) that represents the maximum turn's time.

    • A Timer reference (javax.swing.Timer) that will be the time counter.

  • Implement the TimeListener class that acts as a Listener class for the time counter's events.

    • Add a class attribute that should be a reference to the main window's game (JFrame) and it will be initialized at the class constructor.

    • Add another integer static attribute that will store the remaining number of seconds of the player's turn.

    • Implement the public void actionPerformed(ActionEvent event) method that will be executed periodically by the Timer's object. Such method will decrement the seconds counter and, in the case this value reaches to cero, it will show the corresponding error message to the uses. Finally, it will change the player's turn.

  • Create a Timer object's instance at the TicTacToe's constructor so that, it is started discounting the remainig turn's time from that moment.

    • As a constructor's argument, pass a TimeListener object's reference to it that has to be initialized with a window game's reference, that is, with this

  • Finally, update the method that serves to change the player's turn, public void changeTurn(), so that it should set the TimeListener second's static counter to cero. The counter will, therefore, start discounting the new player turn's remaining time.