Graphical User Interfaces in Java

Size: px
Start display at page:

Download "Graphical User Interfaces in Java"

Transcription

1 COMP16121 Graphical User Interfaces in Java COMP16121 Sean Bechhofer

2 Why? With the dominance of windows-based systems, Graphical User Interfaces (GUIs) are everywhere. They have a number of useful characteristics. They can allow us to present large amounts of information in a concise manner. They can make it easier to allow the user to interact with the state of an application and control its execution. They can look much nicer than command line programs. 2

3 Example GUIs GUIs are not always the answer to our problems though, and there are issues relating to their use that we need to be aware of: Human factors Interface design 3

4 Coming up... Java has a wealth of support for building GUIs. GUIs rely on a number of features of the Java language that we have not yet seen in depth. This includes extending existing classes; In our initial examples, we will also meet a number of new concepts relating to GUIs: Frames, Windows, Components, Containers. The next few lectures will introduce these topics. By the end of these lectures you should know enough to be able to build simple Graphical User Interfaces. 4

5 Aside: Swing vs. AWT The original versions of Java contained components for windowing known as the AWT (Abstract Window Toolkit). Swing provides replacements for most of the AWT graphical components, but a number of non-component AWT classes (such as Container) are still in use. It is recommended that you do not mix Swing and AWT components in a single application as this is likely to cause problems. Swing is slightly more complicated, but is now more widely used. We will use Swing in our examples. 5

6 Example: HelloWord In the best traditions of programming, our first example will be a Hello World program. This simply makes a window appear on the screen with a message. HelloWorld 6

7 HelloWorld The example program does the following: Create an object representing a new window which will be displayed on the screen; The constructor method adds a label to the window; Display the window. To understand this we need to understand how to add things to windows which appear on the screen. This is done using Containers and Components. 7

8 Components and Containers The elements we use to build up GUIs are known as Components. Components include Buttons, Labels, Text Fields and other things that appear on GUIs. All components are kinds of java.awt.component. We often refer to the components that appear on GUIs as widgets. Some Components are Containers these are objects that contain other components. Containers allow us to build up GUIs in sections or pieces which are then assembled together. An example of a container is JPanel. 8

9 Components Labels List Buttons Text Box 9

10 Top Level Containers and JFrame Swing provides a number of special kinds of container known as Top Level Containers, one of which is JFrame. A JFrame is a window that typically has decorations such as a border, a title, and buttons for closing and iconifying the window. Applications with a GUI will in general use at least one frame. Otherwise it s probably not a Graphical User Interface!! 10

11 JFrame Anatomy Window Title Window controls added by host windowing system Menu bar Frame content 11

12 JFrame JFrame also allows us to add menu bars or toolbars to windows. The position of menu bars may be left up to the host windowing systems. For example, on the Macintosh, menu bars tend to appear at the top of the desktop rather than at the top of the window. 12

13 A Simple Frame Example import javax.swing.jframe; public class SimpleFrame { /* Main method to drive the program */ public static void main(string [] args) { JFrame theframe = new JFrame(); theframe.settitle("a Frame"); theframe.setsize( 300, 200 ); theframe.setvisible( true ); } // main } // SimpleFrame Our first example creates a new Frame, gives it a title, then asks it to display. SimpleFrame 13

14 Extending Existing Classes Class libraries such as JFrame provide code that we can reuse in our applications. We don t want to have rewrite our own classes for basic GUI components. There are a number of different ways that we can use JFrame. For example, we could have an instance variable which is a JFrame, and then delegate any operations relating to the window to this instance variable. This would work, but in this case an alternative is to extend an existing class. Instance of our new class are then also instances of JFrame. Extending allows us to provide a specialisation of a class. We can reuse the code in the class and add additional instance variables or methods that perform some particular task for our application. 14

15 Extending Existing Classes The class that is extended is known as the superclass or base class. The class that is doing the extending is known as the subclass or derived class. The derived class can directly use public methods and instance variables. In our example, the statement at the beginning of the class declaration states that we are extending JFrame. import java.awt.container; import javax.swing.jlabel; import javax.swing.jframe; public class HelloWorld extends JFrame {... } // HelloWorld We can now use methods from JFrame within our class. 15

16 HelloWorld main() Our class has a main() method that drives the program. /* Main method to drive the program */ public static void main(string [] args) { HelloWorld thehelloworld = new HelloWorld(); thehelloworld.setvisible( true ); } // main The first thing we do is create a new instance of the HelloWorld class using the constructor. 16

17 HelloWorld constructor /* Constructor */ public HelloWorld() settitle("hello World"); /* Get the contents of the frame and add a label to it */ Container contents = getcontentpane(); contents.add(new JLabel("Hello World!")); /* Specify appropriate behaviour when the window is closed */ setdefaultcloseoperation(exit_on_close); /* pack the frame */ pack(); } // HelloWorld The constructor allows us to create new instances of our HelloWorld class Before any of the code in the method is executed, the no-argument constructor of the base class will be called. This could take care of any initialisation that might be required for the instance variables that come with JFrame. 17

18 HelloWorld constructor /* Constructor */ public HelloWorld() settitle("hello World"); /* Get the contents of the frame and add a label to it */ Container contents = getcontentpane(); contents.add(new JLabel("Hello World!")); /* Specify appropriate behaviour when the window is closed */ setdefaultcloseoperation(exit_on_close); /* pack the frame */ pack(); } // HelloWorld A method from the base class is used to set the title of the window. This is the title that the host windowing system will place on the title bar of the window. This is also usually also the name that is shown when the window is reduced to an icon. 18

19 HelloWorld constructor /* Constructor */ public HelloWorld() settitle("hello World"); /* Get the contents of the frame and add a label to it */ Container contents = getcontentpane(); contents.add(new JLabel("Hello World!")); /* Specify appropriate behaviour when the window is closed */ setdefaultcloseoperation(exit_on_close); /* pack the frame */ pack(); } // HelloWorld By default, a JFrame is empty, and contains no components. The JFrame has an area known as the content pane, which contains the contents of the window. When we add components to a JFrame, we don t add them to the JFrame itself, but instead add them to the content pane. We get the contentpane of the JFrame, which is a Container Note the use of a method from the base class. 19

20 HelloWorld constructor /* Constructor */ public HelloWorld() settitle("hello World"); /* Get the contents of the frame and add a label to it */ Container contents = getcontentpane(); contents.add(new JLabel("Hello World!")); /* Specify appropriate behaviour when the window is closed */ setdefaultcloseoperation(exit_on_close); /* pack the frame */ pack(); } // HelloWorld We then add a label to the content pane, using a new instance of JLabel JLabel provides areas on a GUI for short pieces of text or images The user cannot interact with labels. 20

21 HelloWorld constructor /* Constructor */ public HelloWorld() settitle("hello World"); /* Get the contents of the frame and add a label to it */ Container contents = getcontentpane(); contents.add(new JLabel("Hello World!")); /* Specify appropriate behaviour when the window is closed */ setdefaultcloseoperation(exit_on_close); /* pack the frame */ pack(); } // HelloWorld The above lines tell the window how it should behave when the user closes it. In this case, we want the application to exit. Another option would be to simply close the window, but keep the object representing the window we might want to show it again later. 21

