Swing JComponents.

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

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.
Corresponds with Chapter 12
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 20, 2005.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
LAB SESSION 10 *LAYOUT MANAGER *LISTENERS. Laying the components manually by using a null layout is tedious. Each container object has a layout manager.
IEEM 110 Computing in Industrial Applications Basic User Interface in Java.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
COMP 14 Introduction to Programming Miguel A. Otaduy June 7, 2004.
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.
Advanced Java and Android Programming Day 1: Introduction to GUI Programming Intro to GUI Programming1.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 17 GUI Programming - Component Layout, Additional GUI Components Layout Managers Assigning the Layout Manager FlowLayout Manager FlowLayout Alignment.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
OOP (Java): Layout/ OOP Objectives – –describe the basic layout managers for GUIs Semester 2, GUI Layout.
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.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 12.
1 Why layout managers Can we perform layout without them? –Yes. A container’s layout property can be set to null. Absolute positioning: specify size and.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CompSci 100E 35.1 Graphical User Interfaces: GUIs  Components  Flat Layouts  Hierarchical Layouts  Designing a GUI  Coding a GUI.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Layout Managers Arranges and lays out the GUI components on a container.
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.
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.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
University of Limerick1 Software Architecture Java Layout Managers.
1 Chapter 17 GUI Programming - Component Layout, Additional GUI Components Layout Managers Assigning the Layout Manager FlowLayout Manager FlowLayout.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Csc Basic Graphical User Interface (GUI) Components.
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
Computer Science 209 GUIs Model/View/Controller Layouts.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 14 : Swing II King Fahd University of Petroleum & Minerals College of Computer Science.
J McQuillanSE204:2004/2005: Lecture 3Slide 1 Specialised Components Can create specialised components. Do this by subclassing the component that you are.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Assigning the Layout Manager FlowLayout Manager FlowLayout Alignment
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
CSI 3125, Preliminaries, page 1 Layout Managers. CSI 3125, Preliminaries, page 2 Layout Managers The LayoutManagers are used to arrange components in.
Graphical User Interface (GUI) Two-Dimensional Graphical Shapes.
Java Layouts CSIS 3701: Advanced Object Oriented Programming.
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.
Dept. of CSIE, National University of Tainan 10/21/2012 Arranging Components on a User Interface.
AWT Vs SWING. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in most Java textbooks Adequate for many applications Uses.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
Unit 131 GUI Layout Managers Learning Outcomes oList and distinguish between the four most common, standard layout managers in Java. oUse these and other.
Chapter 7 A First Look at GUI Applications Layout Managers.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Java Applet What is a Java Applet? How is applet compiled?
Graphical User Interfaces -- GUIs
GUIs Model/View/Controller Layouts
Modern Programming Language Java
Ellen Walker Hiram College
Containers and Components
Creating Graphical User Interfaces
PC02 Consolidation %WITTY_QUOTE%. PC02 Consolidation %WITTY_QUOTE%
CiS 260: App Dev I Chapter 6: GUI and OOD.
GUI building with the AWT
Graphical User Interface
Presentation transcript:

Swing JComponents

Layout Managers Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems. The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container. Layout managers are set in containers using the setLayout(LayoutManager) method in a container.

