Java v rytme Swingu (vývoj okienkových aplikácií)

Slides:



Advertisements
Similar presentations
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Advertisements

Graphical User Interfaces
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Graphic User Interfaces Layout Managers Event Handling.
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
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.
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.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
GUI Tutorial Day 3. Custom Dialog Create, display, hide, retrieve information.
© L.Lúcio, An example GUI in Java n Two graphic libraries in Java u AWT u Swing n Swing is more recent than AWT: u Built on top of AWT classes;
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Java GUI building with the AWT. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in most Java textbooks Adequate for many.
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 Swing Chris North cs3724: HCI. AWT to Swing AWT: Abstract Windowing Toolkit import java.awt.* Swing: new with Java2 import javax.swing.* Extends.
Combo Box, Check Boxes, and Radio Buttons. Radio Buttons User can click radio buttons, just like other buttons BUT Radio buttons are mutually exclusive.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Layout Management Containers can arrange their components. Our container is a JPanel, and it can set the way it’s components will be laid out : mypanel.setLayout.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
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.
Java GUIs and Graphics CNS Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Java GUI building with Swing. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Swing [part.1] Taken from Water Milner Eriq Muhammad Adams J |
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
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.
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.
CS Fall 2012, Lab 09 Haohan Zhu. Boston University Slideshow Title Goes Here CS Fall 2012, Lab /20/2015 GUI - Graphical User Interface.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
1 Class 6. 2 Objectives Objectives Enable your applications to perform actions in response to JButton clicks Get the text the user enters in a textfield.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
1 Chapter 16: Creating Windows. 2 Basics of GUI Programming How to create a Window. TryWindow.java You always need a JFrame component before creating.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Atomic Force Microscopy
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Swing and Events Chris North cs3724: HCI. Presentations nadine edwards, steve terhar Vote: UI Hall of Fame/Shame?
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.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
GUI Programming in Java Hao Jiang Boston College April, 2009.
©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
Modular Event Handling
GUIs and Events Rick Mercer.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
GUI building with the AWT
Graphical User Interfaces -- GUIs
GUIs Model/View/Controller Layouts
A Quick Java Swing Tutorial
MVC Paradigm The MVC paradigm breaks applications or interfaces into three parts: the model, the view, and the controller. A --> 25 % B --> 60 % C -->
Typy informácií a ich prezentácia a spracovanie
תכנות מכוון עצמים בשפת JAVA
GUI building with the AWT
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Advanced Programming in Java
어서와 Java는 처음이지! 제13장 실전프로젝트.
GUI building with the AWT
Presentation transcript:

Java v rytme Swingu (vývoj okienkových aplikácií) Róbert Novotný robert.novotny@upjs.sk

Prečo? Načo? Začo? grafické rozhranie (GUI) je v súčasnosti už štandardom bežný používateľ sa stretáva takmer výhradne len s nimi textový procesor, prehliadač, kalkulačka... spoločným úsilím bez ohľadu na jazyk je uľahčiť vývoj aplikácií (najlepšie vizuálne) poskytnúť multiplatformnosť

