MIT AITI 2003 Lecture 16. Swing Part I Let’s swing and have some fun !!!

Slides:



Advertisements
Similar presentations
G5BUID - Java Swing Laying out components Manage realized components Determine size and position Each container has a layout manager (usually)
Advertisements

Introduction to Java 2 Programming
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Graphical User Interfaces
Java Software Development Paradigm Lecture # 12. Basics of GUI.
CS18000: Problem Solving and Object-Oriented Programming.
Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
GUI programming AWT(Abstract Windows Toolkit)-GUI components library when Java was introduced AWT was replaced by Swing components import javax.swing.*;
Swinging Into Swing Leo S. Primero III. Understanding what Swing Is Swing is a package that lets you create applications that use a flashy Graphical User.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
GUI Layout Managers Arkadiusz Edward Komenda. Outline Components and Containers Layout Managers Flow Layout Grid Layout Border Layout Nested Containers.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
GUI and event-driven programming An introduction.
Contructing GUI’s in Java Implemented in the Swing API Imported into your programs by: import javax.swing.*; Most Swing programs also need the AWT packages.
Java Programming Chapter 10 Graphical User Interfaces.
OOP (Java): Layout/ OOP Objectives – –describe the basic layout managers for GUIs Semester 2, GUI Layout.
Introduction to Computation and Problem Solving Class 15: Constructing Interfaces with Swing Prof. Steven R. Lerman and Dr. V. Judson Harward 1.
CIS 068 Welcome to CIS 083 ! Introduction to GUIs: JAVA Swing.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Introduction to Computation and Problem Solving Class 14: Introduction to the Swing Toolkit Prof. Steven R. Lerman and Dr. V. Judson Harward 1.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
GUI Basics.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 12 GUI Basics.
10/24/20151 Java GUI Programming. 10/24/20152 What is a GUI? Java has standard packages for creating custom Graphical User Interfaces Some of the fundamental.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Laying Out Components Interior Design for GUIs. Nov 042 What is Widget Layout? Positioning widgets in their container (typically a JPanel or a JFrame’s.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
ITEC 109 Lecture 27 GUI. GUIs Review Sounds –Arrays hold sample values –Creating a keyboard –Sound effects Homework 3 –The big two –Due after break –Lab.
Layout Manager Summary
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
MIT-AITI 2004 – Lecture 16 Introduction to Swing.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
University of Limerick1 Software Architecture Java Layout Managers.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
3461 Laying Out Components Interior Design for GUIs.
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include: a rich set of user interface components; a.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Review_6 AWT, Swing, ActionListener, and Graphics.
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Programming 2 LAB TA: Nouf Al-Harbi NoufNaief.net :::
Graphical User Interfaces Tonga Institute of Higher Education.
Graphical User Interface (GUI) Two-Dimensional Graphical Shapes.
Java Swing - Lecture 3 Layout Management
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Graphical User Interface (GUI)
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
Graphical User Interfaces
Modern Programming Language Java
Java Swing.
Lecture 27 Creating Custom GUIs
Tim McKenna Layout Mangers in Java Tim McKenna
Chap 7. Building Java Graphical User Interfaces
Steps to Creating a GUI Interface
Chapter 12 GUI Basics.
Graphical User Interface
Presentation transcript:

MIT AITI 2003 Lecture 16. Swing Part I Let’s swing and have some fun !!!

Lecture Preview Over the next 2 lectures, we will introduce you to the techniques necessary to build graphic user interfaces (GUI) for your applications. 1. Learning Swing basic concepts: components and containers, fonts, colors, borders, layout; 2. Constructing Swing interfaces; 3. Using the Swing Event Model.

What is a Swing Application? -- A simple Greeting Swing Application

import javax.swing.*; public class MyTest extends JFrame { JLabel myLabel = new JLabel(" Hello, World!"); public MyTest() { super("MyTest"); setSize(350, 100); getContentPane().add(myLabel); setVisible(true); setDefaultCloseOperation( EXIT_ON_CLOSE ); } public static void main (String args[]) { MyTest m = new MyTest(); }

Categories of GUI Classes Jcomponents : The base class for all Swing components except top-level containers (notice it is an abstract class) – some JComponents present information or interact with the user Examples: labels ( JLabel ), buttons ( JButton ), text fields ( JTextField ) – some JComponents are designed to hold other components, not present or interact, they are called Containers. Examples: JPanel, JScrollPane Top Level Windows: are containers that are not contained by any other containers; they can be iconified or dragged and interact with the native windowing system – Example: JFrame, JDialog (not JComponents at all)

Anatomy of a JFrame Look and Feel and platform dependent Interacts with the window system The contentPane is an inner container that holds your content

Swing Application Termination Any program that makes a Swing component visible, including a dialog created via JOptionPane, must explicitly exit by 1. calling System.exit( int code ) ; 2. using setDefaultCloseOperation( EXIT_ON_CLOSE ); to tell Swing what to do when the window system attempts to close the window, (e.g. by clicking the window close box.) Why? Because as soon as you put up a GUI window, you start a separate GUI thread that won't end when you run off the end of the main() method. the window close box

Display the Greeting Application Try 1, Critique It’s too small and the colors don’t stand out. We need to choose a custom Font and text (foreground) Color. import java.awt.Font; import java.awt.Color;

Fonts Standard constructor: Font myFont = new Font( String name, int style, int size ); Font name: safe approach is to use a logical font name, one of – “Times New Roman”, "Serif", "Monospaced", "Dialog", "DialogInput", "Symbol" Four font styles are present: Font.y where y is – PLAIN, BOLD, ITALIC, UNDERLINE – Font.BOLD + Font.ITALIC Size is point size; 12 corresponds to standard printed text

Colors 13 predefined colors: Color.x where x is – orange, pink, cyan, magenta, yellow, black, blue, white, gray, lightGray, darkGray, red, green You can define your own colors // RGB or (red-green-blue) Color ugly= new Color(30, 90, 120);

Displaying the Greeting, Try 2 myFont = new Font( "Serif", Font.BOLD, 24 ); myLabel.setFont( myFont ); myLabel.setForeground( Color.red ); myLabel.setBackground( Color.white ); Why doesn't the background change? Not all JComponents are opaque by default. The JFrame crowds the label.

Borders In Swing, borders are objects. The best way to get some space around our label is to give it an empty border. The best way to create a border is to use the factory methods in class BorderFactory : import javax.swing.border.*;... Border empty = BorderFactory.createEmptyBorder( top,left, bottom,right);

Displaying the Greeting, Try 3 myLabel.setOpaque( true ); Border empty = BorderFactory.createEmptyBorder(10,20,10,20); myLabel.setBorder( empty ); myLabel.setHorizontalAlignment( SwingConstants.CENTER ); JLabel background is transparent in some look & feels by default Add our empty border to the label and center it

Building GUI with Components As simple as our first application is, we can build some very interesting variations with little additional code. JLabel s can hold images as well as or instead of text. A contentPane has 5 zones where you can add a component.

Complex Components A JLabel is just about as simple as a component gets. But using a more complicated component is identical. Components encapsulate their functionality spatially and conceptually.

Constructing GUIs We will build the GUI by nesting simpler components into containers, and then combining the containers into larger containers. JPanel is the workhorse of most complicated interfaces. It is – a good all purpose container – the standard drawing surface – a base class for many composite components

Layout Management, 1 Layout management is the process of determining the size and location of a container's components. Java containers do not handle their own layout. They delegate that task to their layout manager, an instance of another class. If you do not like a container's default layout manager, you can change it. Container content = getContentPane(); content.setLayout( new FlowLayout() );

Layout Management, 2 Layout management is intrinsically recursive and proceeds top down in the containment hierarchy. If a container encloses another container, the enclosing container can not position the inner container nor size itself until it knows how big the inner container needs to be.

Turning off Layout Management Although layout managers can introduce additional complexity, they are there for a very good reason. The effect of layout management can be turned off by eliminating a container's layout manager via a call to setLayout(null). The user must then explicitly lay out each component in absolute pixel coordinates through calls to setSize() and setLocation() or a single call to setBounds(). The problem with this strategy is that it lacks flexibility.

Greeting Application Without Layout Management public MyTest( String dStr ) {... getContentPane().setLayout( null ); getContentPane().add( myLabel ); myLabel.setBounds( 50, 20, 250, 80 ); setSize( 350, 150 ); }

Coordinates Measured in pixels (e.g. 640 by 480, 1024 by 768, etc.) Upper left hand corner is origin (0,0) X axis goes from left to right, y from top to bottom Each component is anchored in its parent's coordinate system myLabel.setBounds( 50, 20, 250, 80 ); setSize( 350, 150 );

3 Good Reasons to Use Layout Management 1. Often you do not know how large your application will be. Even if you call setSize(), the user can still physically resize the window of an application. 2. Java knows better than you how large components should be. It is hard to gauge the size of a JLabel, for instance, except by trial and error. And if you get the size correct on one system and then run it on another with a different set of fonts, the JLabel will not be correctly sized. 3. Once you lay out a GUI, you may want to make changes that will compromise a layout done by hand. If you use layout management, the new layout happens automatically, but if you are laying out the buttons by hand, you have an annoying task ahead of you.

Size Methods Components communicate their layout needs to their enclosing container's layout manager via the methods: – public Dimension getMinimumSize() – public Dimension getPreferredSize() – public Dimension getMaximumSize() There are three corresponding set methods that allow you to change a component's size hints. – public Dimension setMinimumSize( Dimension d ) Dimension d = new Dimension( int width, int height ) – public Dimension setPreferredSize( Dimension d ) – public Dimension setMaximumSize( Dimension d )

Size Methods, 2 Using these methods to change a component's size is far surer in general than using the explicit setSize() method. The effect of a setSize() will only last until the Java environment lays the container out again. Most components provide good default implementations for the get methods. For instance, a button sets its preferred size to accommodate its image and/or its label and font size.

When does Layout Occur? Swing will automatically (re)layout a GUI 1. when it first becomes visible, 2. when a component is added or deleted, or 3. when a component changes its size because the user physically changes its size (by resizing the window) or because the contents have changed (for instance, changing a label).

Layout Managers There are six layout manager classes supplied by Swing. They range from the simple FlowLayout to the flexible but at times frustrating GridBagLayout. Each manager class implements a particular layout policy. Swing containers have default layout managers. A JFrame content pane uses BorderLayout and a JPanel uses FlowLayout.

FlowLayout The FlowLayout, the simplest of the managers, simply adds components left to right until it can fit no more within its container's width. It then starts a second line of components, fills that, starts a third, etc. Each line is centered within the enclosing container. FlowLayout respects each component's preferred size and will use it to override a size set by setSize().

FlowLayout Example, 1 public class Flow extends JFrame { private Font labelFont; private Border labelBorder; public Flow( ) { setDefaultCloseOperation( EXIT_ON_CLOSE ); labelFont = new Font( "SansSerif",Font.BOLD,24 ); labelBorder = BorderFactory.createLineBorder(Color.red,1); getContentPane().setLayout( new FlowLayout() ); setSize(200, 200 ); }

FlowLayout Example, 2 public void addLabel( String labelStr ) { JLabel label = new JLabel( labelStr ); label.setFont( labelFont ); label.setBorder( labelBorder ); getContentPane().add( label ); } public static void main (String args[]) { Flow flow = new Flow(); flow.addLabel( “Hello1" ); flow.addLabel( “Hello2" );... flow.addLabel( “Hello10" ); flow.setVisible( true ); }

BorderLayout Zones North South WestEastCenter

BorderLayout Policy You specify the zone via a second String argument in the add() method. For example, the following line of code adds the button labeled “DoIt" to the middle of a container. add( new JButton( “DoIt" ), "Center" ); // "Center" == BorderLayout.CENTER A BorderLayout may horizontally stretch its North and South components (if they exist), vertically stretch its East and West components, and stretch the Center component both ways to accommodate its container's size and the constraints of its other four sectors. This can be useful. If you put a JPanel in the Center zone of a container managed by a BorderLayout, the manager will always resize the JPanel to take up all extra space, which is usually what you want if you are using it as a drawing surface.

Grid Layout The GridLayout class is a layout manager that lays out a container's components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle. In the normal constructor you specify the number of rows or columns but not both. The one that is not zero has a fixed number of elements; the other grows as you add components. getContentPane().setLayout( new GridLayout(0,2)); would set a JFrame's layout to a two column grid. The number of rows would depend on the number of added components.

Exercises 1. Create a Swing application with a button saying “click me”. 2. Create a Swing application with a label saying “Sawa Sawa”, and a button saying “Karibu”. Put the button at the center of the frame, and the label at the bottom of the frame. (hint: use border layout) 3. Create a Swing application with: 1) two red color labels, font size 14, bold, your favorite font style. One label saying “mimi”, the other saying “wewe”; 2) a button (green foreground color, black background), saying “kucheza”; 3) add two labels in a JPanel, using flow layout, 4) add the JPanel object (center) and the button (north) to the contentPane, using border layout