The Java Swing Toolkit

Size: px
Start display at page:

Download "The Java Swing Toolkit"

Transcription

1 WHAT IS SWING?... 2 SIMPLE EXAMPLE... 3 HOW TO START A SWING APPLICATION... 4 LABELS, TEXT BOXES AND BUTTONS... 5 HANDLING BUTTON CLICK EVENTS... 6 Which Button?... 6 EVENT HANDLING IN GENERAL... 7 Using adapter classes... 8 IMAGES... 9 Images from the net COLOR FONTS CONTAINERS AND STRUCTURE JPanels and Borders ADDING COMPONENTS TO A JPANEL THE CONTAINMENT HIERARCHY TOP LEVEL CONTAINERS JROOTPANE AND COMPONENTS Using the glasspane LAYOUT MANAGERS BorderLayout GridBagLayout JTABBEDPANE JSPLITPANE MENUS, POPUPS ANDTOOLBARS MAKING A BASIC MENU MAKING THE MENU WORK ELABORATING MENUS POPUP MENUS MENU DESIGN ISSUES TOOLBARS SUBCLASSING WIDGETS... 22

2 WHAT IS SWING? The Swing toolkit is a group of packages which are used for creating GUI interfaces. With Swing you can create windows, labels, text boxes, radio buttons, scroll bars and so on. An alternative to Swing is the Abstract Windowing Toolkit, or AWT. This is abstract in the sense that you use ideas like buttons, which are an abstract version of the actual buttons present on native GUIs in Windows, Solaris and other OS's. The AWT started with JDK 1.0 AWT used OS native code to draw its widgets. Swing uses Java to do a lot of the drawing. AWT is said to be 'heavy-weight' (because it uses a lot of classes) whereas most classes in Swing are lightweight. Swing started in JDK 1.2. In most versions of the JDK, you cannot mix AWT and Swing. These brief notes are intended to explain what Swing is all about, and to provide brief code snippets to enable you to quickly write GUI interfaces which work in typical ways.they are not a complete reference - for that, look at the online API. This document only covers the simple widgets. Those which carry significant amounts of data, such as lists and tables, are covered by a separate document which involves MVC. Most of the code listing does not include import statements. Most IDEs will produce these for you.