22 HelloWorld constructor /* Constructor */ public HelloWorld() settitle("hello World"); /* Get the contents of the frame and add a label to it */ Container contents = getcontentpane(); contents.add(new JLabel("Hello World!")); /* Specify appropriate behaviour when the window is closed */ setdefaultcloseoperation(exit_on_close); /* pack the frame */ pack(); } // HelloWorld Finally, we call the pack() operation. This causes the window to be resized to fit the various constraints of its components. In this case, it means that the window will be resized to fit the dimensions of the label that we have added. 22

23 HelloWorld main() /* Main method to drive the program */ public static void main(string [] args) { HelloWorld thehelloworld = new HelloWorld(); thehelloworld.setvisible( true ); } // main The HelloWorld constructor doesn t do anything about displaying the window that we have created.? Why not? In order to make the window visible, we call setvisible( true ) This will make the window visible, and then bring it to the front. HelloWorld 23

24 Coursework Task Reimplement the HelloWorld GUI example to greet the world in French (or some other language). 24

25 Layout Our first example simply added a single component to the container. If we want to add more than one component, we need to specify how those components should be layed out on the screen. In Swing, layout is controlled by a LayoutManager. There are a number of different layout managers provided in the system libraries. Three simple ones are: FlowLayout GridLayout BorderLayout These are sufficient to build quite sophisticated interfaces. 25

26 Example: HelloSolarSystem Our next example is an extension of the HelloWorld program. This will make a window appear on the screen with a number of messages. We will use a FlowLayout to control how the messages appear on the screen. In FlowLayout, the components are simply added one after the other, and flow across the screen. HelloSolarSystem 26

27 Example: HelloSolarSystem import java.awt.container; import java.awt.flowlayout; import javax.swing.jlabel; import javax.swing.jframe; public class HelloSolarSystem extends JFrame { /* Constructor */ public HelloSolarSystem() settitle("hello Solar System"); /* Get the contents of the frame and add labels to it */ Container contents = getcontentpane(); /* Set the layout manager */ contents.setlayout( new FlowLayout() ); contents.add(new JLabel("Hello Mercury!")); contents.add(new JLabel("Hello Venus!")); contents.add(new JLabel("Hello Earth!")); contents.add(new JLabel("Hello Mars!")); contents.add(new JLabel("Hello Jupiter!")); contents.add(new JLabel("Hello Saturn!")); contents.add(new JLabel("Hello Uranus!")); contents.add(new JLabel("Hello Neptune!")); contents.add(new JLabel("Hello Pluto!")); setdefaultcloseoperation(exit_on_close); pack(); } // HelloSolarSystem 27

28 HelloSolarSystem constructor /* Constructor */ public HelloSolarSystem() settitle("hello Solar System"); /* Get the contents of the frame and add labels to it */ Container contents = getcontentpane(); /* Set the layout manager */ contents.setlayout( new FlowLayout() ); contents.add(new JLabel("Hello Mercury!")); contents.add(new JLabel("Hello Venus!")); contents.add(new JLabel("Hello Earth!")); contents.add(new JLabel("Hello Mars!")); contents.add(new JLabel("Hello Jupiter!")); contents.add(new JLabel("Hello Saturn!")); contents.add(new JLabel("Hello Uranus!")); contents.add(new JLabel("Hello Neptune!")); contents.add(new JLabel("Hello Pluto!")); setdefaultcloseoperation(exit_on_close); pack(); } // HelloSolarSystem The constructor sets the layout manager for the content pane to be a new instance of FlowLayout. 28

29 HelloSolarSystem constructor /* Constructor */ public HelloSolarSystem() settitle("hello Solar System"); /* Get the contents of the frame and add labels to it */ Container contents = getcontentpane(); /* Set the layout manager */ contents.setlayout( new FlowLayout() ); contents.add(new JLabel("Hello Mercury!")); contents.add(new JLabel("Hello Venus!")); contents.add(new JLabel("Hello Earth!")); contents.add(new JLabel("Hello Mars!")); contents.add(new JLabel("Hello Jupiter!")); contents.add(new JLabel("Hello Saturn!")); contents.add(new JLabel("Hello Uranus!")); contents.add(new JLabel("Hello Neptune!")); contents.add(new JLabel("Hello Pluto!")); setdefaultcloseoperation(exit_on_close); pack(); } // HelloSolarSystem We then add a number of labels, one for each planet. The rest of the constructor is as before. The main() method is similar. HelloSolarSystem 29

30 Coursework Task In early chapters we went from HelloWorld to HelloMyFamily. In this task we do the same, but provide a GUI that greets (some some subset of) your family. Use a FlowLayout to control the layout of the GUI. 30

31 Running HelloSolarSystem As you can see, this produces rather ugly results.? What would happen with 100 planets? Can we improve on this? HelloSolarSystem 31

32 Improving Layout The FlowLayout manager simply puts all the components one after another and flows them across the container. Each component takes as much space as it needs. With lots of components, this doesn t always produce nice looking results. Comp1 Comp2 Comp3 Comp4 Comp5 Comp6 Components flow across Container 32

33 Improving Layout: GridLayout An alternative Layout Manager is GridLayout. GridLayout lays out components in a rectangular grid. The grid is divided into equal sized rectangles, with each component put into one rectangle. The grid is sized so that the biggest component will fit. This is one of the reasons why we call pack() to give the container a chance to calculate all the appropriate sizes. Comp1 Comp2 Comp3 Comp4 Comp5 Comp6 33

34 HelloSolarSystemGrid /* Constructor */ public HelloSolarSystemGrid() settitle("hello Solar System"); /* Get the contents of the frame and add labels to it */ Container contents = getcontentpane(); /* Set the layout manager */ contents.setlayout( new GridLayout( 0, 3, 10, 10 ) ); contents.add(new JLabel("Hello Mercury!")); contents.add(new JLabel("Hello Venus!")); contents.add(new JLabel("Hello Earth!")); contents.add(new JLabel("Hello Mars!")); contents.add(new JLabel("Hello Jupiter!")); contents.add(new JLabel("Hello Saturn!")); contents.add(new JLabel("Hello Uranus!")); contents.add(new JLabel("Hello Neptune!")); contents.add(new JLabel("Hello Pluto!")); setdefaultcloseoperation(exit_on_close); pack(); } // HelloSolarSystem The Constructor is the same apart from the setting of the layout manager Note that we will have to change the import headers. 34

35 Running HelloSolarSystemGrid Much nicer! The components are laid out in a grid as expected. The constructor we used for GridLayout is: GridLayout(int rows, int cols, int hgap, int vgap) If we supply an argument of 0 for rows or columns, this means any number. So in our example, we ve fixed the number of columns at 3 as many rows as necessary will be added to display all the components. HelloSolarSystemGrid 35

36 Coursework Task Repeat, this time using a GridLayout to control the layout of the GUI. Experiment with different values for rows and columns to see what the effects are. Write a program that shows a times table using a JLabel to represent each number. Use a GridLayout to control the layout. 36

