Download presentation
Presentation is loading. Please wait.
Published byNeal Gerald King Modified over 9 years ago
1
Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission
2
Import Packages for GUI java.awt.* AWT (abstract window toolkit) is the main Java package used to create and display GUI objects AWT heavily relies on the native operating system to create and display the graphical objects As a result, your GUI interfaces will not look the same on every system “heavyweight” components
3
Import Packages for GUI javax.swing.* Swing is a package of GUI objects which is more-or-less pure Java Swing uses AWT to create a window, and then paints pictures of GUI objects inside the window, instead of relying on the operating system to do this As a result, your GUI interfaces should look about the same on every system Swing allows for a pluggable look and feel to easily change the style “lightweight” components (mostly)
4
Containers GUI objects are grouped together inside some type of container object To create a graphical user interface for a Java program, you must: Create a container object Add GUI components to the container object Add code which will execute in response to the object events This concept is no different from any other data structure that you would have previously used
5
Containers are Data Structures Linked Lists LinkedList list = new LinkedList(); list.add(data1); list.add(data2); Containers Container container = new Container(); container.add(obj1); container.add(obj2); data1 head list obj1obj2 head container
6
Top-Level Containers Top-level containers are the main containers for a Java program A Java GUI program begins by creating a top-level container, and then adds GUI components to it Top-level containers can appear on their own on the screen – all other types of containers must go inside a top-level container
7
Container Hierarchy All top-level containers classes are children of the Container class, which is derived from the Component class of the java.awt package The main window for a desktop application is a JFrame whereas the main container for a browser applet is JApplet Component Container Panel Applet JApplet Window JWindow JDialog JFrame
8
Types of Windows JFrame: Contains a title bar, menu bars, and a border. Can be minimized/maximized/closed. JDialog: Used to create dialog boxes. Often used to obtain more detailed user input or show more detailed output. JWindow: Has no trimmings. Often used for pop-up windows and splash screens.
9
Container Layers Root Pane: Manages/contains all of the layers. Layered Pane: Serves to position its contents in regards to depth (called Z order). Allows overlapping components to appear on top of each other. Holds content and menu. Menu Bar: The home for the root container’s menus Content Pane: Container for the root pane’s visible components (excluding the menu bar). Glass Pane: Acts like a sheet of glass over all other layers. It is completely transparent unless you paint something on it. Root Pane Layered Pane Content Pane Glass Pane Menu Bar
10
Hello World Example package example01; import javax.swing.*; public class HelloWorld { public static void main(String[] args) { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); } }
11
Make It Better package example01; import javax.swing.*; public class HelloWorld { public static void main(String[] args) { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); } package example01; import javax.swing.*; public class HelloWorld { public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); } public static void main(String[] args) { JFrame mainframe = createGUI(); mainframe.setVisible(true); }
12
Threads Threads are units of execution in a program Java programs start with one thread, which begins by executing the code in the main program Programs can create additional threads which are all operating simultaneously Programs which contain more than one thread are multithreaded programs Java GUI programs are multithreaded
13
Threads in Swing Programs There are three major types of threads used in swing programs: Initial threads execute initial application code The event dispatch thread handles all of the events for the GUI Worker threads executes time-consuming background tasks so that the user interface does not freeze while the task is being performed
14
The Event Dispatch Thread Executes code which handles GUI events (button presses, mouse movement, etc.) Most Swing object methods are not thread safe – invoking them from multiple threads risks consistency errors in memory that are hard to debug As a result, all GUI updating should be handled by this thread Jobs to be executed by this thread must be scheduled with the invokeLater or invokeAndWait methods of the javax.swing.SwingUtilities class
15
Initial Threads In standard Java applications, one initial thread starts the main method (for applets, the initial threads construct the applet and invoke its init and start methods) For Swing programs, the initial threads do not have much to do The main task is to initialize the GUI and schedule it to be executed by the event dispatch thread
16
Worker Threads Tasks can be performed by the event dispatch thread as long as they complete quickly If tasks executed by the event dispatch thread take too long, then the GUI becomes unresponsive to the user’s input To prevent this, worker threads are used for time consuming tasks, leaving the EDT to take care of the GUI events
17
So What Does Main Do? invokeLater This method needs an Runnable object as a parameter Runnable objects contain a run method which is executed when the object is used to create a thread Anonymous class: a class which is declared and instantiated at the same time. Used when the class is only needed once. new Runnable() { public void run() { mainFrame.setVisible(true); } } Initialize the GUI Jframe mainframe = createGUI(); Schedule it to be executed by the event dispatch thread SwingUtilities.invokeLater(); Schedule it to be executed by the event dispatch thread
18
Hello World Better package example01; import javax.swing.*; public class HelloWorld { public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); } public static void main(String[] args) { JFrame mainframe = createGUI(); SwingUtilities.invokeLater(new Runnable() { public void run() { mainframe.setVisible(true); } }); } MainThread Create GUI Schedule for the EDT to make it visible E D T
19
Make it Even Better! public class HelloWorld { public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); Instead of having the main program class “create” a JFrame… public class HelloWorld extends JFrame { Let the main program class actually “BE” a JFrame public class HelloWorld extends JFrame { private JLabel label; Objects in the frame should then be class variables so they are accessible from any method
20
package example01; import javax.swing.*; public class HelloWorld { public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); } public static void main(String[] args) { JFrame mainframe = createGUI(); SwingUtilities.invokeLater(new Runnable() { public void run() { mainframe.setVisible(true); } }); } package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); } Hello World Even Better
21
Where Did Main Go? We have two options: Option #1 Since this class is now a JFrame, main can be moved into a separate class In this new main class, instead of creating a “JFrame” object, you will need to create a “HelloWorldEvenBetter” object package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); }
22
Option #1 HelloWorldEvenBetter.java package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); } MainApplication.java package example01; import javax.swing.*; public class MainApplication { public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new HelloWorldEvenBetter().setVisible(true); } }); }
23
Option #2 Any Java class can contain a main method – meaning that any class can be made to be “executable” It is preferred to do this, for the main GUI frame package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); } public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new HelloWorldEvenBetter().setVisible(true); } }); } HelloWorldEvenBetter.java
24
One More Revision The invokeLater method wants a Runnable object as a parameter We created an anonymous class with only a single (required) run method When you create an anonymous class in this manner, it can be replaced with a lambda expression instead Lambda expressions work like anonymous methods (a method without a name) new Runnable() { public void run() { new HelloWorldEvenBetter.setVisible(true); } () -> { new HelloWorldEvenBetter.setVisible(true); } Is the same as: So main becomes: SwingUtilities.invokeLater( () -> { new HelloWorldEvenBetter.setVisible(true); });
25
Final Version This is the final version of the “Hello World” GUI program package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); } public static void main(String [] args) { SwingUtilities.invokeLater( () -> { new HelloWorldEvenBetter().setVisible(true); }); } HelloWorldEvenBetter.java
26
Example #2 Demonstrates: Setting preferred sizes for objects Putting a menu bar in the frame Coloring the menu bar Adding a big colored label to the content pane Root Pane Layered Pane Content Pane Menu Bar JLabel
27
Things You Need To Know You need to create a JMenuBar object A Color object is needed to implement colors for various GUI items Initialize the Color object with the amount of red, green and blue you want in the color The amount is one byte for each == an integer from 0 - 255 A Dimension object is needed to establish sizes Initialize with the width and the height, in pixels
28
Start with the Basic Template package example02; import java.awt.*; import javax.swing.*; public class TopLevelDemo extends JFrame { public TopLevelDemo() { initComponents(); setTitle("Top Level Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { } public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TopLevelDemo().setVisible(true); } }); } TopLevelDemo.java
29
Add Class Variables and Initialization Code private JMenuBar greenMenuBar; private JLabel yellowLabel; private void initComponents() { greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); setJMenuBar(greenMenuBar); getContentPane().add(yellowLabel); pack(); } TopLevelDemo greenMenuBar yellowLabel
30
Final Version This is the final version of the “TopLevelDemo” program package example02; import java.awt.*; import javax.swing.*; public class TopLevelDemo extends JFrame { private JMenuBar greenMenuBar; private JLabel yellowLabel; public TopLevelDemo() { initComponents(); setTitle("Top Level Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); setJMenuBar(greenMenuBar); getContentPane().add(yellowLabel); pack(); } public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TopLevelDemo().setVisible(true); } }); }
31
Layout Managers Each container (by default) has a layout manager These objects determine the size and position of the components in the container Components in the container can provide suggestions about size and alignment, however the layout manager makes the final decision about how items are positioned There are four layout managers which are fairly simple to use Additional layout managers can be written by creating a class which implements the LayoutManager interface
32
Border Layout The default manager for all content panes (except JPanel) Has five areas for holding components: NORTH, SOUTH, EAST, WEST, CENTER All extra space is placed in the center Requires you to indicate in which you want components placed
33
Box Layout Puts components on a single row or column Components are not sized beyond their requested maximum size
34
Flow Layout Default manager for Jpanel objects Sets out components from left to right Starts new rows when necessary
35
Grid Layout Displays components in a grid Resizes components so they are all equal in size Components are added left to right, filling a row before moving on to another row When creating, you must specify the number of desired rows OR columns. The opposite value is automatically computed
36
Other Choices Grid Bag Layout A sophisticated layout manager with much more control over the grid Requires additional objects to help define the pacement of components Absolute Positioning Used when the layout manager is set to null Programmer must specify exact position and size for all components
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.