3 SIMPLE EXAMPLE This displays a window: class Test { public static void main(string[] args) { JFrame frame=new JFrame("A Window"); frame.setbounds(0,0,400,200); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); A JFrame object is a typical window. The setbounds method controls the x and y co-ordinates of the top left of the window, in pixels, relative to the screen. The third and fourth parameters determine the width and height. The setdefaultcloseoperation controls what happens when the window's close button is clicked - EXIT_ON_CLOSE exits the application (the default is nothing happens). A JFrame is initially not shown - setvisible(true) changes that. Basic JFrame

4 HOW TO START A SWING APPLICATION Since Swing controls the user interface, it needs to handle keystrokes, mouse clicks and drags and so on. These are treated as events, and you write pieces of code called event handlers to control what happens when the user clicks a button and so on. This is described in details later on. When an application which uses Swing starts, an additional thread is started which receives and dispatches events to the appropriate handler. This event dispatching thread is additional to the initial application thread which runs main. However Swing code is not threadsafe. This means the thread of main and the eventdispatching thread are not synchronised, and deadlock between them is possible. This problem is solved if all code to create and run the UI is done in the event dispatching thread. A class calledswingutilities has a static method for doing this, which can be used like this, in code you would probably have in main: SwingUtilities.invokeLater(new Runnable() { public void run() { createandshowgui(); ); This defines an anonymous inner class which implements the Runnable interface, and passes an instance of that to the invokelater method. The createandshowgui is a method that you write, possibly in the class that has main. For example, the following does what the first piece of code did, but without the thread problem. It also sub-classes JFrame: class Test { public static void main(string[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createandshowgui(); ); static void createandshowgui() { MyFrame frame = new MyFrame("A Window"); class MyFrame extends JFrame { super(title); setbounds(0, 0, 400, 200); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); In the listings which follow, we are mostly concerned with the frame constructor, and sometimes extra methods in the MyFrame class for event-handling.

5 LABELS, TEXT BOXES AND BUTTONS A JLabel displays some text which the user cannot change. A JTextField is a text entry field which the user can type into. A JButton is a clickable button. Simple Swing widgets This is produced by the following (code in the class containing main is as the last listing): class MyFrame extends JFrame { super(title); setbounds(0, 0, 250, 100); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); setlayout(null); JLabel label = new JLabel("Enter a number"); add(label); label.setbounds(5, 5, 100, 20); JTextField textfield = new JTextField("1234"); add(textfield); textfield.setbounds(110, 5, 100, 20); JButton button = new JButton("OK"); add(button); button.setbounds(5, 30, 80, 20); setlayout(null); concerns the use of a layout manager, which is a software agent which controls how the components are laid out. The null means we do not want to use a layout manager, and we will position components ourselves. This is not a good idea, but it s a simple start. Then we instantiate a new JLabel, add it to the window, and use setbounds to size and position it. Similarly we make a text field, add it and position it, and the same for a JButton.

6 HANDLING BUTTON CLICK EVENTS When the button is clicked, it generates an ActionEvent object. This is dealt with as follows: 1. When we create the button, we tell it where it should send its ActionEvent objects when it is clicked. This is done using the addactionlistener method. 2. The object which receives the ActionEvents must implement the ActionListener interface. 3. That interface has just one method, called actionperformed. The actionperformed method will be executed when the button is clicked, so you write there what you want to happen when the button is clicked. This plan can be carried out in different ways - in particular, different choices of object for step 2. This is often done using anonymous inner classes, which is rather obscure syntax. A simpler approach is to have the container object - the JFrame - receive the ActionEvent clicks. As follows: class MyFrame extends JFrame implements ActionListener {.. as before.. JButton button = new JButton("OK"); add(button); button.setbounds(5, 30, 80, 20); button.addactionlistener(this); public void actionperformed(actionevent e) { System.out.println("You clicked"); Now our frame implements the ActionListener interface, which is the actionperformed method. We have told the button to addactionlistener this - so its ActionEvents will be sent to the frame object, and its actionperformed method is called. WHICH BUTTON? Suppose we have more than one button - which is usually the case. They will often call the same actionperformed method. How do we tell which button was clicked? The ActionEvent class has a getsource() method to tell us who produced the event. We need to make the buttons data members, not local: class MyFrame extends JFrame implements ActionListener { JButton okbutton, cancelbutton;.. as before.. okbutton = new JButton("OK"); add(okbutton); okbutton.setbounds(5, 30, 80, 20); okbutton.addactionlistener(this); cancelbutton = new JButton("Cancel"); add(cancelbutton); cancelbutton.setbounds(90, 30, 80, 20); cancelbutton.addactionlistener(this); public void actionperformed(actionevent e) { Object source = e.getsource(); if (source == okbutton) { System.out.println("OK"); if (source == cancelbutton) { System.out.println("Cancel");

7 EVENT HANDLING IN GENERAL ActionEvent is a sub-class of AWTEvent. This has a superclass with classes of types of events of different kinds - for example, a MouseEvent, a MouseWheelEvent, a KeyEvent and a WindowEvent, the latter happening when a window is closed, resized, restored and so on. These are all handled in a similar way. Their events are passed to an object which implements the appropriate Listener interface. A getsource() can distinguish events coming from different widgets. Widgets actually maintain a list of objects to notify. So when a button is clicked, it can notify a set of objects. This is why the method is addactionlistener rather than setactionlistener. Two examples follow. Firstly this outputs the x and y pixel positions of the mouse as it moves over the frame: class MyFrame extends JFrame implements MouseMotionListener {.. as before.. addmousemotionlistener(this); public void mousedragged(mouseevent e) { public void mousemoved(mouseevent e) { System.out.println(e.getX()+ " "+e.gety()); Second example - when the window close button is clicked, the user must enter q to quit. This is a useful approach, checking if the user really wants to quit, save work and so on: class MyFrame extends JFrame implements WindowListener {..as before.. setdefaultcloseoperation(jframe.do_nothing_on_close);.. as before.. addwindowlistener(this); public void windowopened(windowevent e) { public void windowclosing(windowevent e) { System.out.println("Enter q to quit"); Scanner scanner=new Scanner(System.in); String s = scanner.nextline(); if (s.equals("q")) System.exit(0); public void windowclosed(windowevent e) {

8 public void windowiconified(windowevent e) { public void windowdeiconified(windowevent e) { public void windowactivated(windowevent e) { public void windowdeactivated(windowevent e) { USING ADAPTER CLASSES In the last example, the WindowListener interface has seven methods, and we are only doing something in one of them. To make for less typing, we can use an instance of a sub-class of the abstract WindowAdapter, just implementing the methods we want to. This is often done by making the object to be an instance of an anonymous inner class - like this: addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { System.out.println("Enter q to quit"); Scanner scanner = new Scanner(System.in); String s = scanner.nextline(); if (s.equals("q")) { System.exit(0); ); This is in place of addwindowlistener(this); and the frame no longer implements WindowListener. Instead..new WindowAdapter().. defines an anonymous sub-class of WindowAdapter, and creates an instance of it to deal with the WindowEvents.

9 IMAGES Swing has a class called ImageIcon which can be used to place images on labels and other components. For example: super(title); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); ImageIcon icon = new ImageIcon("c:/temp/baby.jpg"); JLabel label = new JLabel(icon); add(label); pack(); This is very simple, but there is a problem in that an absolute pathname to the image file is given. The code above works if the file is in the folder called temp on drive c - but in a typical deployment of an application, you cannot place a file in a fixed folder on the user's computer. We need to be able to somehow place the file in the application and refer to it there. There are three steps to this: 1. Place the image file in a suitable folder within the folder holding the source code.java files for the relevant package. For example, this is in a package called test, so we could place the image in a sub-folder of test called images. 2. Use a classloader to get the location relative to where the class files will be loaded from: package test; Image on label Source code image placement in NetBeans import.. class Test {.. public static void main(string[] args) {.. class MyFrame extends JFrame { JPanel top, bottom; super(title); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); ClassLoader cldr = this.getclass().getclassloader(); java.net.url imageurl = cldr.getresource("test/images/baby.jpg"); ImageIcon icon = new ImageIcon(imageURL); JLabel label = new JLabel(icon); add(label); pack(); Here, cldr is the class loader which will load the MyFrame class file. Its getresource method gets a location URL for the file named baby.jpg, in the folder called images in the package called test. 3. When this is compiled (or Run in NetBeans), in the classes folder of the build folder, there will be a folder named test to hold the package, and it will contain the class file, and a sub-folder called image with the image file in it. If this is jar'd (in NetBeans, Run Clean and Build) this produces a.jar file (in NetBeans, in the dist folder) which contains the image file. Folders after compiling

10 IMAGES FROM THE NET Alternatively, image files can be downloaded from the net, very simply: class MyFrame extends JFrame {.. try { URL imageurl = new URL(" ImageIcon icon = new ImageIcon(imageURL); JLabel label = new JLabel(icon); add(label); catch (MalformedURLException ex) { Image from the net pack();

11 COLOR Color is a class, with objects representing colours. We can construct a new colour by supplying red, green and blue components as floats in the range 0 to 1, like Color c = new Color(1.0f, 0.5f, 0.1f); 1.0f is a float constant, while 1.0 is type double. Or there are a set of constant named colours, like Color c = Color.GREEN; Swing components have methods setbackground and setforeground to set the colours (not all components have backgrounds and foregrounds). For example: class MyFrame extends JFrame { Using Color.. as before.. JLabel label = new JLabel("Enter a number"); add(label); Color c1 = new Color(1.0f, 0.5f, 0.1f); label.setforeground(c1); label.setbounds(5, 5, 100, 20); JTextField textfield = new JTextField("1234"); Color c2 = Color.GREEN; textfield.setbackground(c2); add(textfield); textfield.setbounds(110, 5, 100, 20);

12 FONTS An instance of the Font class represents a font. The main issue is that fonts are installed locally, so there is no guarantee that a specific font will be available. This is addressed by having two kinds - 'logical' and 'physical'. The logical fonts are a basic set of generic fonts - Dialog, DialogInput, Monospaced, Serif and SansSerif. You can instantiate one of these fonts as for example Font font = new Font("Dialog", Font.PLAIN, 12); and then use the setfont method to apply it to a component, such as label.setfont(font); The same is true of the physical fonts, but you have to ensure that the font you want is actually available. A reasonable approach is to have a set of fonts which you would prefer to use, in order, and use a logical font as the fallback if none are present. For example: GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); String fontname = "SansSerif"; String f[] = ge.getavailablefontfamilynames(); String[] wantedfonts = {"Code2000","Linux Libertine","DejaVu Sans" ; boolean gotfont = false; for (int j = 0; j < wantedfonts.length; j++) { for (int i = 0; i < f.length; i++) { if (f[i].equals(wantedfonts[j])) { fontname = wantedfonts[j]; gotfont = true; break; Unicode font if (gotfont) break; Font font = new Font(fontName, Font.PLAIN, 16); JLabel label = new گڳڳڳڳڱڱJLabel("αβγδεζ in " + fontname); label.setfont(font); add(label); This example shows two other points. Firstly, since Java uses Unicode for characters and strings, it can display a very large set of characters. Secondly, such characters can be used in source code for identifiers and string constants. Whether you can see them depends on which font your editor uses in your IDE - which will be an option you can change. Otherwise you can represent Unicode characters as constants like \u0061 for lower case 'a'.

13 CONTAINERS AND STRUCTURE Swing provides various features to enable you to organise components in a frame as you want. We look at JPanels as a basic building block, borders, the idea of a containment hierarchy, the top-level containers, layout managers, tabbed panes and split panes. JPANELS AND BORDERS A JPanel is a rectangular area which can be used to divide a frame by adding the panels to the frame. We can also add panels to panels, making the layout structure as intricate as is needed. We need to take the layout manager into account. The default for a JFrame is BorderLayout, and for a JPanel, FlowLayout, which adds components in rows. But this can be changed by setlayout(). Borders can also be added to JPanels - and most components. To get a border, use a method from the static BorderFactory class. The idea is that if you use three thin blue borders in your application, in fact only one will be constructed by the BorderFactory, and you will share the instances. The example shows the use of a compound border, with the outer border being empty. This can be used to establish 'padding' around components: super(title); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); // make panels top = new JPanel(); bottom = new JPanel(); // set sizes top.setpreferredsize(new Dimension(100, 100)); bottom.setpreferredsize(new Dimension(100, 100)); // add to frame add(top, BorderLayout.NORTH); add(bottom, BorderLayout.SOUTH); // put labels in panels top.add(new JLabel("Top")); bottom.add(new JLabel("Bottom")); // make and set borders Border redborder=borderfactory.createlineborder(color.red, 1); Border blankborder=borderfactory.createemptyborder(5,5,5,5); Border joint = BorderFactory.createCompoundBorder(blankBorder, redborder); top.setborder(joint); pack(); ADDING COMPONENTS TO A JPANEL We can create a JPanel and add it to the window. Then we can create components and add them to the panel (not the window):.. as before.. // set up a panel on the left JPanel yellow = new JPanel(); add(yellow); yellow.setbounds(0,0,125,100); yellow.setbackground(color.yellow); // add a label to it JLabel label = new JLabel("Enter a number"); label.setbounds(5, 5, 100, 20); yellow.add(label);

14 // set up a panel on the right JPanel red = new JPanel(); add(red); red.setbounds(125,0,125,100); red.setbackground(color.red); // add a textfield to it JTextField textfield = new JTextField("1234"); red.add(textfield); textfield.setbounds(110, 5, 100, 20); Containment hierarchy THE CONTAINMENT HIERARCHY In the above example, the JFrame contains two JPanels, because we have added them. In turn, the left JPanel contains a JLabel, and the right contains a JTextField. Swing uses this concept in general, with all components being contained in other components. Only at the top of each containment tree do we find a top level container, which in this case is a JFrame. TOP LEVEL CONTAINERS There are three useful top level containers JFrame, JDialog and JApplet. The first we have already seen. A JDialog is suitable for use as a dialog box and is descibed later. A JApplet will contain an applet, normally inside a browser window. There is a fourth, but it is usually excluded from the useful list. This is a JWindow. This is a plain rectangle, with no title bar, re-sizing handles, nor close minimize restore buttons. So not useful. On JDK 7, on some platforms, you can have translucent and non-rectangular windows. See later. JROOTPANE AND COMPONENTS JFrame and the other top-level containers is actually slightly more complicated than it appears. In detail, JRootPane and elements A Jframe has a JRootPane A JFrame has glasspane and a Layered Pane A LayeredPane has a contentpane, and maybe a MenuBar Usually we are only interested in the contentpane -the area inside the window where things will be shown. When we place a JLabel in a JFrame, it is added to the contentpane: frame.getcontentpane().add(label); Since this is so common, the add method of JFrame does this for you, so you can just say frame.add(label); with the same effect. Menu bars are easy to use - they are described elsewhere. The glasspane usually does nothing. It can be used to intercept mouse events before they reach the frame components, and you can draw on the glasspane (and therefore over frame components), provided you make it visible. USING THE GLASSPANE For example, the following gets the glasspane, and make sit intercept mouse movements. In response it draws on the glasspane tracking the mouse. The mouse events interception only works if the glasspane is setvisible(); which might not be expected: Drawing on the glasspane class MyFrame extends JFrame implements MouseMotionListener {

15 Component glasspane;..as before.. glasspane = getglasspane(); glasspane.setvisible(true); glasspane.addmousemotionlistener(this); public void mousedragged(mouseevent e) { int lastmousex = -1; int lastmousey = -1; public void mousemoved(mouseevent e) { int mousex = e.getx(); // where's the mouse int mousey = e.gety(); if (lastmousex == -1) { // if first time, last mouse is here as well lastmousex = mousex; if (lastmousey == -1) { lastmousey = mousey; Graphics g = glasspane.getgraphics(); // get a graphics context g.drawline(lastmousex, lastmousey, mousex, mousey); lastmousex = mousex; //ready for next time lastmousey = mousey; This consumes the mouse event, and the underlying button does not receive it. If you want to pass it on, you have to work out if the mouse is over the button, and if so, construct a suitable event and send it on. See LAYOUT MANAGERS Previously we have used setbounds() to position components with pixel co-ordinates and sizes. This is not recommended. The size of a pixel depends on the resolution of the display, and so your components will be smaller on a higher resolution screen. Insead it is better to use a LayoutManager. There is a choice of these, and they place components in different patterns - or you can write your own. We will just look at two. BORDERLAYOUT This is the default for a JFrame. Components can be placed in one of five positions, named north south east west and center. For example: Using BorderLayout class MyFrame extends JFrame { super(title); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); JButton okbutton = new JButton("OK"); add(okbutton, BorderLayout.WEST); JButton cancelbutton = new JButton("Cancel"); add(cancelbutton, BorderLayout.EAST); pack();

16 We have not set a layout manager, so we get the default BorderLayout. We have not sized the frame or the components, but we have called pack(). This calculates the "preferred sizes" of the components, sizes them to that, positions them, and calculates the minimum size of the frame. The five locations may seem to be limiting. But you can add panels to the frame, then components to the panels, and so on. GRIDBAGLAYOUT Some say GridBagLayout is one of the more complicated layout managers, but it is very flexible and effective. Components are placed in cells in rows and columns. You use an instance of GridBagConstraints when you add a component. This has fields gridx and gridy which fix which column and row it goes in - top left cell is (0,0). You can fix the alignment with.anchor EAST or WEST and so on. For a large component, you can make it use more than one row or column using gridwidth or gridheight. And you can space out components using insets. For example: GridBagLayout setlayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.insets = new Insets(5, 5, 5, 5);// everything has a 5 pixel border JLabel label1 = new JLabel("Name"); gc.gridx = 0; // top left gc.gridy = 0; gc.anchor = GridBagConstraints.EAST; // aligned right add(label1, gc); // add it The whole thing is: super(title); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); setlayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.insets = new Insets(5, 5, 5, 5); // top row JLabel label1 = new JLabel("Name"); gc.gridx = 0; gc.gridy = 0; gc.anchor = GridBagConstraints.EAST; add(label1, gc); JTextField name = new JTextField(""); name.setpreferredsize(new Dimension(100, 20)); gc.gridx = 1; gc.gridy = 0; gc.anchor = GridBagConstraints.WEST; add(name, gc); // row 2 JLabel label2 = new JLabel("Date of birth"); gc.gridx = 0; gc.gridy = 1; gc.anchor = GridBagConstraints.EAST; add(label2, gc); JTextField dob = new JTextField(""); dob.setpreferredsize(new Dimension(100, 20)); gc.gridx = 1; gc.gridy = 1; gc.anchor = GridBagConstraints.WEST; add(dob, gc); JButton okbutton = new JButton("OK"); gc.gridx = 0; gc.gridy = 2; // row 3 gc.anchor = GridBagConstraints.CENTER; add(okbutton, gc); JButton cancelbutton = new JButton("Cancel");

17 gc.gridx = 1; gc.gridy = 2; gc.anchor = GridBagConstraints.CENTER; add(cancelbutton, gc); pack(); JTABBEDPANE A tabbed pane produces a set of panes accessible via a 'tab'. This means that a lot of interface can be there in a small area - though you can't see more than one at a time. The sequence is simply: 1. Construct a JTabbedPane JTabbedPane 2. Construct components, and add them as tabs to the tabbed pane. These might be JPanels 3. Add the Tabbed pane to the outer container. For example: JTabbedPane tabbedpane = new JTabbedPane(JTabbedPane.TOP); JPanel panel1 = new JPanel(); tabbedpane.addtab("one", panel1); JPanel panel2 = new JPanel(); tabbedpane.addtab("two", panel2);.. add(tabbedpane); and of course you would add components to the panels. As well as text labels for tabs, you can have icons as well. So if 'one' is an ImageIcon, you can say tabbedpane.addtab("",one, panel1); and so on. Icons for tab labels JSPLITPANE A JSplitPane object does what the name suggests - it splits a container into two parts, and has the functionality to allow the user to control the split. You would typically: 1. Make the things which would be the left and right components - typically, JPanels. You would probably add components to those two panels. 2. Construct the JSplitPane, with the two panels as arguments. 3. Add the JSplitPane to the enclosing container - the one you are splitting. For example - the left component will be a scroll pane enclosing a JList JScrollPane listscroller = new JScrollPane(list); and the right is just a JPanel: JSplitPane JPanel rightpane = new JPanel(); rightpane.setbackground(color.yellow); JLabel lab1= new JLabel("Right pane"); rightpane.add(lab1); Then make the split pane: JSplitPane splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listscroller, rightpane); and add it - this is in the constructor of a subclassed JFrame:

18 add(splitpane); Some code configures this, with obvious meaning: splitpane.setonetouchexpandable(true); splitpane.setdividerlocation(150); Dimension minimumsize = new Dimension(100, 50); listscroller.setminimumsize(minimumsize); rightpane.setminimumsize(minimumsize); For a three-way split, nest them. For example, you might split a frame vertically, then split the top pane horizontally.

19 MENUS, POPUPS ANDTOOLBARS MAKING A BASIC MENU Follow these steps 1. Make a menubar, and add it to the frame (or whatever) 2. Make a menu, and add it to the menubar 3. Make menu items, and add them to the menu Repeat steps two and three for as many menus as you want. For example: Basic menu JMenuBar menubar = new JMenuBar(); setjmenubar(menubar); JMenu menu1 = new JMenu("Menu One"); menubar.add(menu1); JMenuItem item1 = new JMenuItem("Option One"); menu1.add(item1); JMenuItem item2 = new JMenuItem("Option Two"); menu1.add(item2); JMenu menu2 = new JMenu("Menu Two"); menubar.add(menu2); JMenuItem item3 = new JMenuItem("Option Three"); menu2.add(item3); JMenuItem item4 = new JMenuItem("Option Four"); menu2.add(item4); MAKING THE MENU WORK JMenuItems are in fact sub-classed JButtons, and so they use the ActionListener interface and you can treat them like ordinary buttons. This means your JMenuItems would need to be data fields not local to the constructor, so the actionperformed can refer to them. So we modify the above:.. item1 = new JMenuItem("Option One"); menu1.add(item1); item1.addactionlistener(this);.. public void actionperformed(actionevent e) { Object source = e.getsource(); if (source==item1).. whatever ELABORATING MENUS You can add menuitems to menu bars. Or you can add menus to menus, giving submenus. You can have icons as well as text labels in menuitems. You can have a menu separator. You can have checkboxes and radio buttons in menus. Elaborated menu For example, where 'one' is an ImageIcon: JMenuBar menubar = new JMenuBar(); setjmenubar(menubar); JMenu menu1 = new JMenu("Menu One");

20 menubar.add(menu1); item1 = new JMenuItem("Option One"); menu1.add(item1); item1.addactionlistener(this); JMenuItem item2 = new JMenuItem("Option Two", two); menu1.addseparator(); menu1.add(item2); JCheckBox cb = new JCheckBox("Yes or no"); menu1.add(cb); POPUP MENUS Popup menus, which appear floating somewhere in a frame (uually where the mouse was clicked) are excellent. They involve less mouse movement than having to go up to the menu bar, and they can be context-dependent - that is, if the user right-clicks on a particular thing, they get a menu just relevant to that thing. You make a popup menu and add items to it very simply: popup = new JPopupMenu(); JMenuItem menuitem = new JMenuItem("A popup menu item"); popup.add(menuitem); JMenuItem menuitem2 = new JMenuItem("Another popup menu item"); popup.add(menuitem2); To make it work, you have to do two things - get the menu to pop up, and get responses to menu selections. The first is done using a mouse listener. For example: addmouselistener(this);.. public void mouseclicked(mouseevent e) { if (e.getbutton() == MouseEvent.BUTTON3) { popup.show(e.getcomponent(), e.getx(), e.gety()); which means the popup appears if they right-click. The e.getx() and gety mean the menu will appear where they clicked. To make the menu work - the JMenuItems are subclassed JButtons, so use actionlistener just as for menu bars. MENU DESIGN ISSUES Users often complain they cannot 'find' things. This happens when there is a large and complex menu, with many levels, and items are not logically placed. For example, in Word 2003 and before you inserted a header through View in the menu, which is hardly logical. Some suggestions are: 1. Order top level items as expected - File Edit..Help. In File have New, Open, Save, Save as, Close and Exit. This obviously depends on the application, but keep it as close to this - which users will expect - as possible. 2. Use separators to group items logically. 3. If your menus are four deep - find another way. TOOLBARS Toolbars are rows of buttons, which can 'float' in their own window, or will 'dock' at the edge of a container. Instantiate a JToolBar, make and add JButtons to it, then add the toolbar to a container using BorderLayout. The JButtons would normally show icons, but text is possible. The JButtons use actionperformed. For example:

21 ClassLoader cldr = this.getclass().getclassloader(); java.net.url imageurl = cldr.getresource("test/images/edit24.gif"); ImageIcon one = new ImageIcon(imageURL);.. JToolBar toolbar = new JToolBar("Tools"); JButton butt1 = new JButton(one);.. toolbar.add(butt1);.. add(toolbar, BorderLayout.NORTH); Initial toolbar Docked on the left Dragged to new window

22 SUBCLASSING WIDGETS You can set attribute such as fonts and colours for components. For an application you will be likely to want these to be consistent. You can do this by setting the attributes of each widget, but ideally you would have in effect a style sheet. One way to do this is to subclass a standard widget, giving the class the attributes that you want, and instantiating the subclass. For example, a JButton can be made to show text and an icon, and to display only that, and not a button 'body'. We can also set an alternative icon to be displayed when the mouse is rolled over the JButton. To use this consistently we can subclass JButton. All instances can share the same two icons, so these can be static fields. We can load these in a static initialisation block: Sub-classed JButtons class MyButton extends JButton { static ImageIcon red; static ImageIcon yellow; static { ClassLoader cldr = MyButton.class.getClassLoader(); java.net.url imageurl = cldr.getresource("test/images/red.gif"); red = new ImageIcon(imageURL); imageurl = cldr.getresource("test/images/yellow.gif"); yellow = new ImageIcon(imageURL); MyButton(String text) { super(text); seticon(red); setrollovericon(yellow); setcontentareafilled(false); setborderpainted(false); setfocuspainted(false); setcursor(new Cursor(Cursor.HAND_CURSOR));

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User CSE3461 Control Flow Paradigms: Reacting to the User Control Flow: Overview Definition of control flow: The sequence of execution of instructions in a program. Control flow is determined at run time by

More information

Introduction to the JAVA UI classes Advanced HCI IAT351

Introduction to the JAVA UI classes Advanced HCI IAT351 Introduction to the JAVA UI classes Advanced HCI IAT351 Week 3 Lecture 1 17.09.2012 Lyn Bartram lyn@sfu.ca About JFC and Swing JFC Java TM Foundation Classes Encompass a group of features for constructing

More information

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 143 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1 Java Swing based on slides by: Walter Milner Java Swing Walter Milner 2005: Slide 1 What is Swing? A group of 14 packages to do with the UI 451 classes as at 1.4 (!) Part of JFC Java Foundation Classes

More information

Part 3: Graphical User Interface (GUI) & Java Applets

Part 3: Graphical User Interface (GUI) & Java Applets 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 ƒ

More information

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords Goals By the end of this lesson, you should: Lecture 7 More GUI programming 1. Be able to write Java s with JTextField, JList, JCheckBox and JRadioButton components 2. Be able to implement a ButtonGroup

More information

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7 PROGRAMMING DESIGN USING JAVA (ITT 303) Graphical User Interface Unit 7 Learning Objectives At the end of this unit students should be able to: Build graphical user interfaces Create and manipulate buttons,

More information

Java: Graphical User Interfaces (GUI)

Java: Graphical User Interfaces (GUI) Chair of Software Engineering Carlo A. Furia, Marco Piccioni, and Bertrand Meyer Java: Graphical User Interfaces (GUI) With material from Christoph Angerer The essence of the Java Graphics API Application

More information

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest"

More information

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun! Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques

More information

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming

More information

Graphic User Interfaces. - GUI concepts - Swing - AWT

Graphic User Interfaces. - GUI concepts - Swing - AWT Graphic User Interfaces - GUI concepts - Swing - AWT 1 What is GUI Graphic User Interfaces are used in programs to communicate more efficiently with computer users MacOS MS Windows X Windows etc 2 Considerations

More information

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 12 A First Look at GUI Applications Chapter Topics 12.1 Introduction 12.2 Creating Windows 12.3 Equipping GUI Classes

More information

Tool Kits, Swing. Overview. SMD158 Interactive Systems Spring Tool Kits in the Abstract. An overview of Swing/AWT

Tool Kits, Swing. Overview. SMD158 Interactive Systems Spring Tool Kits in the Abstract. An overview of Swing/AWT INSTITUTIONEN FÖR Tool Kits, Swing SMD158 Interactive Systems Spring 2005 Jan-28-05 2002-2005 by David A. Carr 1 L Overview Tool kits in the abstract An overview of Swing/AWT Jan-28-05 2002-2005 by David

More information

Java Programming Lecture 6

Java Programming Lecture 6 Java Programming Lecture 6 Alice E. Fischer Feb 15, 2013 Java Programming - L6... 1/32 Dialog Boxes Class Derivation The First Swing Programs: Snow and Moving The Second Swing Program: Smile Swing Components

More information

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class. Q1. If you add a component to the CENTER of a border layout, which directions will the component stretch? A1. The component will stretch both horizontally and vertically. It will occupy the whole space

More information

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing Introduction to Graphical Interface Programming in Java Introduction to AWT and Swing GUI versus Graphics Programming Graphical User Interface (GUI) Graphics Programming Purpose is to display info and

More information

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 331 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing CSEN401 Computer Programming Lab Topics: Graphical User Interface Window Interfaces using Swing Prof. Dr. Slim Abdennadher 22.3.2015 c S. Abdennadher 1 Swing c S. Abdennadher 2 AWT versus Swing Two basic

More information

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling Handout 12 CS603 Object-Oriented Programming Fall 15 Page 1 of 12 Handout 14 Graphical User Interface (GUI) with Swing, Event Handling The Swing library (javax.swing.*) Contains classes that implement

More information

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages. 1 CS257 Computer Science I Kevin Sahr, PhD Lecture 14: Graphical User Interfaces Command-Line Applications 2 The programs we've explored thus far have been text-based applications A Java application is

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

Graphical User Interfaces. Comp 152

Graphical User Interfaces. Comp 152 Graphical User Interfaces Comp 152 Procedural programming Execute line of code at a time Allowing for selection and repetition Call one function and then another. Can trace program execution on paper from

More information

Chapter 12 GUI Basics

Chapter 12 GUI Basics Chapter 12 GUI Basics 1 Creating GUI Objects // Create a button with text OK JButton jbtok = new JButton("OK"); // Create a label with text "Enter your name: " JLabel jlblname = new JLabel("Enter your

More information

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming Objectives: Last revised 1/15/10 1. To introduce the notion of a component and some basic Swing components (JLabel, JTextField, JTextArea,

More information

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Swing UI by Vlad Costel Ungureanu for Learn Stuff User Interface Command Line Graphical User Interface (GUI) Tactile User Interface (TUI) Multimedia (voice) Intelligent (gesture recognition) 2 Making the

More information

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008 Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008 Announcements A3 is up, due Friday, Oct 10 Prelim 1 scheduled for Oct 16 if you have a conflict, let us know now 2 Interactive

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

Basicsof. JavaGUI and SWING

Basicsof. JavaGUI and SWING Basicsof programming3 JavaGUI and SWING GUI basics Basics of programming 3 BME IIT, Goldschmidt Balázs 2 GUI basics Mostly window-based applications Typically based on widgets small parts (buttons, scrollbars,

More information

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Prototyping a Swing Interface with the Netbeans IDE GUI Editor Prototyping a Swing Interface with the Netbeans IDE GUI Editor Netbeans provides an environment for creating Java applications including a module for GUI design. Here we assume that we have some existing

More information

Part I: Learn Common Graphics Components

Part I: Learn Common Graphics Components OOP GUI Components and Event Handling Page 1 Objectives 1. Practice creating and using graphical components. 2. Practice adding Event Listeners to handle the events and do something. 3. Learn how to connect

More information

AP CS Unit 11: Graphics and Events

AP CS Unit 11: Graphics and Events AP CS Unit 11: Graphics and Events This packet shows how to create programs with a graphical interface in a way that is consistent with the approach used in the Elevens program. Copy the following two

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT-V TWO MARKS QUESTION & ANSWER 1. What is the difference between the Font and FontMetrics class? Font class is used to set or retrieve the screen fonts.the Font class maps the characters of the language

More information

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Graphics. Lecture 18 COP 3252 Summer June 6, 2017 Graphics Lecture 18 COP 3252 Summer 2017 June 6, 2017 Graphics classes In the original version of Java, graphics components were in the AWT library (Abstract Windows Toolkit) Was okay for developing simple

More information

Chapter 1 GUI Applications

Chapter 1 GUI Applications Chapter 1 GUI Applications 1. GUI Applications So far we've seen GUI programs only in the context of Applets. But we can have GUI applications too. A GUI application will not have any of the security limitations

More information

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University March 10, 2008 / Lecture 8 Outline Course Status Course Information & Schedule

More information

Dr. Hikmat A. M. AbdelJaber

Dr. Hikmat A. M. AbdelJaber Dr. Hikmat A. M. AbdelJaber JWindow: is a window without a title bar or move controls. The program can move and resize it, but the user cannot. It has no border at all. It optionally has a parent JFrame.

More information

JLayeredPane. Depth Constants in JLayeredPane

JLayeredPane. Depth Constants in JLayeredPane JLayeredPane Continuing on Swing Components A layered pane is a Swing container that provides a third dimension for positioning components depth or Z order. The class for the layered pane is JLayeredPane.

More information

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything. Java - Applications C&G Criteria: 5.3.2, 5.5.2, 5.5.3 Java applets require a web browser to run independently of the Java IDE. The Dos based console applications will run outside the IDE but have no access

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

CSE 331. Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CSE 331. Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 331 Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT Lecturer: Michael Hotan slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer,

More information

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place. Chapter 8 Java continued CS3283 - Hugh Anderson s notes. Page number: 263 ALERT MCQ test next week This time This place Closed book CS3283 - Hugh Anderson s notes. Page number: 264 ALERT Assignment #2

More information

GUI Programming: Swing and Event Handling

GUI Programming: Swing and Event Handling GUI Programming: Swing and Event Handling Sara Sprenkle 1 Announcements No class next Tuesday My Fourth of July present to you: No quiz! Assignment 3 due today Review Collections: List, Set, Map Inner

More information

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in Lab 4 D0010E Object-Oriented Programming and Design Lecture 9 Lab 4: You will implement a game that can be played over the Internet. The networking part has already been written. Among other things, the

More information

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3 Chapter 8 Java continued MCQ test next week This time This place Closed book ALERT CS3283 - Hugh Anderson s notes. Page number: 263 CS3283 - Hugh Anderson s notes. Page number: 264 ALERT Last week Assignment

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) Layout Managment 1 Hello World Often have a static method: createandshowgui() Invoked by main calling invokelater private static void createandshowgui() { } JFrame frame

More information

BASICS OF GRAPHICAL APPS

BASICS OF GRAPHICAL APPS CSC 2014 Java Bootcamp Lecture 7 GUI Design BASICS OF GRAPHICAL APPS 2 Graphical Applications So far we ve focused on command-line applications, which interact with the user using simple text prompts In

More information

Chapter 14. More Swing

Chapter 14. More Swing Chapter 14 More Swing Menus Making GUIs Pretty (and More Functional) Box Containers and Box Layout Managers More on Events and Listeners Another Look at the Swing Class Hierarchy Chapter 14 Java: an Introduction

More information

PIC 20A GUI with swing

PIC 20A GUI with swing PIC 20A GUI with swing Ernest Ryu UCLA Mathematics Last edited: November 22, 2017 Hello swing Let s create a JFrame. import javax. swing.*; public class Test { public static void main ( String [] args

More information

CS 251 Intermediate Programming GUIs: Event Listeners

CS 251 Intermediate Programming GUIs: Event Listeners CS 251 Intermediate Programming GUIs: Event Listeners Brooke Chenoweth University of New Mexico Fall 2017 What is an Event Listener? A small class that implements a particular listener interface. Listener

More information

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC). The Abstract Windowing Toolkit Since Java was first released, its user interface facilities have been a significant weakness The Abstract Windowing Toolkit (AWT) was part of the JDK form the beginning,

More information

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Rui Moreira Some useful links: http://java.sun.com/docs/books/tutorial/uiswing/toc.html http://www.unix.org.ua/orelly/java-ent/jfc/

More information

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Graphics programming COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Overview Aims To provide an overview of Swing and the AWT To show how to build

More information

CHAPTER 2. Java Overview

CHAPTER 2. Java Overview Networks and Internet Programming (0907522) CHAPTER 2 Java Overview Instructor: Dr. Khalid A. Darabkh Objectives The objectives of this chapter are: To discuss the classes present in the java.awt package

More information

GUI in Java TalentHome Solutions

GUI in Java TalentHome Solutions GUI in Java TalentHome Solutions AWT Stands for Abstract Window Toolkit API to develop GUI in java Has some predefined components Platform Dependent Heavy weight To use AWT, import java.awt.* Calculator

More information

Systems Programming Graphical User Interfaces

Systems Programming Graphical User Interfaces Systems Programming Graphical User Interfaces Julio Villena Román (LECTURER) CONTENTS ARE MOSTLY BASED ON THE WORK BY: José Jesús García Rueda Systems Programming GUIs based on Java

More information

JAVA NOTES GRAPHICAL USER INTERFACES

JAVA NOTES GRAPHICAL USER INTERFACES 1 JAVA NOTES GRAPHICAL USER INTERFACES Terry Marris 24 June 2001 5 TEXT AREAS 5.1 LEARNING OUTCOMES By the end of this lesson the student should be able to understand how to get multi-line input from the

More information

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS Objec&ves RouleQe Assign 8: Refactoring for Extensibility Programming Paradigms Introduc&on to GUIs in Java Ø Event handling Nov 6, 2015 Sprenkle - CSCI209 1 Nov 6, 2015 Sprenkle - CSCI209 2 Assign 8:

More information

(Incomplete) History of GUIs

(Incomplete) History of GUIs CMSC 433 Programming Language Technologies and Paradigms Spring 2004 Graphical User Interfaces April 20, 2004 (Incomplete) History of GUIs 1973: Xerox Alto 3-button mouse, bit-mapped display, windows 1981:

More information

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing. COSC User Interfaces Module 3 Sequential vs. Event-driven Programming Example Programs DemoLargestConsole.java DemoLargestGUI.java Demo programs will be available on the course web page. GUI Program Organization

More information

GUI Design. Overview of Part 1 of the Course. Overview of Java GUI Programming

GUI Design. Overview of Part 1 of the Course. Overview of Java GUI Programming GUI Design Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh spring@imap.pitt.edu http://www.sis.pitt.edu /~spring Overview of Part 1 of the Course Demystifying

More information

1.00 Lecture 14. Lecture Preview

1.00 Lecture 14. Lecture Preview 1.00 Lecture 14 Introduction to the Swing Toolkit Lecture Preview Over the next 5 lectures, we will introduce you to the techniques necessary to build graphic user interfaces for your applications. Lecture

More information

Unit 7: Event driven programming

Unit 7: Event driven programming Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Unit 7: Event driven programming 1 1. Introduction 2.

More information

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline Sequential vs. Event-driven Programming Reacting to the user GUI Program Organization Let s digress briefly to examine the organization of our GUI programs We ll do this in stages, by examining three example

More information

Programming graphics

Programming graphics Programming graphics Need a window javax.swing.jframe Several essential steps to use (necessary plumbing ): Set the size width and height in pixels Set a title (optional), and a close operation Make it

More information

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming Objectives: Last revised March 2, 2017 1. To introduce the notion of a component and some basic Swing components (JLabel, JTextField,

More information

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver Building a GUI in Java with Swing CITS1001 extension notes Rachel Cardell-Oliver Lecture Outline 1. Swing components 2. Building a GUI 3. Animating the GUI 2 Swing A collection of classes of GUI components

More information

Graphical Interfaces

Graphical Interfaces Weeks 11&12 Graphical Interfaces All the programs that you have created until now used a simple command line interface, which is not user friendly, so a Graphical User Interface (GUI) should be used. The

More information

Chapter 13 GUI Basics. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved.

Chapter 13 GUI Basics. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. Chapter 13 GUI Basics 1 Motivations The design of the API for Java GUI programming is an excellent example of how the object-oriented principle is applied. In the chapters that follow, you will learn the

More information

Event Driven Programming

Event Driven Programming Event Driven Programming Part 1 Introduction Chapter 12 CS 2334 University of Oklahoma Brian F. Veale 1 Graphical User Interfaces So far, we have only dealt with console-based programs Run from the console

More information

Class 16: The Swing Event Model

Class 16: The Swing Event Model Introduction to Computation and Problem Solving Class 16: The Swing Event Model Prof. Steven R. Lerman and Dr. V. Judson Harward 1 The Java Event Model Up until now, we have focused on GUI's to present

More information

Widgets. Widgets Widget Toolkits. 2.3 Widgets 1

Widgets. Widgets Widget Toolkits. 2.3 Widgets 1 Widgets Widgets Widget Toolkits 2.3 Widgets 1 User Interface Widget Widget is a generic name for parts of an interface that have their own behavior: buttons, drop-down menus, spinners, file dialog boxes,

More information

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers Course Name: Advanced Java Lecture 19 Topics to be covered Java Swing Lists Trees Tables Styled Text Components Progress Indicators Component Organizers AWT to Swing AWT: Abstract Windowing Toolkit import

More information

Introduction. Introduction

Introduction. Introduction Introduction Many Java application use a graphical user interface or GUI (pronounced gooey ). A GUI is a graphical window or windows that provide interaction with the user. GUI s accept input from: the

More information

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Frames, GUI and events Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Introduction to Swing The Java AWT (Abstract Window Toolkit)

More information

Graphical User Interfaces in Java - SWING

Graphical User Interfaces in Java - SWING Graphical User Interfaces in Java - SWING Graphical User Interfaces (GUI) Each graphical component that the user can see on the screen corresponds to an object of a class Component: Window Button Menu...

More information

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain

More information

User interfaces and Swing

User interfaces and Swing User interfaces and Swing Overview, applets, drawing, action listening, layout managers. APIs: java.awt.*, javax.swing.*, classes names start with a J. Java Lectures 1 2 Applets public class Simple extends

More information

Java. GUI building with the AWT

Java. GUI building with the AWT Java GUI building with the AWT AWT (Abstract Window Toolkit) Present in all Java implementations Described in most Java textbooks Adequate for many applications Uses the controls defined by your OS therefore

More information

Building Graphical User Interfaces. GUI Principles

Building Graphical User Interfaces. GUI Principles Building Graphical User Interfaces 4.1 GUI Principles Components: GUI building blocks Buttons, menus, sliders, etc. Layout: arranging components to form a usable GUI Using layout managers. Events: reacting

More information

China Jiliang University Java. Programming in Java. Java Swing Programming. Java Web Applications, Helmut Dispert

China Jiliang University Java. Programming in Java. Java Swing Programming. Java Web Applications, Helmut Dispert Java Programming in Java Java Swing Programming Java Swing Design Goals The overall goal for the Swing project was: To build a set of extensible GUI components to enable developers to more rapidly develop

More information

Class 14: Introduction to the Swing Toolkit

Class 14: Introduction to the Swing Toolkit Introduction to Computation and Problem Solving Class 14: Introduction to the Swing Toolkit Prof. Steven R. Lerman and Dr. V. Judson Harward 1 Class Preview Over the next 5 lectures, we will introduce

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 29 Nov. 19, 2010 Swing I Event- driven programming Passive: ApplicaHon waits for an event to happen in the environment When an event occurs, the applicahon

More information

encompass a group of features for building Graphical User Interfaces (GUI).

encompass a group of features for building Graphical User Interfaces (GUI). Java GUI (intro) JFC Java Foundation Classes encompass a group of features for building Graphical User Interfaces (GUI). javax.swing.* used for building GUIs. Some basic functionality is already there

More information

Building Graphical User Interfaces. Overview

Building Graphical User Interfaces. Overview Building Graphical User Interfaces 4.1 Overview Constructing GUIs Interface components GUI layout Event handling 2 1 GUI Principles Components: GUI building blocks. Buttons, menus, sliders, etc. Layout:

More information

CS 251 Intermediate Programming GUIs: Components and Layout

CS 251 Intermediate Programming GUIs: Components and Layout CS 251 Intermediate Programming GUIs: Components and Layout Brooke Chenoweth University of New Mexico Fall 2017 import javax. swing.*; Hello GUI public class HelloGUI extends JFrame { public HelloGUI ()

More information

Packages: Putting Classes Together

Packages: Putting Classes Together Packages: Putting Classes Together 1 Introduction 2 The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic

More information

2110: GUIS: Graphical User Interfaces

2110: GUIS: Graphical User Interfaces 2110: GUIS: Graphical User Interfaces Their mouse had a mean time between failure of a week it would jam up irreparably, or... jam up on the table--... It had a flimsy cord whose wires would break. Steve

More information

Chapter 12 GUI Basics. Motivations. The design of the API for Java GUI programming

Chapter 12 GUI Basics. Motivations. The design of the API for Java GUI programming Chapter 12 GUI Basics 1 Motivations The design of the API for Java GUI programming is an excellent example of how the object-orientedoriented principle is applied. In the chapters that follow, you will

More information

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling Overview Building Graphical User Interfaces Constructing GUIs Interface components GUI layout Event handling 4.1 GUI Principles AWT and Swing Components: GUI building blocks. Buttons, menus, sliders, etc.

More information

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions. Parts of a Contract Syntax - Method signature Method name Parameter list Return type Semantics - Comments Preconditions: requirements placed on the caller Postconditions: what the method modifies and/or

More information

Graphical Interfaces

Graphical Interfaces Weeks 9&11 Graphical Interfaces All the programs that you have created until now used a simple command line interface, which is not user friendly, so a Graphical User Interface (GUI) should be used. The

More information

JAVA NOTES GRAPHICAL USER INTERFACES

JAVA NOTES GRAPHICAL USER INTERFACES 1 JAVA NOTES GRAPHICAL USER INTERFACES Terry Marris July 2001 8 DROP-DOWN LISTS 8.1 LEARNING OUTCOMES By the end of this lesson the student should be able to understand and use JLists understand and use

More information

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events Objectives Event Handling Animation Discussion of Roulette Assignment How easy/difficult to refactor for extensibility? Was it easier to add to your refactored code? Ø What would your refactored classes

More information

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo Widgets Overview Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo Widget Widget is a generic name for parts of an interface that have their own behavior: buttons, progress

More information

CS11 Java. Fall Lecture 4

CS11 Java. Fall Lecture 4 CS11 Java Fall 2006-2007 Lecture 4 Today s Topics Interfaces The Swing API Event Handlers Inner Classes Arrays Java Interfaces Classes can only have one parent class No multiple inheritance in Java! By

More information

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali GUI and its COmponent Textfield, Button & Label By Iqtidar Ali GUI (Graphical User Interface) GUI is a visual interface to a program. GUI are built from GUI components. A GUI component is an object with

More information

Widgets. Widgets Widget Toolkits. User Interface Widget

Widgets. Widgets Widget Toolkits. User Interface Widget Widgets Widgets Widget Toolkits 2.3 Widgets 1 User Interface Widget Widget is a generic name for parts of an interface that have their own behavior: buttons, drop-down menus, spinners, file dialog boxes,

More information

The AWT Event Model 9

The AWT Event Model 9 The AWT Event Model 9 Course Map This module covers the event-based GUI user input mechanism. Getting Started The Java Programming Language Basics Identifiers, Keywords, and Types Expressions and Flow

More information