1,QWURGXFWLRQWR-DYD3URJUDPPLQJ (( Part 3: Graphical User Interface (GUI) & Java Applets EE905-GUI 7RSLFV Creating a Window Panels Event Handling Swing GUI Components ƒ Layout Management ƒ Text Field ƒ Check Box ƒ Combo Box ƒ Menu ƒ Dialog Java Applets (in comparison with Java Applications) EE905-GUI-2
2 7KH*UDSKLFV3DFNDJHV Originally, you would program graphics in Java using the AWT (Abstract Window Toolkit) - java.awt. The AWT provided (and still provides) cross-platform graphics support using the window and graphics functions provided by the various platforms, but for reasons you ll find in the textbooks, it s not the ideal way to do it. The later toolkit, and the one we ll be using, is called Swing - javax.swing. It does not rely on the platform s own libraries except for the most basic functions, but it still allows applications to be given a platform s look and feel. Swing does not replace the whole of the AWT functionality, so we ll generally be using classes from both in our programs. EE905-GUI-3 Creating a Window EE905-GUI-4
3 &UHDWLQJD:LQGRZ To use graphics, the first thing we need is a window to draw in. Here s a simple program that will create a window on the display: SimpleFrame.java Compile and Execution javac SimpleFrame.java java SimpleFrame Live Demo EE905-GUI-5 7KHSimpleFrame &ODVV class SimpleFrame extends JFrame { public SimpleFrame() { settitle("simpleframe"); setsize(300, 200); } This code defines a class called SimpleFrame, which is an extension of (i.e., inherits from) the JFrame class provided by Swing. The JFrame class is the standard class that provides a window. The method publicsimpleframe() is the constructor for the new class. It sets the title (displayed in the title bar of the window) and it sets the initial size of the window. You don t have to set the title, but you must set the size. Otherwise you get the JFrame s default size, which is zero by zero pixels and therefore not very useful. EE905-GUI-6
4 7KHmain 0HWKRG public static void main(string[] args) { SimpleFrame frame = new SimpleFrame(); frame.show(); } The main() method let us run SimpleFrame as a console application. It creates a new SimpleFrame object, and calls the object s show() method to display the window. New windows are not displayed until the show() method is called. This is so that you can create them and then draw in them before the user sees them. Then the main() method exits. You might expect this to terminate the program, but it doesn t. The window is left in control. EE905-GUI-7 &ORVLQJWKH:LQGRZ To make the program terminate, the obvious thing to do is to click the window s close box. But this doesn t work! The window does go away, but the program is still running - as you ll see from the absence of a Linux prompt in the console window. To make the program stop, you have to kill it by typing Control-C. Let s fix that... EE905-GUI-8
5 4XLWWLQJWKH3URJUDP The reason that the program doesn t quit when you close the window is that you don t always want it to. Your program might have several windows, for example, and it s unlikely that you d want the program to stop if you closed just one of them. Therefore, by default, windows can be closed and will go away, but the program will not stop. To make the window closure terminate the program, add this line in main() before the call to frame.show(). frame.setdefaultcloseoperation(jframe.exit_on_close); EE905-GUI-9 *LYLQJmain() LWV2ZQ&ODVV In the previous example, we put the main() method into the frame class. This works, but it s not the most natural way to do it because the frame class is not main() s natural home. (If there were many frames, which one would you put main() in?) Here s the program so far, but rearranged so that there s a top class to represent the program as well as the SimpleFrame class to represent the frame. See Graphics01.java in supplement. EE905-GUI-10
6 Panels EE905-GUI-11 $GG7ZR%XWWRQVLQWR:LQGRZ JPanel pane = new JPanel(); JButton button1 = new JButton("Click Me!"); pane.add(button1); JButton button2 = new JButton("Click Me Too!"); pane.add(button2); frame.getcontentpane().add(pane); (refer to Graphics02.java ) Create a new JPanel object A JPanel is a rectangular container for other graphics objects (widgets) Widgets added to a JPanel will be packed left to right and then top to bottom, like words in a paragraph Create two buttons, adding them to the JPanel. Add the JPanel to the frame object. EE905-GUI-12
7 )UDPHDQG3DQHO3DFNGLIIHUHQWO\ If we had added the buttons directly to the frame, the two buttons are still both there, but each has been made to be the full size of the window and the second one has been placed on top of the first. Demonstrate the difference. (refer to: Graphics03.java) That s why we use the JPanel to contain the buttons, and then pack just the JPanel into the frame. The JPanel s (default) layout method is called flow layout. EE905-GUI-13 )UDPHV8VH%RUGHU/D\RXW Actually, frames do some layout: by default, they use border layout. There are five areas: NORTH, SOUTH, EAST, WEST and CENTER. If you don t specify which area to put a widget in, it goes into the CENTER area (which is what has happened in the examples so far). If you put more than one widget into the same area, only the last one is visible (as we have seen). The following code adds a text label in the SOUTH area, with our twobutton JPanel still being placed in the CENTER area. (refer to Graphics04.java) JLabel label = new JLabel("Hi there!"); frame.getcontentpane().add(label,borderlayout.south); EE905-GUI-14
8 Event Handling EE905-GUI-15 (YHQWV An Event is an object in Java - a chunk of data stored in memory. One is created every time a button is clicked (or anything else happens, for that matter). To make your program respond to an event, you have to declare a listener object, which will contain a method that gets executed in response to the creation of the Event. EE905-GUI-16
9 /LVWHQHU Any object can be a listener object, provided you give its class two specific features: ƒ You must declare the class as one that implements ActionListener. ƒ You must declare a method within the class, of this form: public void actionperformed(actionevent event){... } The method name must be actionperformed; you can t just have any name of your choice. The following code adds some very minimal code to respond to a button click on the first button. (Refer to Graphics5.java) import java.awt.event.*; button1.addactionlistener(new Action()); class Action implements ActionListener { public void actionperformed(actionevent event) { Graphics05.label.setText("Thanks!"); } } EE905-GUI-17 $QRWKHUZD\WRJHW$SSOLFDWLRQWRHQG Refer to CloseableFrame.java in the supplement addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { System.exit(0); } }); EE905-GUI-18
10 )RQW Font class Five logical font names: ƒ SansSerif, Serif, Monospaced, Dialog, DialogInput System specific fonts available Font styles: ƒ Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD+Font.ITALIC Font sansb14 = new Font("SansSerif", Font.BOLD, 14); g.setfont(sansb14); EE905-GUI-19 &RORXU Color class Provides 13 standard colours e.g.: ƒ Color.black, Color.white, Color.red, Color.green, etc. Colours can also be defined by (red, green, blue) mix. e.g.: ƒ Color dullbluegreen = new Color(0, 128, 128); System colors can be used for portability, e.g.: ƒ SystemColor.window - background for windows ƒ SystemColor.windowBorder - Colour of window border frame ƒ SystemColor.windowText - Text colour inside windows Can use these colors to set e.g. current drawing colour: ƒ g.setcolor(color.red); or frame background: ƒ f.setbackground(systemcolor.window); EE905-GUI-20
1 6KDSH Within the paintcomponent() of a JPanel, use the supplied Graphics object g to draw Vast collection of methods, e.g.: drawstring(string str, int x, int y) drawline(int x1, int y1, int x2, int y2) drawpolygon(polygon p) fillpolygon(polygon p) Possible to draw images, but this is complicated by Java s support for downloading images across the network: see Image, Toolkit and MediaTracker classes EE905-GUI-21 (YHQW+DQGOLQJ([DPSOHV Live demo on ButtonFrame.java Live demo on MouseFrame.java EE905-GUI-22
12 Swing GUI Components EE905-GUI-23 9DVW6ZLQJ&RPSRQHQWV Vast array of GUI components: see Swing API (1.4) A visual index to the Swing component: here Including (as early as Swing 1.0.3) : ƒ JButton, JCheckbox, JCheckBoxMenuItem, JComboBox, JDialog, JEditorPane, JFileChooser, JLabel, JList, JMenu, JMenuBar, JMenuItem, JOptionPane, JPanel, JPasswordField, JPopupMenu, JProgressBar, JRadioButton, JRadioButtonMenuItem, JScrollBar, JScrollPane, JSlider, JTextArea, JTextField, JToolBar If these aren t enough, try e.g. Gamelan (http://www.developer.com/java/) to download additional contributed components Note: there are more components in later versions of Swing EE905-GUI-24
13 /D\RXW0DQDJHPHQW Every container has a layout manager. Java provides several ways to layout components automatically ƒ FlowLayout : Arranges components in a left-to-right flow, much like lines of text in a paragraph (default for JPanel ) ƒ BorderLayout : Lays out a container, arranging and resizing its components to fit in five regions: North, South, East, West, and Center (default for JFrame ) ƒ GridLayout : Lays out a container s components in a rectangular grid ƒ GridBagLayout : Flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size: tricky! Several others, plus write your own! C:\j2sdk1.4.0\tutorials\uiswing\mini\layout.html Layout Management Example: Calculator.java EE905-GUI-25 0RUH([DPSOHV See supplement Text Input: TextEditFrame.java Check Box: CheckBoxFrame.java Combo Box: ComboBoxFrame.java Menu: MenuFrame.java Dialog: DialogFrame.java EE905-GUI-26
14 Java Applets EE905-GUI-27 %DVLFVRI-DYD$SSOHWV An applet is a special kind of Java program that a Java-enabled browser can download from the internet and then run. Motivation behind applets: users would be freed from the hassles of installing software, and that they could access their software from any Java-enabled computer or device with an internet connection. Applets are embedded inside HTML page. The browser retrieves the class files from the internet (or from a directory on the user s machine) and automatically runs the applet. EE905-GUI-28
15 $Q([DPSOH$SSOHW Applications ƒ Main method: main() ƒ Example: Hello.java again Applets ƒ Example: HelloApplet.java ( HelloApplet.html ) ƒ Example: HelloApplet2.java ( HelloApplet2.html) Comparison of two by code analysis EE905-GUI-29 0DLQ0HWKRGVRIApplet &ODVV init(): Initialise applet Used for whatever initialization is needed for the applet. It works much like a constructor It is automatically called by the system when Java launches the applet for the first time. start(): Start or restart applet It is automatically called after Java calls the init method. paint(): Draw applet stop() : Stop applet It is automatically called when the user moves off the page on which the applet sits. destroy() : Release applet resources It is only called when the browser shuts down normally. Please refer to JDK API documentations EE905-GUI-30
16 6HFXULW\&RQFHUQVIRU$SSOHWV Applets (unlike applications) are restricted in what they can do. The applet security manager throws a SecurityException whenever an applet attempts to violate one of the access rules. Applets can normally do the following things: Showing images and playing sounds Getting keystrokes and mouse clicks from the user Sending user input back to the host from which they were loaded The restricted execution environment for applets is often called the sandbox. Applets playing in the sandbox cannot alter the user s system or spy on it. Be noted that applets are interpreted by JVM rather than CPU. Signed applets EE905-GUI-31 5XQ\RXU$SSOHWV To execute the applet, the following two steps need to be carried out: ƒ Compile your source files into class files ƒ Create an HTML file that tells the browser which class file to load first and how to size the applet. Before viewing the applet in a browser, you can test it in the applet viewer. ƒ at command line type in appletviewer followed by url) ƒ ƒ However, it shows you only the applet, not the surrounding HTML text And if an HTML file contains multiple applets, the applet viewer pops up multiple windows. To properly view the applet, you need a Java 2 enabled browsers. If the applet doesn t show up, your browser uses its built-in virtual machine, and you need to configure it to use the Java Plug-in instead. EE905-GUI-32
17 &RQYHUWLQJ$SSOLFDWLRQVWR$SSOHWV Easy and essentially all of the user interface code can stay the same. Steps: ƒ Make an HTML page with the appropriate tag to load the applet code. ƒ Supply a subclass of the JApplet class. Make this class public. ƒ Eliminate the main method in the application. Do not construct a frame window for the application (because applet is displayed inside browser). ƒ Move any initialization code from the frame window constructor to the init method of the applet. ƒ Remove the call to setsize for applets, sizing is done by HTML file. ƒ Remove the call to setdefaultcloseoperation. Applets terminate when the browser exits. ƒ If the application calls settitle, remove it because applets don t have title bar (but you can title the web page by using the HTML title tag). ƒ Don t call show. Applets are displayed automatically. Example: refer to Calculator.java and CalculatorApplet.java EE905-GUI-33 3DVVLQJ,QIRUPDWLRQWR$SSOHWV Applets can use parameters that are embedded in the HTML file. This is done via the HTML tag called param along with attributes. <applet code= AppletA.class width=200 height=200> <param name= font value= Arial /> <param name= size value= 20 /> </applet> public class AppletA extends JApplet { public void init() { String fontname = getparameter ( font ); int fontsize = Integer.parseInt(getParameter( size )); End of Part 3 EE905-GUI-34