37 Beyond Simple Text We ve seen JLabel used to display a piece of text. A JLabel can also be used to display an image: This can help in providing more interesting GUIs. /* Get the contents of the frame and add a label to it */ Container contents = getcontentpane(); contents.add(new JLabel( new ImageIcon( "smiley.jpg" ) ); We create a new ImageIcon object and pass that to the JLabel. HelloShark 37

38 Aside: LayoutManager as a parameter The constructors for HelloSolarSystem and HelloSolarSystemGrid are identical apart from the creation of the FlowLayout or GridLayout. /* Constructor */ public HelloSolarSystem() settitle("hello Solar System"); /* Get the contents of the frame and add labels to it */ Container contents = getcontentpane(); /* Set the layout manager */ contents.setlayout( new FlowLayout() ); contents.add(new JLabel("Hello Mercury!")); contents.add(new JLabel("Hello Venus!")); contents.add(new JLabel("Hello Earth!")); contents.add(new JLabel("Hello Mars!")); contents.add(new JLabel("Hello Jupiter!")); contents.add(new JLabel("Hello Saturn!")); contents.add(new JLabel("Hello Uranus!")); contents.add(new JLabel("Hello Neptune!")); contents.add(new JLabel("Hello Pluto!")); setdefaultcloseoperation(exit_on_close); /* Constructor */ public HelloSolarSystemGrid() settitle("hello Solar System"); /* Get the contents of the frame and add labels to it */ Container contents = getcontentpane(); /* Set the layout manager */ contents.setlayout( new GridLayout( 0, 3, 10, 10 ) ); contents.add(new JLabel("Hello Mercury!")); contents.add(new JLabel("Hello Venus!")); contents.add(new JLabel("Hello Earth!")); contents.add(new JLabel("Hello Mars!")); contents.add(new JLabel("Hello Jupiter!")); contents.add(new JLabel("Hello Saturn!")); contents.add(new JLabel("Hello Uranus!")); contents.add(new JLabel("Hello Neptune!")); contents.add(new JLabel("Hello Pluto!")); setdefaultcloseoperation(exit_on_close); pack(); } // HelloSolarSystem pack(); } // HelloSolarSystemGrid We could move the creation of the layout manager out of this method and pass it in as an argument to the constructor this would give us some extra flexibility and make it easier to experiment with other layouts. 38

39 Summary Elements of GUIs Windows and Frames JFrame Components JLabel Containers Extending Existing Classes Reusing classes and adding new functionality Layout Management FlowLayout GridLayout 39

40 COMP16121 Interacting with GUIs COMP10081 Sean Bechhofer

41 Interacting with a GUI The HelloWorld and HelloSolarSystem examples provide GUIs that the user doesn t really interact with. We can t press buttons to change the state or make the application do anything (other than close down). Swing provides a number of components that allow us to build interactive interfaces E.g. Buttons to start or stop an application The next example is a simple stop clock timer that the user can stop and start by pressing a button. StopClock 41

42 Event Driven Programming The programs that you have seen up to now are procedural: the flow of execution is controlled by loops and decision statements. E.g. do A, then B, then while some condition is true, do C. This is known as procedural programming In event driven programming, code is executed when events occur. This is appropriate when programs need to react to external events, such as the action of a user 42

43 Event Driven Programming A Procedural Program is like a recipe It gives a series of instructions that are to be performed in sequence. Making a burger: 1. Turn the grill on 2. Grill burger until cooked 3. Turn the grill off 4. Butter bun 5. Put burger on bun 6. If cheeseburger, add cheese 7. Add salad 8. Add top of bun Of course there may be many more steps with complicated loop or control structures. But the instructions are followed in sequence. 43

44 Event Driven Programming In the burger example, we know exactly what we re going to do, and what s going to happen There s no need to react to external events. Consider a burger van: Sam Larry 44

45 Burgers Larry doesn t know what the orders are going to be at the beginning of the evening, so can t know beforehand what he has to do. Instead, he reacts to external events (orders) as they come in from Sam Within the handling of each particular order, he may then follow a simple procedural path (for example, someone might order a cheese burger) 45

46 Events Java provides a rich event model: a framework for handling events. In particular this includes libraries for events relating to GUIs. There are many different kinds of event. Here, we will be interested in ActionEvent ActionEvents occur when a user performs some kind of action on a GUI, for example pressing a button. We say that the event has been raised. Events can also represent other things: The user typed something at the keyboard A window has been closed The state of an object has been changed. 46

47 Sources and Listeners In the Java Event model, actions involve at least two participants The source produces an event, The listener receives the event. There is also an object that represents the event itself. 47

48 Sauces and Listeners Consider our burger van example The customer tells Sam what she wants. Sam shouts this out, creating an order The order is thus passed to Larry, who (hopefully) then cooks the appropriate food. Customer Order Make Choices Shout Order Order to Larry Sam Larry 48

49 Sources and Listeners A general pattern for this is as follows User Action ActionEvent Object Trigger event Generate event Notify listener Source Object Register with Source Listener Object Note that the listener must register with the source, telling it that it is interested in receiving events. 49

50 In our example, Sam is playing the role of a widget on a user interface. Widgets can be the source of events Larry plays the role of an event listener, an object that reacts to events as they are raised. 50

51 Events In the Java Event model, events are represented as objects. This means that the object can carry around some state with it For example, we can find out the object that caused the event to happen (the source)? Why would we want to know about the source? 51

52 Interfaces Interfaces in Java allow us to specify particular methods that we want classes to implement. The interface advertises the fact that instances of the class will supply some particular methods. A class that implements the interface then has to provide code for the methods named. Interfaces are like protocols They specify some agreed behaviour 52

53 Implementing Interfaces For example, the ActionListener interface has a single method: public void actionperformed( ActionEvent e ) If a class implements this interface, instances of the class will be able to respond in some appropriate manner when they receive ActionEvents. Because the class implements the interface, instances can be registered as listeners with objects such as JButton, that are sources of ActionEvents. 53

54 Designing the StopClock There are (at least) two things we need to think about when designing our Stop Clock class The information that the stop clock holds What the clock will look like on the screen What information do we show? What controls will the clock have? The two are obviously related We can t display information that the clock isn t holding! 54

55 Class Design What information should the clock hold? When it was started. When it was stopped. Whether it is running. These can all be represented using instance variables. For the first two, we can use a Date. The third is a boolean value. 55

56 GUI What should the clock look like? When building GUIs, it s often useful to sketch something out on paper first. 56

57 StopClock instance variables public class StopClock extends JFrame implements ActionListener {... /* Local instance variables */ private boolean isrunning = false; private Date startdate; private Date stopdate; private JLabel starttimejlabel = new JLabel( "Not started" ); private JLabel stoptimejlabel = new JLabel( "Not started" ); private JLabel elapsedtimejlabel = new JLabel( "Not started" );... } Private instance variables hold the state of the clock isrunning, startdate, stopdate We will display the values using labels, so we also have variables that represent the labels used on the clock, and provide them with initial values. 57