História inde úspešné pokusy o rýchly návrh už v minulosti Borland Delphi (Pascal, od 1995) prvý RAD (rapid app. development) grafický návrh. Komponenty vkladáme do formulára. Výzor pri návrhu je rovnaký ako počas behu. Dopíšeme lepiaci kód a ideme. légie nasledovníkov Visual Basic [Pascal], C++ Builder [C++], Visual Studio.NET [C#]

Java a GUI Java nemohla nepokryť túto oblasť už od počiatku pokryla ju však veľmi povážlivým spôsobom v súčasnosti hneď tri knižnice pre vývoj AWT (prapôvodná knižnica) zobrazovanie ovládacích prvkov ponecháva na OS: natívny vzhľad, ale množstvo problémov s prenositeľnosťou Swing (druhý pokus) NetBeans značne vylepšený návrh, v súčasnosti štandard. vykreslenie si rieši samo. Aplikácie vyzerajú jednotne, možnosť používať Look & Feel (alias skiny) SWT (IBM) Eclipse zobrazenie prvkov rieši OS: natívny vzhľad, ale potreba medziknižnice – limitovaný počet platform

Swing – základné prvky komponenty komponenty sú v kontajneroch – všetko s čím sa dá interagovať ovládacie prvky, teda okná, gombíky, tlačidlá, rozbaľovacie boxy, ... komponenty sú v kontajneroch okno obsahuje panel, ktorý obsahuje panel, ktorý obsahuje, ..., ktorý obsahuje gombík komponenty reagujú na udalosti interakciou s komponentom generujeme udalosti klik na gombík, pohyb myšou, výber položky v zozname.... komponent môže mať model model poskytuje dáta, komponent ich zobrazuje dáta: zoznam, model: prostredník, komponent: rozbaľovací box

Swing – návrh aplikáciu možno navrhovať vizuálne alebo ručne (písaním kódu) vizuálne – vývojové prostredie poskytuje možnosť tvorby formulárov, vkladania komponentov, dodávanie kódu pre obsluhu udalostí... NetBeans IntelliJ IDEA ručne – písaním kódu

Ukážka kódu Prázdny formulár vytvoríme jednoducho: public class MainForm extends JFrame { } public class Runner { public static void main(String[] args) { MainForm mainForm = new MainForm(); mainForm.setBounds(0, 0, 640, 480); mainForm.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE); mainForm.setVisible(true); }

Ukážka kódu Veci môžeme presunúť do konštruktora public class MainForm extends JFrame { public MainForm() { setBounds(0, 0, 640, 480); setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE); } public class Runner { public static void main(String[] args) { MainForm mainForm = new MainForm(); mainForm.setVisible(true): }

Dodáme si prvý gombík okno (JFrame) je ako okno na dome. Má rámec, kľučky, atď. analógia: Vianoce v škôlke lepíme na okno Mikulášov my budeme lepiť na okno ovládacie prvky v skutočnosti ich ale lepíme na sklo sklo = ContentPane postup vytvor inštanciu komponentu nastav jej rozmery, vlastnosti, atď. prilep ju na sklo

Dodáme si prvý gombík gombík s textom OK umiestnený vľavo hore zodpovedá mu trieda JButton public class MainForm extends JFrame { public MainForm() { ... //toto zatiaľ necháme, okomentujeme neskôr setLayout(null); JButton button = new JButton("OK"); button.setBounds(10, 10, 80, 20); getContentPane().add(button); }

Dodáme si prvý gombík môžeme veselo pridávať ďalšie komponenty public class MainForm extends JFrame { public MainForm() { ... JTextField textField = new JTextField("Hello World"); textField.setBounds(10, 50, 80, 20); getContentPane().add(textField); } JTextField – textové políčko

Udalosti na každom ovládacom prvku vieme generovať udalosti príklad: na gombíku JButton vieme vyvolať akciu zoznam podporovaných udalostí zistíme: otvoríme dokumentáciu pohľadáme metódy addXXXListener() popozeráme komentáre k interfejsu XXXListener gombík: addActionListener() interfejst ActionListener

Udalosti - filozofia ovládací prvok je ako rozhlasový vysielač po vyvolaní udalosti oznámi okoliu "Vážení poslucháči, niekto na mne vyvolal udalosť U" každý poslucháč vie na to zareagovať. niekto klikne na gombík (udalosť action) gombík oznámi okoliu "Vážení poslucháči, niekto na mne vyvolal udalosť ActionEvent") každý poslucháč (ActionListener) vie na to zareagovať

Udalosti - filozofia ako vytvorím poslucháča pre udalosť action? vytvorím inštanciu triedy, ktorá implementuje interfejs ActionListener public class SysoutListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Klik!"); } ako docielim, aby poslucháč dostával informácie od gombíka? inštanciu poslucháča zaregistrujem na gombíku

Udalosti - filozofia ako docielim, aby poslucháč dostával informácie od gombíka? inštanciu poslucháča zaregistrujem na gombíku public class MainForm extends JFrame { public MainForm() { ... gombík.addActionListener(new SysoutListener()); }

Udalosti - filozofia anonymné vnútorné triedy – umožňujú na jednom riadku vytvoriť triedu implementujúcu rozhranie vytvoriť jej inštanciu public class SysoutListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Klik!"); } gombik.addActionListener(new SysoutListener()); gombik.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Klik!"); } });

Udalosti – kód generovaný NetBeans-om public class MainForm extends JFrame { public MainForm() { ... gombík.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { gombíkActionPerformed(e); } }); public void gombíkActionPerformed(ActionEvent e) { System.out.println("Klik!");

Layout managery doteraz sme komponenty umiestňovali na vopred danú pozíciu problémy: čo ak chceme meniť veľkosť okna? čo ak máme iný operačný systém? (Linux má väčšie písma a väčšie rozpätia) čo ak máme nastavené písmo veľkosti 20? čo ak potrebujeme lokalizáciu?

Layout managery layout manager – správca rozloženia komponentov poloautomaticky rozhadzuje komponenty po formulári mení ich veľkosť v prípade zmeny veľkosti nadradeného kontajnera na rôzne príležitosti rôzne implementácie null – žiadny LM – komponenty rozhadzujeme ručne FlowLayout – štýl ukladania znakov na riadok CardLayout – komponenty vo viacerých vrstvách (ako karty v balíčku) BoxLayout – komponenty sú ukladané buď vedľa seba alebo nad seba

BoxLayout – ukážka kódu public class MainForm extends JFrame { public MainForm() { setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS)); JButton button = new JButton("OK"); button.setBounds(10, 10, 80, 20); getContentPane().add(button); JTextField textField = new JTextField("Hello World"); textField.setBounds(10, 50, 80, 20); getContentPane().add(textField); }

BoxLayout – ukážka kódu public class MainForm extends JFrame { public MainForm() { setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS)); JButton button = new JButton("OK"); button.setBounds(10, 10, 80, 20); getContentPane().add(button); JTextField textField = new JTextField("Hello World"); textField.setBounds(10, 50, 80, 20); getContentPane().add(textField); }