Layout Managers 2 Layout managers automate the positioning of components within containers. They free the programmer from the difficult task of figuring out the space needed for each component and the pixel coordinate positions for each component. The layout manager looks at the size of its container and the sizes of the container's components. It then tries to fit the components neatly into the container. If a user resizes the window, the layout manager takes that into account and adjusts the layout accordingly. If a programmer adjusts a component's size (e.g., by changing a label's font size), the layout manager takes that into account and adjusts the layout accordingly.

Layout Managers The four most common layout manager classes: 3 The four most common layout manager classes: FlowLayout BorderLayout GridLayout GridBagLayout All of these layout manager classes are in the java.awt package so import that package.

Assigning the Layout Manager 4 To assign a particular layout manager to a JFrame window, call the setLayout method as follows: setLayout(new <layout-manager-class>()); In the above code template, replace <layout­manager­class> by one of the layout manager classes (e.g., FlowLayout, BorderLayout, GridLayout). If setLayout is not called, then the BorderLayout manager is used (because that's the default layout manager for a JFrame window).

FlowLayout Manager 5 The FlowLayout class implements a simple one-compartment layout scheme that allows multiple components to be inserted into the compartment. When a component is added to the compartment, it is placed to the right of any components that were previously added to the compartment. If there is not enough room to add a component to the right of previously added components, then the new component is placed on the next line (i.e., it "flows" to the next line).

JFrame Example public class FrameTester { public static void main (String args[]) { JFrame f = new JFrame ("JFrame Example"); Container c = f.getContentPane(); c.setLayout (new FlowLayout()); for (int i = 0; i < 5; i++) { c.add (new JButton ("No")); c.add (new Button ("Batter")); } c.add (new JLabel ("Swing")); f.setSize (300, 200); f.show(); 7

FlowLayout Alignment 6 By default, components are placed in a FlowLayout container using top, center alignment. There's no way to change the vertical alignment. But there is a way to change the horizontal alignment. To do so, insert one of the FlowLayout alignment constants (FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT) in the FlowLayout constructor call. For example, here's how to specify left alignment: setLayout(new FlowLayout(FlowLayout.LEFT));

BorderLayout Manager 8 The BorderLayout manager provides five regions/compartments in which to insert components. The sizes of the five regions are determined at run time, and they're based on the contents of each region. Thus, if the west region contains a long label, the layout manager attempts to widen the west region. Likewise, if the west region contains a short label, the layout manager attempts to narrow the west region.

BorderLayout Manager 11 To add a component to a BorderLayout region, call the container's add method like this: add(<component>, <region>); Replace <component> by a component (a JLabel object, a JButton object, etc.) and replace <region> by one of these named constants: BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.EAST, BorderLayout.CENTER In the add method call, if the region argument is omitted, then the center region is used (because that's the default region). With a BorderLayout container, you can add only five components total, one for each of the five regions. If you add a component to a region that already has a component, then the new component overlays the old component.

AfricanCountries Program with Buttons 12 import javax.swing.*; import java.awt.*; public class AfricanCountries extends JFrame { private static final int WIDTH = 325; private static final int HEIGHT = 200; public AfricanCountries() setTitle("African Countries"); setSize(WIDTH, HEIGHT); setLayout(new BorderLayout()); setDefaultCloseOperation(EXIT_ON_CLOSE); add(new JButton("Tunisia"), BorderLayout.NORTH); add(new JButton("<html>South<br />Africa</html>"), BorderLayout.SOUTH); add(new JButton("Western Sahara"), BorderLayout.WEST); add(new JButton("Central African Republic"), BorderLayout.CENTER); add(new JButton("Somalia"), BorderLayout.EAST); setVisible(true); } // end AfricanCountries constructor //************************************** public static void main(String[] args) new AfricanCountries(); } // end main } // end class AfricanCountries

Exercise Program this The buttons set the colour of the left hand pane

Label Alignment 14 To specify a label's alignment within a BorderLayout region, instantiate the label with an alignment constant like this: new JLabel(<label's-text>, <alignment-constant>) Replace <alignment-constant> by one of these named constants: SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT Here's an example that adds a center-aligned label to a BorderLayout north region: add(new JLabel("Tunisia", SwingConstants.CENTER), BorderLayout.NORTH);

GridLayout Manager 16 The GridLayout manager lays out a container's components in a rectangular grid. The grid is divided into equal-sized cells. Each cell can hold only one component. To specify the use of a GridLayout manager for a particular container, call setLayout like this: setLayout(new GridLayout(rows, cols, hGap, vGap)); # of rows Gap between columns, in pixels. Default value = 0. # of columns Gap between rows, in pixels. Default value = 0.

horizontal gap = 5 pixels GridLayout Manager 18 Here's an example that displays a two-row, three-column table with six buttons: setLayout(new GridLayout(2, 3, 5, 5)); add(new JButton("1")); add(new JButton("2")); add(new JButton("3")); add(new JButton("4")); add(new JButton("5")); add(new JButton("6")); vertical gap = 5 pixels horizontal gap = 5 pixels

Setting text display with Alignment property of text field.

Embedded Layout Managers 26 What layout manager scheme should be used for this math-calculator window? The GridLayout manager is usually pretty good at positioning components in an organized tabular fashion, but it's limited by the fact that each of its cells must be the same size.

JPanel Class 28 A JPanel container object is a generic storage area for components. If you have a complicated window with lots of components, you may want to compartmentalize them by storing groups of components in JPanel containers. JPanel containers are particularly useful with GridLayout and BorderLayout windows because each compartment in those layouts can store only one component. If you need a compartment to store more than one component, let that one component be a JPanel container, and put multiple components into the JPanel container.

JPanel Class When using a JPanel container, do these things: 29 When using a JPanel container, do these things: Since JPanel is in the javax.swing package, import that package. Instantiate a JPanel object: JPanel <JPanel-reference> = new JPanel(<layout-manager>) Add the components to the JPanel object: <JPanel-reference>.add(<component>) Add the JPanel object to the window: add(<JPanel-reference>) Optional argument. The default is FlowLayout with center alignment. If the JPanel object uses a BorderLayout, then add a region argument. If the JFrame object uses a BorderLayout, then add a region argument.

JPanel Class 30 For example, to create the top-left cell's panel in the math-calculations program, do this in the createContents method: xPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); xPanel.add(xLabel); xPanel.add(xBox); add(xPanel);

This MathCalculator program uses embedded layout managers to display square root and logarithm calculations. 31 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MathCalculator extends JFrame { private static final int WIDTH = 380; private static final int HEIGHT = 110; private JTextField xBox; // user's input value private JTextField xSqrtBox; // generated square root private JTextField xLogBox; // generated logarithm //*************************************** public MathCalculator() setTitle("Math Calculator"); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(EXIT_ON_CLOSE); createContents(); setVisible(true); } // end MathCalculator constructor

MathCalculator Program 32 //************************************** // Create components and add to window. private void createContents() { JPanel xPanel; // holds x label and its text box JPanel xSqrtPanel; // holds "sqrt x" label and its text box JPanel xLogPanel; // holds "log x" label and its text box JLabel xLabel; JButton xSqrtButton; JButton xLogButton; Listener listener; setLayout(new GridLayout(2, 2)); // Create the x panel: xLabel = new JLabel("x:"); xBox = new JTextField(8); xPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); xPanel.add(xLabel); xPanel.add(xBox);

MathCalculator Program 33 // Create the square-root panel: xSqrtButton = new JButton("sqrt x"); xSqrtBox = new JTextField(8); xSqrtBox.setEditable(false); xSqrtPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); xSqrtPanel.add(xSqrtButton); xSqrtPanel.add(xSqrtBox); // Create the logarithm panel: xLogButton = new JButton("log x"); xLogBox = new JTextField(8); xLogBox.setEditable(false); xLogPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); xLogPanel.add(xLogButton); xLogPanel.add(xLogBox); // Add panels to the window: add(xPanel); add(xSqrtPanel); add(new JLabel()); // dummy component add(xLogPanel);

MathCalculator Program 34 listener = new Listener(); xSqrtButton.addActionListener(listener); xLogButton.addActionListener(listener); } // end createContents //*************************************** // Inner class for event handling. private class Listener implements ActionListener { public void actionPerformed(ActionEvent e) double x; // numeric value for user entered x double result; // calculated value try x = Double.parseDouble(xBox.getText()); } catch (NumberFormatException nfe) x = -1; // indicates an invalid x

MathCalculator Program 35 if (e.getActionCommand().equals("sqrt x")) { if (x < 0) xSqrtBox.setText("undefined"); } else result = Math.sqrt(x); xSqrtBox.setText(String.format("%7.5f", result)); } // end if else // calculate logarithm xLogBox.setText("undefined"); result = Math.log(x); xLogBox.setText(String.format("%7.5f", result)); getActionCommand retrieves the label of the button that was clicked.

MathCalculator Program 36 } // end else } // end actionPerformed } // end class Listener //************************************** public static void main(String[] args) { new MathCalculator(); } // end main } // end class MathCalculator