58 StopClock constructor public class StopClock extends JFrame implements ActionListener {... public void actionperformed( ActionEvent evt ) {... }... } The class header tells us that the class is going to implement ActionListener. We must then provide code for the required actionperformed () method. If we don t provide the method required by the interface, the compiler will report an error. 58

59 StopClock actionperformed() public void actionperformed( ActionEvent evt ) { if (! isrunning) { /* Start the clock */ startdate = new Date(); starttimejlabel.settext( "" + startdate ); stoptimejlabel.settext( "Running..." ); elapsedtimejlabel.settext( "Running..." ); isrunning = true; // Need to pack again because label size may have changed pack(); } else { /* Stop the clock and show the updated times */ stopdate = new Date(); stoptimejlabel.settext( "" + stopdate ); long elapsedmilliseconds = ( stopdate.gettime() - startdate.gettime() ); elapsedtimejlabel.settext( "" + elapsedmilliseconds / ); isrunning = false; // Need to pack again because label size may have changed pack(); } } // actionperformed If the clock isn t running, start it and make a note of the start time. Otherwise, stop the clock and update the display. 59

60 Running StopClock StopClock 60

61 StopClock Sources and Listeners What happens in the stop clock? evt Press Button Generate event Event passed to listener actionperformed( evt ) startstopjbutton thestopclock startstopjbutton.addactionlistener( this ) When the button is pressed, a new ActionEvent object is created and passed to the StopClock object. The actionperformed() method is then invoked with the event as argument. 61

62 Who calls the method? Within our StopClock class, we defined a method actionperformed() that was never explicitly called. However it does get called sometime during the execution of the program if the button gets pressed. This is a common feature of event-driven programming The methods you write may not be called explicitly within your code. This can make such programs hard to debug hard to test But where is the method called? 62

63 Threads: Parallel Execution Consider a busy lecturer He has many things to do in a day: Write a paper Mark some work Give a lecture Keep up with Important s may get missed He may be writing collaboratively Instead, he can (appear to) perform the tasks in parallel He can only do one thing at a time (he s a man). He could do one after the other, but that might cause problems What he s actually doing though, is switching between them. 63

64 Threads: Parallel Execution We have grown used to being able to perform many tasks simultaneously with computers. Several programs running at the same time What s usually happening though is that each program has its own process, and the resources of the central processor are shared between the processes. There are various strategies for dividing time between processes. The swapping between processes is rapid enough for you not to notice this (most of the the time) In Java, we have the notion of threads, which allow a single program to perform a number of tasks. 64

65 Threads: Main Thread When a Java program starts, the virtual machine (VM) creates the main thread. This executes the main() method, along with any method calls there might be within the body. When the thread reaches the end of the body, the thread terminates. If the main thread was the only thread, then the virtual machine ends the program. Otherwise, the program will continue to run until all threads have terminated. Up to now, the programs you have been writing have had a single thread. So the programs end when the main thread gets to the end of the main body. The situation is a little different when we begin to use GUI components. 65

66 Threads: GUI Thread When a program creates a window on the screen, the virtual machine creates a new thread -- the GUI thread. This thread actually spends much of its time asleep. When the user does something interesting (e.g. presses a button), the operating systems tell the VM, and the VM wakes up the GUI thread. The GUI thread then checks to see if the event really was interesting, and if so, executes the appropriate code. Once it s done, the GUI thread goes back to sleep again. Note that the processor isn t necessarily executing tasks in parallel, but will (usually) be swapping between the threads. Again though, this is so rapid, we don t notice this. 66

67 ... imports...! /**! * Simple frame with a single button.! <a href="mailto:sean.bechhofer@manchester.ac.uk">sean Bechhofer</a>! */! public class Button extends JFrame implements ActionListener {! private JButton thebutton = new JButton( "Press Me!" );! /* Constructor */! public Button() {!!settitle("one Button");!!/* Get the contents of the frame and add a label to it */!!Container contents = getcontentpane();!!contents.add( thebutton );!!thebutton.addactionlistener(this);!!/* Specify appropriate behaviour when the window is closed */!!setdefaultcloseoperation(exit_on_close);!!/* pack the frame */!!pack();! } // OneButton! public void actionperformed( ActionEvent evt ) {!!System.out.println("Pressed!");! }! /* Main method to drive the program */! public static void main(string [] args) {!!Button thebutton = new Button();!!theButton.setVisible( true );! } // main! } // OneButton! 67

68 Threads Java s system libraries provide a number of classes that allow us to explicitly create and manage threads. What kind of issues might come up? For the programs that we are creating, and for our GUI programs, we don t need to worry about this, and can happily allow the VM to take care of our threading needs. 68

69 StopClock with a Split time Now, we decide that we want to be able to record split times while the clock is running. We can add a second button for this When it is pressed, the clock continues to run, but updates to display the value of the split time. StopClockSplit 69

70 StopClockSplit changes We need to add another label and another button. We need to change the constructor in order to add the field and button in the appropriate place. The first half of actionperformed() will be (almost) the same. 70

71 StopClockSplit actionperformed() When the clock is running, we now have a problem. The user can either press Start/Stop, to stop the clock (as before), or can press Split to record a split time (but leave the clock running). These two actions should have different consequences. The StopClock will be registered as a listener with both buttons, but has a single actionperformed() method. How do we know which button has been pressed? 71

72 ActionEvent sources As we ve seen, in the Java Event Model, events are represented by objects. In our example, instances of ActionEvent are used to represent actions such as the user pressing a button. These objects carry information around with them. So for example, we can ask an event for it s source -- the object that caused the event to be raised. This is done by calling the getsource() method on the event object. In our example, the source of the event object will be the JButton that was pressed. This then allows us to check which button was pressed, and take appropriate action. 72

73 Running StopClockSplit StopClockSplit 73

74 Coursework Task Take the StopClock example and change the code to provide a split time button. When the split time button is pressed, the clock should continue to run but the split or elapsed time should be displayed. The split button can be pressed any number of times when the clock is running, with the elapsed time updating each time it is pressed. 74

75 Summary Events and the Java Event Model Event Sources Event Listeners Implementing Interfaces ActionListener Multiple sources, one listener ActionEvent Threads 75

76 COMP16121 Entering Information & Layout COMP10081 Sean Bechhofer

77 Interacting with a GUI In our previous example, we provided the user with the opportunity to interact with a GUI by pressing buttons. Up to now, the only way that we ve been able to pass information or data into a program has been via arguments to main(). Now we re going to add components to an interface that allow the user to enter data. Our example will be an interface to the GCD code that we have already seen. 77

78 JTextField Our new GUI will allow the user to enter some data This is done using text fields. JTextField is a component that displays some text. Unlike JLabel, however, the user can interact with the text field and can enter new values. 78

79 GCD instance variables public class GCD extends JFrame implements ActionListener {... private JTextField number1jtextfield = new JTextField( 20 ); private JTextField number2jtextfield = new JTextField( 20 ); private JTextField resultjtextfield = new JTextField( 20 );... } We have three text fields that will hold the text to be displayed. When creating a text field we can specify how big it should be this then allows the interface to size itself appropriately. The field will start off with an empty string as content. It s also possible to provide a JTextField with some initial value: JTextField myfield = new JTextField( "hello" ); 79

80 GCD constructor public GCD() { settitle("gcd"); Container contents = getcontentpane(); contents.setlayout( new GridLayout( 0, 1 ) ); contents.add( new Label( "Number 1" ) ); contents.add( number1jtextfield ); contents.add( new Label("Number 2" ) ); contents.add( number2jtextfield ); JButton computejbutton = new JButton( "Compute" ); contents.add( computejbutton ); computejbutton.addactionlistener( this ); contents.add( new Label( "GCD of Number 1 and Number 2" ) ); contents.add( resultjtextfield ); /* Specify appropriate behaviour when the window is closed */ setdefaultcloseoperation( EXIT_ON_CLOSE ); pack(); } // GCD The text fields are added to the GUI just like any other components. 80

81 GCD actionperformed() public void actionperformed(actionevent e) { int number1 = Integer.parseInt( number1jtextfield.gettext() ); int number2 = Integer.parseInt( number2jtextfield.gettext() ); int thegcd = greatestcommondivisor( number1, number2 ); resultjtextfield.settext( "" + thegcd ); } // actionperformed In actionperformed(), we can get the values that the user has entered into the text fields, and then compute the GCD based on those values. Note that as the result of gettext() is a String, we need to parse the string to an int before we can process it. This is similar to the original example where the arguments were passed in from the command line Once we ve calculated the GCD, we can then set the value of the result field. 81

82 Running GCD GCD 82

83 Coursework Task Provide a GUI that allows you to input three numbers and calculate their GCD. 83

84 Enabling and Disabling Components Components like buttons and text fields allow the user to interact with them We can press buttons or enter text into text fields Sometimes in a GUI we might want to disable a component. For example, in a mailer, we might not want the user to be able to send a message unless a valid mail address has been entered into the To: field. We could do this by: Allowing the user to press the Send button, but raising an error if the mail address is invalid Disabling the Send button until a valid mail address has been given. Java Components can be enabled and disabled through the setenabled( boolean ) method. 84

85 Disabling Text Fields In our GCD example, it doesn t make any sense for the user to be able to type text into the result field. We can prevent this happening by disabling it.? A disabled JTextField seems a bit like a JLabel. Why have both? GCDDisabled 85

86 Coursework Task Reimplement StopClock with a split time making the following changes: Use JTextField instead of JLabel to display the start/stop date and elapsed time. Change the behaviour of the split time button so that it is disabled when the clock isn t running. 86

87 JTextArea A JTextField is good for input or display of a single line of text. If we want to display more than one line, a JTextArea is appropriate. An example using a JTextArea is an application that displays a times table. 87

88 TimesTable instance variables public class TimesTable extends JFrame implements ActionListener {... private JTextField multiplierjtextfield = new JTextField( 5 ); private JTextArea displayjtextarea = new JTextArea( 15, 20 );... } The TimesTable GUI has a single text field for input of a value, and a text area to display the results of calculating the table. When we create a text area, we say how many rows and columns we expect it to have again as with the text fields, this allows the layout manager to work out how much space it should give the text area. 88

89 BorderLayout The TimesTable GUI is going to use a third layout manager that we haven t yet seen BorderLayout. This is slightly more complicated than FlowLayout and GridLayout, but provides more flexibility. Combinations of FlowLayout, GridLayout and BorderLayout will allow us to build quite sophisticated interfaces. 89

90 BorderLayout In BorderLayout, the container is divided into five areas: North, South, East, West and Center North West Center East South When we add a component to a container that s using a BorderLayout, we say which area we want the component to appear in: Constants from the BorderLayout class are used to indicate this. contents.add( mycomponent, BorderLayout.NORTH ) 90

91 TimesTable constructor public TimesTable() { settitle("times Table"); Container contents = getcontentpane(); contents.setlayout(new BorderLayout()); contents.add( multiplierjtextfield, BorderLayout.NORTH ); contents.add( displayjtextarea, BorderLayout.CENTER ); JButton displayjbutton = new JButton( "Display ); contents.add( displayjbutton, BorderLayout.SOUTH ); displayjbutton.addactionlistener( this ); pack(); } // TimesTable The constructor is similar to those we ve seen before, but here, when we add the components, we tell the layout manager which area of the layout we want them to appear in. Order is no longer important. We could add the button first and it would still appear at the bottom of the screen. With BorderLayout we have to be careful that we don t add two components to the same area. 91

92 TimesTable actionperformed() public void actionperformed( ActionEvent e ) { displayjtextarea.settext( "" ); int multiplier = Integer.parseInt( multiplierjtextfield.gettext() ); displayjtextarea.append( " \n" ); displayjtextarea.append( " Times table for " + multiplier + "\n" ); displayjtextarea.append( " \n" ); for (int thisnumber = 1; thisnumber <= 10; thisnumber = thisnumber + 1) displayjtextarea.append( " " + thisnumber + " x " + multiplier + " = " + thisnumber * multiplier + "\n" ); displayjtextarea.append( " \n" ); } // actionperformed In actionperformed(), the first thing we do is clear the text area by using settext() to set it to be the empty string. settext() will replace any existing text. We can then append text to the text area using append(). This doesn t replace the area, but adds the text on to the end. We can include new lines in the text by including the newline character "\n". 92

93 TimesTable actionperformed() public void actionperformed( ActionEvent e ) { displayjtextarea.settext( " ); int multiplier = Integer.parseInt( multiplierjtextfield.gettext() ); displayjtextarea.append( " \n" ); displayjtextarea.append( " Times table for " + multiplier + "\n" ); displayjtextarea.append( " \n" ); for ( int thisnumber = 1; thisnumber <= 10; thisnumber = thisnumber + 1 ) displayjtextarea.append( " " + thisnumber + " x " + multiplier + " = " + thisnumber * multiplier + "\n" ); displayjtextarea.append( " \n" ); } // actionperformed A for loop is used to append the times table to the text area. 93

94 Running TimesTable TimesTable 94

95 JPanel: Building things up from pieces So far, all our interfaces have been relatively simple. We ve been able to use a single container to hold the pieces that we wanted. Often, however, our interfaces will be made up of a number of different parts or panels, that we want to combine together into one big piece. For example, think of Mozilla s mail interface. In this case, having a single container and layout manager won t be enough. Java provides a lightweight container known as JPanel that allows us to do build things up. A JPanel is a blank area that we can add things to. The JPanel can then be added to other containers. 95

96 GCDWithPanels constructor public GCDWithPanels() { settitle("gcd"); Container contents = getcontentpane(); contents.setlayout(new GridLayout(0, 1)); JPanel numberfieldspanel = new JPanel(); numberfieldspanel.setlayout( new GridLayout( 0, 2 ) ); contents.add( numberfieldspanel ); numberfieldspanel.add( new JLabel( "Number 1" ) ); numberfieldspanel.add( new JLabel( "Number 2" ) ); numberfieldspanel.add( number1jtextfield ); numberfieldspanel.add( number2jtextfield );... } // GCDWithPanels In the constructor, we build a number of different instances of JPanel. Each one has its own layout manager, and panels can then be added to other panels or the contents of the JFrame. Note that the order in which we add things here doesn t matter. The panel is added to the container before the labels and fields are added to the panel. Calling pack() at the end of the constructor makes sure that everything gets sized properly. 96

97 Running GCDWithPanels GCDWithPanels 97

98 Anatomy of GCDWithPanels numberfieldspanel with a 2-column grid layout contents with a 1- column grid layout buttonandresultpanel with a 2-column grid layout. Note that the Compute button is the same size as the combined label and field on the right hand side resultpanel with a 1-column grid layout 98

99 Information Overload! In our TimesTable example, we created a JTextArea that was big enough for the text that we wanted to display: private JTextArea displayjtextarea = new JTextArea( 15, 20 );? What happens if we put more than 15 lines of text into this? We can test this by changing the interface. We add a field that allows the user to input the size of table required and then change the termination condition of the for loop. private JTextField tablesizejtextfield = new JTextField(5); int tablesize = Integer.parseInt(tableSizeJTextField.getText()); for ( int thisnumber = 1; thisnumber <= tablesize; thisnumber = thisnumber + 1 ) displayjtextarea.append( " " + thisnumber + " x " + multiplier + " = " + thisnumber * multiplier + "\n" ); 99

100 Running TimesTable Once the text area is full, the text gets lost and doesn t appear on the screen. We can move the cursor off the bottom, but we still can t see anything. A solution to this is to use a Scroll Bar. TimesTable2 100

101 Scroll Bars Scroll Bars are often used in windowing applications when components are too big to fit into the available space. They serve a number of purposes: They allow the user to navigate (scroll) the area to find the right place They provide an indication of where we are in the text They give an indication of how much text is hidden the smaller the bar, the smaller the proportion of the text that is being shown. 101

102 Scroll Bars This scrollbar is telling me that I m at the top of the text and I m seeing around 10% of what there is. 102

103 JScrollPane JScrollPane is a component that provides a scrollable wrapper around a component. If the component will fit into the available space, then (by default) nothing happens and no scroll bars are shown. If the component is too big, the JScrollPane will provide scrollbars that allow you to see all the text. 103

104 TimesTableScroll constructor public TimesTableScroll() {... contents.add( multiplierjtextfield, BorderLayout.NORTH ); contents.add( new JScrollPane( displayjtextarea ), BorderLayout.CENTER );... } // TimesTableScroll The constructor is the same as before, except this time we create a new JScrollPane containing the JTextField and add that to the contents. 104

105 Running TimesTableScroll Now we can scroll down to see all the results of the table. TimesTableScroll 105

106 Coursework Task Implement a GUI that gives an interface to the Three Weights problem that you saw in Chapter 3. The GUI should allow you to enter three values for the weights, and will then display in a text area the possible weights that could be measured using the given values. 106

107 Containment Hierarchies Containers like JPanel allow us to build up nested collections of components. In order to appear on the screen, every GUI component must be part of a containment hierarchy. A containment hierarchy is a tree of components that has an instance of a Top Level Container (such as JFrame) as its root. 107

108 Summary Components for displaying and entering text JTextField JTextArea More sophisticated layout management BorderLayout Building up interfaces in pieces JPanel JScrollPane 108

109 COMP16121 Multiple Windows & Models COMP10081 Sean Bechhofer

110 More than one Window So far, all our programs have used a single window (or frame) This doesn t have to be the case We can have a number of different windows open at the same time. To demonstrate this, we ll extend our GCD example to allow the user to open up another window. GCDWithNew 110

111 GCDWithNew changes As with the StopClock example, we add a new button to the window. The class is changed to add buttons as instance variables We also change the constructor to add the button to the screen and register the GCDWithNew object with the button as a listener. 111

112 GCDWithNew actionperformed() public void actionperformed(actionevent e) { if ( e.getsource() == computejbutton ) { int number1 = Integer.parseInt(number1JTextField.getText()); int number2 = Integer.parseInt(number2JTextField.getText()); int thegcd = greatestcommondivisor(number1, number2); resultjtextfield.settext("" + thegcd); } else if ( e.getsource() == newjbutton ) { GCDWithNew newone = new GCDWithNew(); newone.setvisible( true ); } } // actionperformed The code computing the GCD is the same. However, this is only executed if the Compute button was pressed. If the New button is pressed, we create a new object and then ask it to display on the screen. Recall that the constructor doesn t make the window display. 112

113 Running GCDWithNew GCDWithNew 113

114 Problem I The new window opens up directly on top of the old one. This is because we haven t said anything about where we expect the window to appear By default the window appears in the top left hand corner A solution would be to tell the new window that it should open up in a slightly different place. 114

115 Locations We can solve this problem by: Getting the location of the current window Setting the location of the new window to be a position relative to the location of the current window. We can get the location of a window using method: public Point getlocation() We can set the location of a window using method: public void setlocation( Point p ) Point is a class from the Java libraries that represents a pair of (x, y) coordinates. GCDWithNew2 115

116 Problem II What happens when we close one of the windows? All of the windows disappear and the program exits. This is exactly how we told the application to behave! public GCDWithNew2() {... /* Specify appropriate behaviour when the window is closed */ setdefaultcloseoperation( EXIT_ON_CLOSE );... } // GCDWithNew This means that the application terminates when any of the windows are closed.? Why might this be a problem? 116

117 Setting the Default Close Operation In our code we have been using EXIT_ON_CLOSE as the default action. This means that the entire application quits An alternative is to use DISPOSE_ON_CLOSE /* Specify appropriate behaviour when the window is closed */ setdefaultcloseoperation( DISPOSE_ON_CLOSE ); This means that the window will be hidden, then the object representing the frame will be disposed of. If we do this, it means that when one window is closed, the application will continue to run, and other windows will still be there. GCDWithNew3 117

118 When does the application terminate? With the use of EXIT_ON_CLOSE, we can be sure that the application will terminate when a window is closed. With DISPOSE_ON_CLOSE, as long as we have been careful about the creation of our windows and listener objects, the application will terminate when all the windows have been closed. The GUI thread(s) will terminate and the virtual machine will end the program. Recall our earlier discussion of threads 118

119 A Simple Log Book application Your logbook is used to record information as you work. In this example, we provide a GUI where messages can be typed into a window and then collected together in a single log. We can open separate windows for different tasks. The GUI has: A field for a label A text area for the message Buttons for Log and New actions. LogGUI 119

120 LogBook import java.text.simpledateformat; import java.util.date; /** A class that records information. */ public class LogBook { private String logname; private String log; private SimpleDateFormat dateformat; /* Constructor */ public LogBook( String alogname ) { logname = alogname; dateformat = new SimpleDateFormat( "hh:mm:ss" ); log = ""; } }... The LogBook has a name There is also an instance of SimpleDateFormat This is a helper class from the Java libraries that can print out Date objects in a nice way. 120

121 LogBook /** Log a message. */ public void logmessage( String label, String message ) { Date now = new Date(); String logmessage = "Time: " + dateformat.format( now ) + "\n" + "Label: " + label + "\n"+ "Note: " + message; /* Add the message to the log */ log = log + logmessage + "\n"; /* Display the message */ System.out.println( " " ); System.out.println( logmessage ); System.out.println( " " ); } There is a method on LogBook that can be called when somebody wants to log a message. The method takes a label and the message. The message is printed out to the console along with the time. 121

122 LogGUI public class LogGUI extends JFrame implements ActionListener {... /* The LogBook that we will send messages to */ private LogBook logbook; } public LogGUI( LogBook alogbook ) { logbook = alogbook;... } // LogGUI... LogGUI provides us with a window where we can log messages. An instance of LogGUI has a reference to a LogBook This is passed in to the constructor. 122

123 LogGUI public void actionperformed( ActionEvent e ) { if ( e.getsource() == logbutton ) { /* Log the message */ logbook.logmessage( labelfield.gettext(), messagetextarea.gettext() ); /* Now clear the text */ messagetextarea.settext(""); } else if ( e.getsource() == newbutton ) { /* Create a new GUI with the same logbook */ LogGUI newloggui = new LogGUI( logbook ); newloggui.setvisible( true ); } } // actionperformed If the Log button is pressed, then the text that has been typed into the text area is passed to the room object s logmessage() method. This will result in the message being printed out on the console. We then clear the text area ready for the next message. 123

124 LogGUI public void actionperformed( ActionEvent e ) { if ( e.getsource() == logbutton ) { /* Log the message */ logbook.logmessage( labelfield.gettext(), messagetextarea.gettext() ); /* Now clear the text */ messagetextarea.settext(""); } else if ( e.getsource() == newbutton ) { /* Create a new GUI with the same logbook */ LogGUI newloggui = new LogGUI( logbook ); newloggui.setvisible( true ); } } // actionperformed If the New button is pressed, then we create a new instance of LogGUI, but pass in the same LogBook instance. This means that any messages sent from the new window will be sent to the same LogBook instance. LogGUI 124

125 Multiple GUIs, one object What we re seeing here is a situation where we have more than one window or GUI manipulating a single object, sometimes referred as the model. We re also seeing that the state of the GUI may be held indirectly by other objects It does not necessarily have to be held as direct instance variables of the GUI class itself. LogGUI LogGUI LogBook 125

COMP16121 Sample Code Lecture 1

COMP16121 Sample Code Lecture 1 COMP16121 Sample Code Lecture 1 Sean Bechhofer, University of Manchester, Manchester, UK sean.bechhofer@manchester.ac.uk 1 SimpleFrame 1 import javax.swing.jframe; 2 3 public class SimpleFrame { 4 5 /*

More information

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau List of Slides 1 Title 2 Chapter 13: Graphical user interfaces 3 Chapter aims 4 Section 2: Example:Hello world with a GUI 5 Aim 6 Hello world with a GUI 7 Hello world with a GUI 8 Package: java.awt and

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

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

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

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

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

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

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

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

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

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

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 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

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

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

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

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

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

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

Agenda. Container and Component

Agenda. Container and Component Agenda Types of GUI classes/objects Step-by-step guide to create a graphic user interface Step-by-step guide to event-handling PS5 Problem 1 PS5 Problem 2 Container and Component There are two types of

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

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

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs What is Widget Layout? Laying Out Components Positioning widgets in their container (typically a JPanel or a JFrame s content pane) Basic idea: each widget has a size and position Main problem: what if

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

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

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

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

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

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

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

Window Interfaces Using Swing. Chapter 12

Window Interfaces Using Swing. Chapter 12 Window Interfaces Using Swing 1 Reminders Project 7 due Nov 17 @ 10:30 pm Project 6 grades released: regrades due by next Friday (11-18-2005) at midnight 2 GUIs - Graphical User Interfaces Windowing systems

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

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation KF5008 Program Design & Development Lecture 1 Usability GUI Design and Implementation Types of Requirements Functional Requirements What the system does or is expected to do Non-functional Requirements

More information

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University Java Swing Recitation 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University Announcements Project 8 is out Milestone due on Dec 3rd, 10:00 pm Final due on Dec 10th, 10:00 pm No classes,

More information

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs are divided into classes 7 Class: public class 8 Class:

More information

Graphical User Interfaces (GUIs)

Graphical User Interfaces (GUIs) CMSC 132: Object-Oriented Programming II Graphical User Interfaces (GUIs) Department of Computer Science University of Maryland, College Park Model-View-Controller (MVC) Model for GUI programming (Xerox

More information

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1 Datenbank-Praktikum Universität zu Lübeck Sommersemester 2006 Lecture: Swing Ho Ngoc Duc 1 Learning objectives GUI applications Font, Color, Image Running Applets as applications Swing Components q q Text

More information

Laying Out Components. What is Widget Layout?

Laying Out Components. What is Widget Layout? Laying Out Components Interior Design for GUIs What is Widget Layout? Positioning widgets in their container (typically a JPanel or a JFrame s content pane) Basic idea: each widget has a size and position

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

17 Hello world 18 Type: String: literal 19 Standard API: System: out.println() 20 Hello world 21 Statement 22 Statement: simple statements are ended w

17 Hello world 18 Type: String: literal 19 Standard API: System: out.println() 20 Hello world 21 Statement 22 Statement: simple statements are ended w List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs are divided into classes 7 Class: public class 8 Class:

More information

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014 Introduction to GUIs Principles of Software Construction: Objects, Design, and Concurrency Jonathan Aldrich and Charlie Garrod Fall 2014 Slides copyright 2014 by Jonathan Aldrich, Charlie Garrod, Christian

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

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

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS Glossary of Terms 2-4 Step by Step Instructions 4-7 HWApp 8 HWFrame 9 Never trust a computer

More information

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) ) COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) ) Course Evaluations Please do these. -Fast to do -Used to

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

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

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

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

Graphical User Interfaces. Swing. Jose Jesus García Rueda

Graphical User Interfaces. Swing. Jose Jesus García Rueda Graphical User Interfaces. Swing Jose Jesus García Rueda Introduction What are the GUIs? Well known examples Basic concepts Graphical application. Containers. Actions. Events. Graphical elements: Menu

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

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

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

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

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

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN CSSE 220 Day 19 Object-Oriented Design Files & Exceptions Check out FilesAndExceptions from SVN A practical technique OBJECT-ORIENTED DESIGN Object-Oriented Design We won t use full-scale, formal methodologies

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

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

MIT AITI Swing Event Model Lecture 17

MIT AITI Swing Event Model Lecture 17 MIT AITI 2004 Swing Event Model Lecture 17 The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the user. But how do GUIs interact with users? How do applications

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

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

Example: Building a Java GUI

Example: Building a Java GUI Steven Zeil October 25, 2013 Contents 1 Develop the Model 2 2 Develop the layout of those elements 3 3 Add listeners to the elements 9 4 Implement custom drawing 12 1 The StringArt Program To illustrate

More information

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN CSSE 220 Day 19 Object-Oriented Design Files & Exceptions Check out FilesAndExceptions from SVN A practical technique OBJECT-ORIENTED DESIGN Object-Oriented Design We won t use full-scale, formal methodologies

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

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

Lab 5 TOC to Me. Class Structure. IM Client Implementation --- Part 2 Due: 23:00 Monday 13 October. CS 150, Profs. Lawson and Szajda Fall 2008

Lab 5 TOC to Me. Class Structure. IM Client Implementation --- Part 2 Due: 23:00 Monday 13 October. CS 150, Profs. Lawson and Szajda Fall 2008 Lab 5 TOC to Me IM Client Implementation --- Part 2 Due: 23:00 Monday 13 October In this week s lab we will finish work on the IM client programs you started in the last lab. You will add one significant

More information

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread G51PGP Programming Paradigms Lecture 008 Inner classes, anonymous classes, Swing worker thread 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals

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

Eclipsing Your IDE. Figure 1 The first Eclipse screen.

Eclipsing Your IDE. Figure 1 The first Eclipse screen. Eclipsing Your IDE James W. Cooper I have been hearing about the Eclipse project for some months, and decided I had to take some time to play around with it. Eclipse is a development project (www.eclipse.org)

More information

Example: Building a Java GUI

Example: Building a Java GUI Steven Zeil October 25, 2013 Contents 1 Develop the Model 3 2 Develop the layout of those elements 4 3 Add listeners to the elements 12 4 Implement custom drawing 15 1 The StringArt Program To illustrate

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

Lab 5 Classy Chat. XMPP Client Implementation --- Part 2 Due Oct. 19 at 11PM

Lab 5 Classy Chat. XMPP Client Implementation --- Part 2 Due Oct. 19 at 11PM Lab 5 Classy Chat XMPP Client Implementation --- Part 2 Due Oct. 19 at 11PM In this week s lab we will finish work on the chat client programs from the last lab. The primary goals are: to use multiple

More information

Building Java Programs Bonus Slides

Building Java Programs Bonus Slides Building Java Programs Bonus Slides Graphical User Interfaces Copyright (c) Pearson 2013. All rights reserved. Graphical input and output with JOptionPane JOptionPane An option pane is a simple dialog

More information

Lecture (06) Java Forms

Lecture (06) Java Forms Lecture (06) Java Forms Dr. Ahmed ElShafee 1 Dr. Ahmed ElShafee, Fundamentals of Programming I, Introduction You don t have to output everything to a terminal window in Java. In this lecture, you ll be

More information

Lab 5 TOC to Me. IM Client Implementation --- Part 2

Lab 5 TOC to Me. IM Client Implementation --- Part 2 Lab 5 TOC to Me IM Client Implementation --- Part 2 In this week s lab we will finish work on the IM client programs from the last lab. The primary goals are: to use multiple windows to manage more than

More information

1005ICT Object Oriented Programming Lecture Notes

1005ICT Object Oriented Programming Lecture Notes 1005ICT Object Oriented Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 2, 2015 1 20 GUI Components and Events This section develops a program

More information

Lecture 9. Lecture

Lecture 9. Lecture Layout Components MVC Design PaCern GUI Programming Observer Design PaCern D0010E Lecture 8 - Håkan Jonsson 1 Lecture 8 - Håkan Jonsson 2 Lecture 8 - Håkan Jonsson 3 1 1. GUI programming In the beginning,

More information

What is Widget Layout? COSC 3461 User Interfaces. Hierarchical Widget Layout. Resizing a Window. Module 5 Laying Out Components

What is Widget Layout? COSC 3461 User Interfaces. Hierarchical Widget Layout. Resizing a Window. Module 5 Laying Out Components COSC User Interfaces Module 5 Laying Out Components What is Widget Layout? Positioning widgets in their container (typically a JPanel or a JFrame s content pane) Basic idea: each widget has a size 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

Jonathan Aldrich Charlie Garrod

Jonathan Aldrich Charlie Garrod Principles of Software Construction: Objects, Design, and Concurrency (Part 3: Design Case Studies) Introduction to GUIs Jonathan Aldrich Charlie Garrod School of Computer Science 1 Administrivia Homework

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

GUI Event Handlers (Part I)

GUI Event Handlers (Part I) GUI Event Handlers (Part I) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda General event

More information

GUI Forms and Events, Part II

GUI Forms and Events, Part II GUI Forms and Events, Part II Quick Start Compile step once always mkdir labs javac PropertyTax6.java cd labs Execute step mkdir 6 java PropertyTax6 cd 6 cp../5/propertytax5.java PropertyTax6.java Submit

More information

Lecture 5: Java Graphics

Lecture 5: Java Graphics Lecture 5: Java Graphics CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki 1 New Unit Overview Graphical User Interfaces (GUI) Components, e.g., JButton, JTextField, JSlider, JChooser, Containers,

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

A set, collection, group, or configuration containing members regarded as having certain attributes or traits in common.

A set, collection, group, or configuration containing members regarded as having certain attributes or traits in common. Chapter 6 Class Action In Chapter 1, we explained that Java uses the word class to refer to A set, collection, group, or configuration containing members regarded as having certain attributes or traits

More information

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR DEMYSTIFYING PROGRAMMING: CHAPTER FOUR Chapter Four: ACTION EVENT MODEL 1 Objectives 1 4.1 Additional GUI components 1 JLabel 1 JTextField 1 4.2 Inductive Pause 1 4.4 Events and Interaction 3 Establish

More information

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain "undo" commands, too.

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain undo commands, too. Commands A command is something you want someone else to perform. Instead of directly issuing a command, we can write it down and give it to someone to perform. Written commands can be reused, cataloged,

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

UI Software Organization

UI Software Organization UI Software Organization The user interface From previous class: Generally want to think of the UI as only one component of the system Deals with the user Separate from the functional core (AKA, the app

More information

CS Exam 1 Review Suggestions

CS Exam 1 Review Suggestions CS 235 - Fall 2015 - Exam 1 Review Suggestions p. 1 last modified: 2015-09-30 CS 235 - Exam 1 Review Suggestions You are responsible for material covered in class sessions, lab exercises, and homeworks;

More information

Unit 6: Graphical User Interface

Unit 6: Graphical User Interface 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 6: Graphical User Interface 1 1. Overview of the

More information

Resizing a Window. COSC 3461: Module 5B. What is Widget Layout? Size State Transitions. What is Widget Layout? Hierarchical Widget Layout.

Resizing a Window. COSC 3461: Module 5B. What is Widget Layout? Size State Transitions. What is Widget Layout? Hierarchical Widget Layout. COSC 3461: Module 5B Resizing a Window Widgets II What has changed? scrollbar added menu has wrapped toolbar modified (buttons lost) 2 What is Widget Layout? Size State Transitions Recall: each widget

More information

CS 2113 Software Engineering

CS 2113 Software Engineering CS 2113 Software Engineering Java 5 - GUIs Import the code to intellij https://github.com/cs2113f18/template-j-5.git Professor Tim Wood - The George Washington University Class Hierarchies Abstract Classes

More information

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software. Introduction to Netbeans This document is a brief introduction to writing and compiling a program using the NetBeans Integrated Development Environment (IDE). An IDE is a program that automates and makes

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

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

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