Swing: the art of the GUI COMP204, Bernhard Pfahringer.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Chapter 16 GUI Programming Basics GUI Overview Event-Driven Programming Basics GUI Classes and Packages A Simple Window Program JFrame Class Java Components.
User Interfaces II GUI – Awt, Swing, Web
Introduction to Swing Components Chapter 14. Part of the Java Foundation Classes (JFC) Provides a rich set of GUI components Used to create a Java program.
Graphical User Interfaces
1 cs205: engineering software university of virginia fall 2006 Wimpy Interfaces.
Computer Science 209 Images and GUIs. Working with Java Colors The class java.awt.Color includes constants, such as Color.red, for some commonly used.
Graphical User Interfaces Java’s AWT and Swing APIs.
Graphical User Interfaces (Part IV)
Java Software Development Paradigm Lecture # 12. Basics of GUI.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
CS18000: Problem Solving and Object-Oriented Programming.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
F27SB2 Programming Languages
Graphical User Interfaces, 2D Graphics & Game Programming.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
TCU CoSc Programming with Java Handling Events.
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 Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Event Handling Events and Listeners Timers and Animation.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
©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.
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.
CIS 068 Welcome to CIS 083 ! Introduction to GUIs: JAVA Swing.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Java GUIs and Graphics CNS Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
C13a, AWT Create, display, facilitate user interaction with window objects software framework: a way of structuring generic solutions to common problems.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
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.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Layout Managers Arranges and lays out the GUI components on a container.
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
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.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
CS1054: Lecture 21 - Graphical User Interface. Graphical User Interfaces vs. Text User Interface.
Swing Components. Introduction Swing – A set of GUI classes – Part of the Java's standard library –Much better than the previous library: AWT Abstract.
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.
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
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.
C13b, AWT cont.. Panel Container that acts like a Component Can be added into other components (like Frames, other Panels) private Panel makeScrollBars()
Introduction to GUI in 1 Graphical User Interface 3 Nouf Almunyif.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
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:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
A Quick Java Swing Tutorial
Advanced User Interfaces
Java Swing.
Graphical User Interface (pronounced "gooey")
A Quick Java Swing Tutorial
Chapter 13: Advanced GUIs and Graphics
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Swing: the art of the GUI COMP204, Bernhard Pfahringer

Swing Swing is very powerful, but also complex built on top of AWT Swing classes start with J.., e.g. JFrame need (at least): import javax.swing.*; often Swing classes are subclasses of AWT classes, e.g. javax.swing JFrame extends java.awt.Frame Swing GUIs use double-buffering (default) => no flickering GUI elements are either: Objects with specific function (e.g. JButton) Containers for GUI elements (e.g. JFrame)

Generic GUI app (composition) Swing is NOT thread-safe, for efficiency reasons (see link on web-page for more details) Need to be careful: public static void main (String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new GUIClass().createAndShowGUI(); } });

