CIT 590 Swing/GUI in Java. How to create a GUI Create a window in which to display things—usually a JFrame (for an application), Use the setLayout(LayoutManager.

Slides:



Advertisements
Similar presentations
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Advertisements

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.
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.
20-Jun-15 GUI building with Swing. 2 How to build a GUI Create a window in which to display things—usually a JFrame (for an application), or a JApplet.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java GUI building with the AWT. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in most Java textbooks Adequate for many.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
23-Aug-15 GUI building with Swing. 2 How to build a GUI Create a window in which to display things—usually a JFrame (for an application), or a JApplet.
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.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
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.
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Java GUI building with Swing. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
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 ( 李德成 )
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 Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
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.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
CS3340: Swing and Event handling L. Grewe. Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel,
1 12 Apr 2011 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.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Computer Science 209 GUIs Model/View/Controller Layouts.
CIT 590 Swing/GUI in Java. Examples in the repository Examples/Java/GUI
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.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
GUI Tutorial 1. A Bit of Philosophy on what to Teach  There are numerous libraries, frameworks, options  Modern GUIs are often developed using XML (e.g.,
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Graphical User Interface (GUI)
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
Introduction to GUI in 1 Graphical User Interface 3 Nouf Almunyif.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Graphical User Interfaces -- GUIs
8 April 2008 GUIS —Graphical User Interfaces
GUI building with Swing
A Quick Java Swing Tutorial
Chapter 13: Advanced GUIs and Graphics
GUI building with Swing
GUI building with Swing
GUI building with the AWT
GUI building with Swing
A Quick Java Swing Tutorial
Advanced Programming in Java
GUI building with Swing
GUI building with Swing
GUI building with the AWT
Advanced GUIs and Graphics
13 April 2010 GUIS: Graphical User Interfaces
Presentation transcript:

CIT 590 Swing/GUI in Java

How to create a GUI Create a window in which to display things—usually a JFrame (for an application), Use the setLayout(LayoutManager manager) method to specify a layout manager Throw some components in. Create some listeners and attach them to your components. When you do something to a component, an event is generated which is ‘listened’ to. When the listener ‘hears’ the event, it executes code to deal with it Display your window.

Frames v Applets A lot of what we cover applies to both Applications and Applets Applications are basically what we have been writing so far – everything running on your computer Applets were the predecessors of things like Flash on the internet Basically can be embedded in HTML Runs in browser Currently very very few people use Applets. did-java-go-wrong-on-the-client did-java-go-wrong-on-the-client We will only do application programming – safely assume everything is a frame.

So many packages to import … CTRL(Command) + SHIFT + O = magic! That keyboard shortcut will import all that is needed. If you are curious…. Javax.swing.* Java.awt.* Java.awt.event.* Javax.swing.event.* And others …. I always use CTRL + SHIFT +O If it doesn’t work (rare but can happen), I google and find out what I need to import.

Layouts for your container The most important layout managers are: BorderLayout Provides five areas into which you can put components This is the default layout manager for both JFrame and JApplet FlowLayout Components are added left to right, top to bottom GridLayout Components are put in a rectangular grid All areas are the same size and shape BoxLayout Creates a horizontal row or a vertical stack This can be a little weird to use

Add components container.add( component ); What is a component? Buttons, textboxes, checkboxes, textareas etc etc For FlowLayout, GridLayout, and BoxLayout, this adds the component to the next available location For BorderLayout, this puts the component in the CENTER by default For BorderLayout, it’s usually better to use container.add( component, BorderLayout. position ); position is one of NORTH, SOUTH, EAST, WEST, or CENTER

Useful resources ples.jar ples.jar A jar file is just a bunch of compressed java files.

8 Some types of components JLabel JButton JCheckbox JChoice JList JScrollbar JTextField JTextArea JCheckboxGroup JCheckbox

9 Create components JButton button = new JButton("Click me!"); JLabel label = new JLabel("This is a JLabel"); JTextField textField1 = new JTextField("This is the initial text"); JTextField textField2 = new JTextField("Initial text", columns); JTextArea textArea1 = new JTextArea("Initial text"); JTextArea textArea2 = new JTextArea(rows, columns); JTextArea textArea3 = new JTextArea("Initial text", rows, columns); JCheckBox checkbox = new JCheckBox("Label for checkbox"); JRadioButton radioButton1 = new JRadioButton("Label for button"); ButtonGroup group = new ButtonGroup(); group.add(radioButton1); group.add(radioButton2); etc. This is just a sampling of the available constructors; see the javax.swing API for all the rest

public class BorderLayoutExample extends JFrame{ public BorderLayoutExample () { setLayout(new BorderLayout ()); add(new JButton("One"), BorderLayout.NORTH); add(new JButton("Two"), BorderLayout.WEST); add(new JButton("Three"), BorderLayout.CENTER); add(new JButton("Four"), BorderLayout.EAST); add(new JButton("Five"), BorderLayout.SOUTH); add(new JButton("Six")); } }

FlowLayout

GridLayout

BoxLayout example As mentioned, this can be a little weird to use but useful if you want to stack things vertically or horizontally

14 Nested layouts A JPanel is both a JContainer and a Component Because it’s a container, you can put other components into it Because it’s a component, you can put it into other containers All but the very simplest GUIs are built by creating several JPanel s, arranging them, and putting components (possibly other JPanel s) into them A good approach is to draw (on paper) the arrangement you want, then finding an arrangement of JPanel s and their layout managers that accomplishes this

Container container = new JFrame() or JApplet() ; JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); p1.add(new JButton("A"), BorderLayout.NORTH); // also add buttons B, C, D, E JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3, 2)); p2.add(new JButton("F")); // also add buttons G, H, I, J, K JPanel p3 = new JPanel(); p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS)); p3.add(new JButton("L")); // also add buttons M, N, O, P container.setLayout(new BorderLayout()); container.add(p1, BorderLayout.CENTER); container.add(p2, BorderLayout.SOUTH); container.add(p3, BorderLayout.EAST);

16 Create and attach listeners JButton okButton = new JButton("OK"); okButton.addActionListener(new MyOkListener()); class MyOkListener implements ActionListener { public void actionPerformed(ActionEvent event) { // code to handle okButton click } } A small class like this is often best implemented as an anonymous inner class

What is a listener Components like button, textbox etc have events that can be ‘listened’ to When the event is triggered, the next lines of code executed will be the ones corresponding to the listener code. A listener is always going to implement one of the ‘standard’ interfaces ActionListener KeyListener MouseListener

18 Suggested program arrangement 1 class SomeClass { // Declare components as instance variables JFrame frame; // Can also define them here if you prefer JButton button; public static void main(String[] args) { new SomeClass().createGui(); } // Define components and attach listeners in a method void createGui() { frame = new JFrame(); button = new JButton("OK"); frame.add(button); // (uses default BorderLayout) button.addActionListener(new MyOkListener()); } // Use an inner class as your listener class MyOkButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { // Code to handle button click goes here } } }

19 Suggested program arrangement 2 class SomeClass extends JFrame { // Declare components as instance variables // JFrame frame; // Don't need this JButton button; public static void main(String[] args) { new SomeClass().createGui(); } // Define components and attach listeners in a method void createGui() { // frame = new JFrame(); // Don't need this button = new JButton("OK"); add(button); // Was: frame.add(button); button.addActionListener(new MyOkListener()); } // Use an inner class as your listener class MyOkButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { // Code to handle button click goes here } } }

20 Components use various listeners JButton, JMenuItem, JComboBox, JTextField: addActionListener(ActionListener) public void actionPerformed(ActionEvent event) JCheckBox, JRadioButton: addItemListener(ItemListener) public void itemStateChanged(ItemEvent event) JSlider addChangeListener(ChangeListener) public void stateChanged(ChangeEvent event) JTextArea getDocument().addDocumentListener(DocumentListener) public void insertUpdate(DocumentEvent event) public void removeUpdate(DocumentEvent event) public void changedUpdate(DocumentEvent event)

21 Getting values Some user actions normally cause the program to do something: clicking a button, or selecting from a menu Some user actions set values to be used later: entering text, setting a checkbox or a radio button You can listen for events from these, but it’s not usually a good idea Instead, read their values when you need them String myText = myJTextField.getText(); String myText = myJTextArea.getText(); boolean checked = myJCheckBox.isSelected(); boolean selected1 = myJRadioButton1.isSelected();

22 Enabling and disabling components It is poor style to remove components you don’t want the user to be able to use “Where did it go? It was here a minute ago!” It’s better to enable and disable controls Disabled controls appear “grayed out” The user may still wonder why?, but that’s still less confusing anyComponent.setEnabled( enabled ); Parameter should be true to enable, false to disable

23 Summary I: Building a GUI Create a container, either have a Jframe instance variable or extend JFrame Choose a layout manager Create more complex layouts by adding JPanels ; each JPanel can have its own layout manager Create other components and add them to whichever JPanels you like

24 Summary II: Building a GUI For each active component, look up what kind of Listeners it can have Implement the Listeners often there is one Listener for each active component Active components can share the same Listeners For each Listeners you implement, supply the methods that it requires

25 Dialogs A dialog (small accessory window) can be modal or nonmodal When your code opens a modal dialog, it waits for a result from the dialog before continuing When your code opens a nonmodal dialog, it does so in a separate thread, and your code just keeps going Sun supplies a few simple (but useful) modal dialogs for your use You can create your own dialogs (with JDialog ), but they are nonmodal by default

26 Message dialogs JOptionPane.showMessageDialog(parentJFrame, "This is a JOptionPane \"message\" dialog."); Notice that showMessageDialog is a static method of JOptionPane The “ parentJFrame ” is typically your main GUI window (but it’s OK to use null if you don’t have a main GUI window)

27 Confirm dialogs int yesNo = JOptionPane.showConfirmDialog(parentJFrame, "Is this what you wanted to see?"); if (yesNo == JOptionPane.YES_OPTION) {... }

28 Input dialogs String userName = JOptionPane.showInputDialog(parentJFrame, "What is your name?")

29 Option dialogs Object[] options = new String[] {"English", "Chinese", "French", "German" }; int option = JOptionPane.showOptionDialog(parentJFrame, "Choose an option:", "Option Dialog", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); // use as default Fourth argument could be JOptionPane.YES_NO_CANCEL_OPTION Fifth argument specifies which icon to use in the dialog; it could be one of ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, or PLAIN_MESSAGE Sixth argument ( null above) can specify a custom icon

30 Load file dialogs JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Load which file?"); int result = chooser.showOpenDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file } You could also test for CANCEL_OPTION or ERROR_OPTION You will get back a File object; to use it, you must know how to do file I/O

31 Save file dialogs JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(“Save file as?"); int result = chooser.showSaveDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file } You could also test for CANCEL_OPTION or ERROR_OPTION You will get back a File object; to use it, you must know how to do file I/O

32 Quitting the program gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Other options are DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, and DISPOSE_ON_CLOSE

33 Summary I: Building a GUI Create a container, either have a Jframe instance variable or extend JFrame Choose a layout manager Create more complex layouts by adding JPanels ; each JPanel can have its own layout manager Create other components and add them to whichever JPanels you like

34 Summary II: Building a GUI For each active component, look up what kind of Listeners it can have Implement the Listeners often there is one Listener for each active component Active components can share the same Listeners For each Listeners you implement, supply the methods that it requires