Download presentation
Presentation is loading. Please wait.
Published byJoonas Mäkelä Modified 6년 전
1
Java AWT Computer Programming Distributed Computing System Laboratory
Department of Computer Science and Engineering Seoul National University, Korea 05/30/2017
2
Overview AWT Basic Using AWT AWT Event Handling More Details
3
What is AWT? Abstract Window Toolkit Class for graphic features Roles
Features supported by most GUI platform Classic Windows programming method System dependent heavyweight component java.awt.* Roles Control and manage graphic context Print out figures and text Control and manage image related resources 고전적인 윈도우 프로그래밍 방식 GUI 관련 그래픽이 실행되는 시스템에 의존 Heavyweight component 이러한 단점 때문에 Swing이 개발됨 Swing은 경량 컴포넌트임 Java.awt.* 코드 작성시 반드시import해야한다 그래픽 컨텍스트 제어 및 관리 색, 폰트, 좌표, 클리핑, 그리기 모드 등의 정보를 저장하고 제어 도형과 텍스트 출력 문자열과 직선, 사각형등 각종 도형을 그리는 기능 이미지 관련 이미지를 출력하거나 복사 할 수 있는 기능 Swing 운영 환경에 영향을 받지 않고 동일한 화면을 보여줄 수 있도록 시스템에 대한 의존도를 최소화하고 각종 컴포넌트들을 자바에서 직접 그려서 구현을 하였다. 따라서 여러 환경에서 동일한 모습을 보일 수 있도록 구현되었으나 대신 해당 시스템의 고유한 모습을 보여줄 수 없다. AWT와의 비교[편집] 이 부분의 본문은 AWT입니다. AWT는 시스템의 그래픽 컴포넌트를 직접 사용하여 해당 시스템의 모습을 그대로 구현한다. 또한 스레드 보안(Thread Safe)이 되어 있어 스윙과 비교하여 컴포넌트의 업데이트에 문제가 발생하지 않는다. 또한 최소 JDK 1.2, 혹은 성능을 위하여 더 최신의 JVM이 필요한 스윙에 비하여 AWT는 자바에서 지원하는 최초의 그래픽 툴킷으로 버전에 상관없이 모든 JVM에서 사용 가능하다. 마이크로소프트가 썬 마이크로시스템즈와의 자바 사용권에 대한 재판에서 패소함에 따라 신규 JVM을 지원하지 않고 있는데 MS의 기존 JVM에서도 AWT는 사용이 가능하다.(2007년 12월 31일로 만료됨) [2] 그러나 자바 1.2 이후 컴포넌트의 제약에도 불구하고 Java2D, Java3D 등의 풍부한 그래픽 환경을 제공한다.
4
Why should we know AWT? Types of user interface
CUI (Character User Interface) GUI (Graphical User Interface) Most programs we use are based on GUI Windows, Media Player, Editplus, etc. In java, we can use AWT & Swing
5
AWT Component
6
How to use AWT component
1. Create component Button myButton= new Button("myButton"); 2. Add the component on container add(myButton); 3. Create Event handling routine and add EventListener MyActionListener mal= new MyActionListener(); myButton.addActionListener(mal);
7
Overview AWT Basic Using AWT AWT Event Handling More Details
8
Event Event Event-based programming
An event user takes act on UI component Event-based programming Program listens event from user and respond for the event while in infinite loop
9
Handling event java.awt.event Mandatory event handler model
Provides various event listener and handler interface and classes for AWT component Interface : xxxListener,… Class : xxxEvent, xxxAdapter,… Mandatory event handler model Add eventListener class to component(event source) Handling specific events
10
Types of Event Low-Level Event & Semantic Event
Handling semantic event is a bit more efficient usually Semantic Event Secondary events from low-level event Mouse click ㄴ> 2 Low level events : Clickstart, Clickend Handle with action event Low-Level Event System-level events occurred from user input or component function Example : java.awt.event.ComponentEvent java.awt.event.FocusEvent java.awt.event.KeyEvent java.awt.event.MouseEvent java.awt.event.WindowEvent Example : java.awt.event.ActionEvent java.awt.event.AdjustmentEvent java.awt.event.ItemEvent java.awt.event.TextEvent While FocusEvent, KeyEvent, MouseEvent and ComponentEvent can ocurr in any Component; the semantics one, ItemEvent, TextEvent, AdjustmentEvent and ActionEvent are related with a particular type of component. Semantics events somehow have a meaning:
11
Calling eventListener
processEvent Calls eventListener when event happens (Listner is often called Handler) ex) FocusEvent processEvent => processFocusEvent => Create FocusListener instance and handle processEvent processComponentEvent processKeyEvent processMouseEvent processFocusEvent FocusListener 생성 후 ID 에 따라 처리함
12
Event & EventListener Event classes categorized by components that events can occur in Event class has appropriate information and methods Events are provided for components ex:) Events for Button ActionEvent, ComponentEvent, FocusEvent, KeyEvent, MouseEvent Component that ActionEvent can happen Button, List, MenuItem, TextField Check API documents for detail
13
Hierarchy
14
Event & EventListener Listerner is interface for event handling
Event class(xxxEvent) corresponds to Event Listener Interface(xxxListener) In eventListener class, methods for handling low-level events exists ex:) KeyListener for KeyEvent void keyPressed(KeyEvent e) void keyReleased(KeyEvent e) void keyTyped(KeyEvent e)
15
Handling event Select Event to handle Define class for eventListener
ex:) ActionEvent Define class for eventListener MyListener for ActionListener Class MyListener implements ActionListner{ …} Method : void actionPerformed(ActionEvent e) has to be implemented Each Listener has its own methods to implement See API Documentation Create instance and add it as eventListener for component this.addActionListener(new MyListener());
16
Event Adapter Easy handling for low-level events
For Listener interface with more than 2 event handling methods, there exists implemented Adapter class Each event handler methods are empty If Adapter class exists, define class that extends Adapter instead of implementing listener It is a pattern which provides default implementation of interface or abstract class. - Adapter class provides the default implementation of all the methods in an event listener interface. - Usually adapter classes ease the programmers by providing the implementations of the listener interfaces instead of having to implement them. This is where the event adapter class comes into picture. - These classes are useful when you want to process only few of the events that are handled by a particular event listener interface. Advantage - It increases the transparency of classes. - It makes a class highly reusable. - It provides a pluggable kit for developing application. - It provides a way to include related patterns in a class. - Using adapters it helps to reduce the clutter in your code. Overriding
17
ActionEvent & ActionListener
Major Method of ActionListener void actionPerformed(ActionEvent ev) When event occurs Clicking Button Clikcing Menu entry Pressing Enter key in TextField Double-clicking entry of the list Major methods for ActionEvent String getActionCommand() Return the name of command Object getSource() Method overrided from EventObject
18
WindowEvent & WindowListener
Major methods for WindowListener Case that causes change of condition fo window void windowActivated(WindowEvent ev) void windowClosed(WindowEvent ev) Major methods for WindowEvent int getNewState() 0 for normal state int getOldState() Window getWindow()
19
ItemEvent & ItemListner
Major methods for ItemListener void itemStateChanged(ItemEvent ev) Selecting/Deselecting items from Checkbox, CheckboxMenuItem, Choice, List Major methods for ItemEvent Object getItem() int getStateChange() String paramString()
20
AdjustmentEvent & AdjustmentListener
Major methods for AdjustmentListener void adjustmentValueChanged(AdjustmentEvent ev) Case that causes change of condition of scroll bar Major methods for AdjustmentEvent int getValue() int getAdjustmentType() UNIT_INCREMENT, UNIT_DECREMENT, BLOCK_INCREMENT,BLOCK_DECREMENT, TRACK
21
KeyEvent & KeyListener
KeyEvent occurs when events related to keystroke happens Major methods for KeyListener keyPressed(KeyEvent ev) keyReleased(KeyEvent ev) keyTyped(KeyEvent ev) Major methods for KeyEvent char getKeyChar() int getKeyCode() int getKeyLocation() static String getKeyText(int keyCode) static String getKeyModifiersText(int)
22
MouseEvent & Related Listeners
MouseEvent occurs when events related to mouse happens Major methods for MouseListener mouseClicked(MouseEvent ev) mousePressed(MouseEvent ev) mouseReleased(MouseEvent ev) Major methods for MouseMotionListener mouseDragged(MouseEvent ev) mouseMoved(MouseEvent ev) Major methods for MouseEvent int getButton() Point getPoint()
23
TextEvent & FocusEvent
Methods of TextListener textValueChanged(TextEvent ev) Case that causes change of condition of TextArea & TextField Methods of FocusListener Case when component gain or loses input focus focusGained(FocusEvent ev) focusLost(FocusEvent ev)
24
Overview AWT Basic Using AWT AWT Event Handling More Details
25
Graphic context Environment for Graphic operations
ex:) coordinate system, background color, fonts, etc. Major attribute Graphic context handles Object to do graphic works Coordinate System Current clipping area Clipping area : area to do re-drawing Current color & font 그리기 작업을 할 객체 : 그래픽 객체가 실제 그리기 작업을 할 대상 객체 좌표계 : 그리기의 기준이 되는 좌표 정보 현재 클리핑 영역 : 클리핑 정보 클리핑 영역은 다시 그려야 할 영역 표시 현재 색과 폰트 : 그리기 작업에 사용할 색과 폰트 정보
26
Coordinate system (0, 0) for left-upmost
X-axis increases towards right Y-axis increases towards down 컴포넌트 (0, 0) (width-1, height-1) 예) width * height square
27
Layout manager Manage placement Types of Layout
Manage positions of components attached on Container Types of Layout BorderLayout BoxLayout CardLayout FlowLayout GridBagLayout GridLayout SprintLayout
28
Role of Layout manager No Layout Manager With Layout Manager
29
How to assign Layout Create Layout manager
BorderLayout bm= new BorderLayout(); Set layout manager for component setLayout(bm); Add Compoment add(myButton); Check API Documentations, for method varies for each layouts
30
BorderLayout
31
BorderLayout When adding component, You can select position with arguments public LayoutFrame(){ setLayout(new BorderLayout()); add(new Button("North"), BorderLayout.NORTH); add(new Button("South"), BorderLayout.SOUTH); add(new Button("East"), BorderLayout.EAST); add(new Button("West"), BorderLayout.WEST); add(new Button("Center"), BorderLayout.CENTER); }
32
Color & Font Color Use R,G,B and alpha value to give color to component Constructors Color(float r, float g, float b, float a) Color(int r, int g, int b, int a) Font Shape and size of texts printed out on screen BOLD, ITALIC, PLAIN Major methods getFont(), setFont(Font font)… Check API Documentation
33
Drawing figure Drawing inside : fillArc, fillRect…
Drawing outside : drawArc, drawRect… Line : 두께 1인 직선 Rect : 직사각형 3Drect : 3차원으로 입체감 있는 사각형 RoundRect : 모서리 둥근 사각형 Oval : 타원 Arc : 원호, 원의 일부 자른 모양 Polygon : 다각형. 시작점과 끝점 이어 만듬 Type of Figures
34
Drawing figure Draw line Draw rectangular Draw oval & arc
drawLine(int x1, int y1, int x2, int y2) Draw rectangular drawRect(int x, int y, int width, int height) draw3DRect(), drawRoundRect(), fillRect()… Draw oval & arc Designate rectangular that oval will be drawn inside Oval is drawn inscribed in the rectangular Drawing starts at three o’clock and go counterclockwise with angle
35
Drawing String Draws with method like drawString()
Give font characteristics by FontMetrics Fonts have variable width Characters have its own width
36
Q&A Q&A
37
Toolkit class Parent class of object in AWT GUI toolkit Abstract Class
Create components of AWT Connect with native component of system Abstract Class Get class from Toolkit.getDefaultToolkit or getToolkit method of Component getImage() returns image object immediately java.awt.Toolkit 주요 메소드 Dimension getScreenSize() 스크린의 전체 크기를 얻는다 int getScreenResolution() 스크린의 해상도를 얻는다 (DPI: dots per inch) Image getImage(String filename) 주워진 파일의 이미지를 가져온다 getImage(URL url) 주어진 URL의 이미지를 가져온다
38
Toolkit example Toolkit example for getting information
public void test() { Toolkit toolkit = getToolkit(); Dimension dim = toolkit.getScreenSize(); toolkit.setDynamicLayout(true); add(new Label("운영체제 : "+System.getProperty("os.name"))); add(new Label("화면 크기 : "+dim.getWidth()+" * "+dim.getHeight())); add(new Label("화면 해상도 : "+oolkit.getScreenResolution()+"DPI")); add(new Label("가로 최대화 : "+toolkit.isFrameStateSupported(Frame.MAXIMIZED_HORIZ))); add(new Label("세로 최대화 : "+toolkit.isFrameStateSupported(Frame.MAXIMIZED_VERT))); add(new Label("Dynamic Layout : "+toolkit.isDynamicLayoutActive())); }
39
Drawing Image drawImage(Image img, int x, int y, Color bgcolor, ImageObserver obs) Draw image at (x,y) position, with colors filled with bgcolor ImageObserver For bigger image resources, ImageObserver object first loads image data and draw image with imageUpdate() method Image zoom in/out Easily done by argument of drawImage() method
40
Managing image resources
Flatform other than java Stop other operation while loading image When created image object, load all data at once Java flatform 이미지 객체 생성 메소드 호출시 즉각 반환, 배후의 스레드가 로딩작업 처리. ex:) Printing operation when image data is not fully ready 자바이외의 플랫폼에서는 데이터가 완전히 로딩 될 때까지 기다린 후 출력 작업 시행 자바 플랫폼에서는 현재 도달한 이미지를 가지고 출력 작업 처리
41
Printing image on screen
1. Get URL, file name of image file 2. Get Toolkit object 3. Call the image 4. Prepare Image 5. Print out Image URL url = getClass().getResource(file_name); Toolkit toolkit = Toolkit.getDefaultToolkit(); Image img = toolkit.getImage(url); 사용법 URL url = new URL(" imgExample = getToolkit().getImage(url); 생성자 내용 public void paint(Graphics g){ if ( getToolkit().prepareImage(imgExample, -1, -1, this) == false ) { g.drawString("Wait for Loading", 100, 100); } else { g.drawImage(imgExample, 10, 10, this); } Paint 메소드
42
Image Button Add image into buttons ImageButton.java
public void paint(Graphics g){ if (xImage == null) super.paint(g); else { /* 이미지를 버튼의 중앙에 그린다. */ g.drawImage( xImage , (getWidth() - xImage.getWidth(this)) /2 , (getHeight() - xImage.getHeight(this)) /2 , this ); }
43
Menu Configuration
44
메뉴 만드는 법 메뉴가 붙을 메뉴바 생성 메뉴 생성 메뉴 아이템을 만들어 메뉴에 추가 메뉴바에 메뉴 추가
MenuBar myMenuBar= new MenuBar(); 메뉴 생성 Menu myMenu= new Menu("내 메뉴"); 메뉴 아이템을 만들어 메뉴에 추가 MenuItem myMenuItem= new MenuItem("내 아이템"); myMenu.add(myMenuItem); 메뉴바에 메뉴 추가 myMenuBar.add(myMenu); 프레임에 메뉴바를 설치 Frame myFrame= new Frame(); myFrame.setMenuBar(myMenuBar);
45
체크박스 메뉴 ... Menu myMenu= new Menu("내 메뉴");
CheckboxMenuItem myCheckboxMenuItem= new CheckboxMenuItem("내 체크박스메뉴"); myMenu.add(myCheckboxMenuItem); MenuItem 대신 CheckboxMenuItem 사용
46
서브 메뉴 ... Menu myMenu= new Menu("내 메뉴");
Menu mySubMenu= new Menu("내 서브메뉴"); MenuItem mySubMenuItem= new MenuItem("내 서브메뉴 아이템"); mySubMenu.add(mySubMenuItem); myMenu.add(mySubMenu); MenuItem 대신 Menu 사용
Similar presentations