cont. public void createAndShowGUI() { _frame = new JFrame(”Title"); // make sure closing exits _frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // // … more setup code // _frame.pack(); _frame.setVisible(true); }

Updating the display Whenever something changes (e.g. text of a JLabel), need to call repaint() NEVER call paint directly Event handling thread queues repaint() request, will fuse multiple calls on the same object into one, and eventually call paint All Components have appropriate paint methods, but you can do your own, if you need (e.g. animation, see code example) public void paint(Graphics g) { g.setColor(_color); g.fillOval(_x-_radius,_y-_radius,2*_radius,2*_radius); }

LayoutManager Container classes need to know where elements go to on the screen: Container content = getContentPane(); LayoutManager layout = new GridLayout(3, 2); content.setLayout(layout); _celsiusLabel = new JLabel("Celsius"); content.add(_celsiusLabel); Typical: BorderLayout, FlowLayout, BoxLayout, CardLayout, GridBagLayout, … see JavaDoc for details, and others

Buttons and ActionListeners Specify interaction by attaching Listeners to GUI objects JButton b = new JButton(“do it!”); b.addActionListener(new DoIt()); … private class DoIt implements ActionListener { public void actionPerformed( ActionEvent e) { // whatever }

Alternative: inheritance + interface implementation in one go private class ColorButton extends JButton implements ActionListener { private Color c; public ColorButton(Color c1, String name) { super(name); c = c1; addActionListener(this); //  OURSELVES !!! } public void actionPerformed(ActionEvent e) { setFromColor(c); }

Abstract class: ButtonAdapter abstract class ButtonAdapter extends Jbutton implements ActionListener { public ButtonAdapter(String name) { super(name); addActionListener(this); } public void actionPerformed(ActionEvent e) { pressed(); } public abstract void pressed(); }

Usage Use with anonymous class: JPanel p = new JPanel(); p.add(new ButtonAdapter(“Quit”) { public void pressed() { System.exit(0); } } );

MouseListener Interface Five events: mousePressed(MouseEvent e) mouseReleased(..) mouseClicked(..) mouseEntered(..) mouseExited(..) tedious to implement all when only one is needed: instead subclass abstract MouseAdapter see also: MouseMotionListener ner.html

Animations: javax.swing.Timer ActionListener incrementYPosition = new ActionListener() { public void actionPerformed(ActionEvent evt) { if (_y < 400) { _y++; if (_frame != null) _frame.repaint(); } else { _timer.stop(); } }; _timer = new javax.swing.Timer(10,incrementYPosition); _timer.start();

Safe loading of an ImageIcon /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = ButtonDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find file: " + path); return null; }

ButtonDemo action method public void actionPerformed(ActionEvent e) { if ("disable".equals(e.getActionCommand())) { b2.setEnabled(false); b1.setEnabled(false); b3.setEnabled(true); } else { b2.setEnabled(true); b1.setEnabled(true); b3.setEnabled(false); }

Setting up a button b1 = new JButton("Disable middle button", leftButtonIcon); b1.setVerticalTextPosition(AbstractButton.CENTER); //aka LEFT, for left-to-right locales b1.setHorizontalTextPosition(AbstractButton.LEADING) b1.setMnemonic(KeyEvent.VK_D); b1.setActionCommand("disable"); b1.addActionListener(this); b1.setToolTipText("Click this button to disable the middle button.");

JCheckbox Maintain/display labeled binary state (on/off, yes/no, selected/unselected) getLabel(), setLabel(String), isSelected(), setSelected() also: an ItemListener for an ItemEvent

Trivial example import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CheckBoxTest extends JFrame { private JCheckBox cb = new JCheckBox("off"); public static void main(String[] args) { CheckBoxTest w = new CheckBoxTest(); w.show(); }

cont. public CheckBoxTest() { setTitle("CheckBoxTest"); setSize(300,70); cb.addItemListener(new CheckBoxTestListener()); add("Center", cb); } private class CheckBoxTestListener implements ItemListener { public void itemStateChanged(ItemEvent e) { cb.setLabel( (cb.isSelected()) ? "ON" : "OFF"); }

RadioButtonDemo public class RadioButtonDemo extends JPanel implements ActionListener { static String birdString = "Bird"; …. JRadioButton birdButton = new JRadioButton(birdString); birdButton.setMnemonic(KeyEvent.VK_B); birdButton.setActionCommand(birdString); birdButton.setSelected(true);.... ButtonGroup group = new ButtonGroup(); group.add(birdButton); group.add(catButton); …

cont. birdButton.addActionListener(this); … JPanel radioPanel = new JPanel(new GridLayout(0, 1)); radioPanel.add(birdButton); … add(radioPanel, BorderLayout.LINE_START); add(picture, BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); public void actionPerformed(ActionEvent e) { picture.setIcon(createImageIcon("images/" + e.getActionCommand() + ".gif")); }

Dialogs Special purpose window displayed shortly To notify, or ask simple questions Always attached to a Frame Modal: demands user response, prevents further actions; show() won’t return until dismissed,  setVisible(false) Nonmodal: actions often placed into separate Thread Dialog dig = new Dialog(this,false);

Dialog example public class DialogTest extends JFrame { public static void main(String[] args) { DialogTest w = new DialogTest(); w.show(); } private JTextArea d = new JTextArea(); private JCheckBox cb = new JCheckBox("Modal Dialog?"); public DialogTest() { setTitle("DialogTest"); setSize(300,220); add("West",cb); add("East",new MakeButton()); add("South",d); }

cont private void makeDialog(boolean modalFlag) { final JDialog dialog = new JDialog(this,modalFlag); dialog.setSize(100,100); dialog.add("North",new CountButton(1)); dialog.add("West",new CountButton(2)); dialog.add("East",new CountButton(3)); dialog.add("South", new ButtonAdapter("Hide") { public void pressed() { dialog.setVisible(false); } }); dialog.show(); }

cont. private class MakeButton extends ButtonAdapter { public MakeButton() { super("Make Dialog"); } public void pressed() { makeDialog(cb.isSelected()); } } private class CountButton extends ButtonAdapter { public CountButton(int value) { super("" + value); } public void pressed() { d.append("Button " + getLabel() + " pressed\n"); } } }

JFileChooser import javax.swing.filechooser.*; fc = new JFileChooser(); public void actionPerformed(ActionEvent e) { if (e.getSource() == openButton) { int returnVal = fc.showOpenDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // … This is where a real application would open the file. log.append("Opening: " + file.getName() + "." + newline); } else { log.append("Open command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength());

JMenuBar Attached to JFrame by setJMenuBar(): JMenuBar bar = new JMenuBar(); setJMenuBar(bar); Add menus: JMenu HelpMenu = new JMenu(“Help”); bar.add(helpMenu); Add menu items: JMenuItem quitItem = new JMenuItem(“Quit”); quitItem.addActionListener(new QuitListener()); helpMenu.add(quitItem);