BorderLayout – štandardný LM pre JFrame public class MainForm extends JFrame { public MainForm() { JButton button = new JButton("OK"); button.setBounds(10, 10, 80, 20); getContentPane().add(button, BorderLayout.SOUTH); JTextField textField = new JTextField("Hello World"); textField.setBounds(10, 50, 80, 20); getContentPane().add(textField, BorderLayout.CENTER); }

Modely model je objekt, ktorý poskytuje komponentu dáta na zobrazenie viacero komponentov môže zobrazovať dáta z modelu odlišným spôsobom (v zozname, tabuľke, ...) ListBox v starom Delphi: jednotlivé položky listboxu sa museli pridať ručne nevýhoda: dáta máme aj v listboxe aj v nejakom poli nevýhoda: musíme synchronizovať dáta v komponente s dátami v poli JList v Swingu pole obalíme ListModelom, ktorý pridáme ku JListu

Príklad modelu pre JList chceme zobrazovať zoznam súborov vyrobíme si vlastnú triedu pre model zoznamu (dedíme od AbstractListModel) public class DirectoryFilesListModel extends AbstractListModel{ private File file; public DirectoryFilesListModel(File file) { this.file = file; } public int getSize() { return file.listFiles().length; public Object getElementAt(int index) { return file.listFiles()[index];

Príklad modelu pre JList model priradíme nasledovne ListModel fileListModel = new DirectoryFilesListModel(new File("D:")) JList listOfFiles = new JList(fileListModel); getContentPane().add(listOfFiles); model je niekedy zamaskovaný, predošlý príklad je ekvivalentný s File[] files = new File("D:").listFiles(); JList listOfFiles = new JList(files); v útrobách JListu sa vytvoril model v niektorých komponentoch model nie je, niekde sa zaobídeme aj bez neho, inde je zase nutnosťou (stromy)