어디가에 계실 번역자님~~~ 글을 복사한 것에 따른 문의가 있으면 언제든지 연락주세요...
링크로 바꿀께요^^;; 다음에 원문을 혹시나 찾지 못할까봐ㅎㅎ
코드 분석을 위해 새삼스럽게 Java swing 쪽을 잠시 보고 있는데 나름 부담되었는데 도움이 되었다^^
출처 : http://java.sun.com/docs/books/tutorial/uiswing/components/jcomponent.html
JComponent클래스
최상위 컨테이너를 제외하고 이름이 J로 시작하는 모든 Swing콤포넌트는JComponent
클래스를 상속한다.
예를 들면, JPanel, JScrollPane, JButton, JTable등은 모두 JComponent클래스를 상속했다.
그러나, JFrame, JDialog는 그렇지 않은 데, 그것들은 최상위 컨테이너 이다.
JComponent클래스는Container
클래스를 상속하며, Container컨테이너 클래스는 다시Component
클래스를 상속한다.Component클래스는 레이아웃 힌트를 제공하는 것부터 그리기, 이벤트를 제공하는 것까지 모든 것을 포함한다.
Container클래스는 콤포넌트를 컨테이너에 추가하고, 레이아웃을 설정하는 것을 지원한다.
이 문서의 API 표는 JComponent클래스 뿐만이 아니라, Component, Container클래스의 가장 자주 사용되는 메소드들을 요약했다.
JComponent클래스의 기능
JComponent클래스의 기능은 다음 카테고리로 나눌 수 있다.
- 툴팁
- 그리기와 테두리
- 프로그램 전체에 영향을 끼치는 룩앤필
- 사용자정의 속성
- 레이아웃 지원
- 노약자, 장애인을 위한 접근성 지원
- 드랙앤드롭 지원
- 이중 버퍼링
- 키바인딩(Key bindings)
- 툴팁
- setToolTipText메소드로 문자열을 지정하면, 콤포넌트 사용자에게 도움말을 제공할 수 있다.
- 커서가 콤포넌트 위에서 머물면, 콤포넌트 옆의 작은 창에 지정된 문자열이 보인다.
- 더 자세한 정보는 How to Use Tool Tips 을 참조한다.
- 그리기와 테두리
- setBorder메소드는 콤포넌트가 가장자리에 보여주는 테두리를 설정할 수 있도록 한다.
- 콤포넌트 안쪽을 그리기 위해서는 paintComponent메소드를 오버라이드 하면 된다.
- 자세한 내용은 How to Use Borders와 Performing Custom Painting을 참조한다.
- 프로그램 전체에 영향을 끼치는 룩앤필
- 모든 JComponent객체는 그에 해당된는 ComponentUI객체를 가지고 있으며,
- ComponentUI객체는 그리기와 이벤트 처리, 크기조절등의 역할을 행한다.
- 정확히 어떤 ComponentUI객체가 사용되는 지는 현재의 룩앤필에 따라 다르다.
- UIManager.setLookAndFeel메소드를 사용해서 현재의 룩앤필을 설정할 수 있다.
- 자세한 내용은 How to Set the Look and Feel을 참조한다.
- 사용자정의 속성
- 모든 JComponent객체를 한 개 이상의 속성(이름/객체 쌍)과 연관시킬 수 있다.
- 예를 들면, 레이아웃 관리자는 속성을 사용해서 레이아웃 관리자가 관리하는 모든 콤포넌트와 제약 객체(constraints object)를 연관시킬 수 있다. putClientProperty메소드를 이용해서 속성을 설정하고, getClientProperty를 이용해서 속성을 가져온다.
- 속성에 대한 일반적인 정보를 얻고 싶으면 Properties를 참고한다.
- 레이아웃 지원
- AWT의 Component클래스는 getPreferredSize, getAlignmentX와 같은 레이아웃 힌트 메소드는 제공하지만, 이러한 레이아웃 힌트를 설정할 수 있는 방법을 제공하지 않는다. JComponent클래스느 레이아웃 힌트를 설정하는 메소드를 제공한다. setMinimumSize, setMaximumSize, setAlignmentX, setAlignmentY 메소드가 그것이다.
- 더 자세한 정보는 Laying Out Components Within a Container를 참조한다.
- 노약자, 장애인을 위한 접근성 지원
- JComponent클래스는 스크린 리더가 콤포넌트로부터 정보를 가져가는 것을 돕는 등의 접근기술을 도와주는 API와 기본기능이 있다.
- How to Support Assistive Technologies을 참조한다.
- 드래그앤드드롭 지원
- JComponent클래스는 콤포넌트의 이전 처리기(transfer handler)를 설정하는 API를 제공한다.
- 이전 처리기는 Swing 드래그앤드드롭의 기반이 된다.
- 자세한 사항은 Introduction to Drag and Drop and Data Transfer을 참조한다.
- 이중 버퍼링
- 이중 버퍼링(double buffering) 화면에서 부드러운 그리기 동작을 보여준다.
- Performing Custom Painting을 참조한다.
- 키 바인딩
- 이 기능을 사용하면 사용자가 키보드의 특정 키를 누를 때 콤포넌트가 반응하도록 만들 수 있다.
- 예를 들면, 많은 룩앤필의 경우 버튼이 포커스를 가지고 있을 때, 스페이스 키를 누르는 것은 마우스로 클릭하는 것과 동일한 효과를 가진다. 룩앤필은 자동적으로 스페이스키를 누르는 것과 버튼의 결과적인 효과를 바인딩(결속) 시켜준다.
- 더 자세한 정보는 How to Use Key Bindings을 참조한다.
JComponent API
JComponent클래스는 많은 새로운 메소드를 제공하며, Component클래스와 Container클래스로부터 많은 메소드를 상속 받았다. 다음 표는 가장 많이 사용하는 메소드를 요약했다.
- 콤포넌트 외양을 커스터마이징
- 콤포넌트 상태를 설정하거나 가져오기
- 이벤트 처리하기
- 콤포넌트 그리기
- 포함계층구조를 처리하기
- 콤포넌트 레이아웃
- 크기와 위치정보를 가져오기
- 크기와 위치를 지정하기
콤포넌트 외양을 커스터마이스징 메소드 용도 void setBorder(Border)
Border getBorder()콤포넌트의 테두리를 설정하거나 가져온다.
자세한 내용은 How to Use Borders 을 참조한다.void setForeground(Color)
void setBackground(Color)콤포넌트의 전면색상 혹은 배경색상을 설정한다.
전면색상은 주로 콤포넌트 안에 문자를 그려넣는 데 사용되는 색상이다. 배경색상은 콤포넌트가 불투명하다는 전제하에서 콤포넌트의 뒷배경영역의 색상이다.Color getForeground()
Color getBackground()콤포넌트의 전면색상 혹은 배경색상을 가져온다. void setOpaque(boolean)
boolean isOpaque()콤포넌트가 불투명(opaque)한지 여부를 설정하거나 가져온다.
불투명한 콤포넌트는 그 배경을 배경색상을 채워넣는다.void setFont(Font)
Font getFont()콤포넌트의 글꼴을 설정하거나 가져온다.
만약 콤포넌트의 글꼴이 설정되지 않았다면, 부모콤포넌트의 글꼴이 반환된다.void setCursor(Cursor)
Cursor getCursor()커서를 갖다대었을 때 표시되는 커서모양을 설정하거나 가져온다. 예를 들면 aPanel.setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR));
콤포넌트의 상태 설정하기 메소드 용도 void setComponentPopupMenu(String) JComponent객체의 JPopupMenu설정하기.
바인딩을 등록하고 필요한 리스너를 추가해서 적절한 타이밍에 JPopMenu객체가 보여지게 하는 것은 UI가 담당한다.
JPopMenu가 보여지는 시점은 룩앤필에 따라 다르다. 어떤 룩앤필은 마우스 이벤트에 보여줄 것이고, 어떤 이벤트는 키바인딩을 가능하게 할 것이다.
popup이 null이고, getIngeritsPopupMenu가 true를 반환하면, getComponentPopupMenu메소드는 부모객체로 위임될 것이다. 이 방식으로 자식 콤포넌트가 부모 콤포넌트의 popupmenu를 상속할 수 있다.void setTransferHandler(TransferHandler)
TransferHandler getTransferHandler()transferHandler속성을 설정하거나 제거한다.
TransferHandler는 드래그앤드드롭 혹은 클립보드 로 (부터)의 잘라내기, 복사, 붙여넣기를 통해서 데이터를 교환하는 것을 지원한다.
더 자세한 내용은 Introduction to Drag and Drop and Data Transfer을 참조한다.void setToolTipText(String) 툴팁에 보여줄 문자열을 설정한다.
더 많은 정보는 How to Use Tool Tips을 참조한다.void setName(String)
String getName()콤포넌트의 이름을 설정하거나 가져온다.
이 메소드는 텍스트를 표시하지 않는 콤포넌트와 문자열을 연결시킬 때 유용할 수 있다.boolean isShowing() 콤포넌트가 화면에 보여지는 지를 결정한다.
이것의 의미는 콤포넌트가 visible이어야 하고, visible하고 show된 컨테이너에 포함되어야 한다는 의미이다.void setEnabled(boolean)
boolean isEnabled()콤포넌트가 활성화 여부를 설정하거나 가져온다.
활성화된 콤포넌트는 사용자 입력에 반응하고 이벤트를 생성할 수 있다.void setVisible(boolean)
boolean isVisible()콤포넌트가 visible인지를 설정하고 가져온다.
최상위 콤포넌트를 제외한 모든 콤포넌트는 초기값으로 visible하다.
이벤트 처리
(자세한 사항은 Writing Event Listeners을 참조한다.)메소드 용도 void addHierarchyListener(hierarchyListener l)
void removeHierarchyListener(hierarchyListener l)계층구조가 변경되었다는 이벤트를 처리하기 위한 지정된 hierarchy listener를 추가하거나 제거한다.
리스너가 null이면, 예외를 발생시키지 않으며, 아무런 행동도 취해지지 않는다.void addMouseListener(MouseListener)
void removeMouseListener(MouseListener)마우스 리스너(mouse listener)를 추가하거나 제거한다.
마우스 리스너는 사용자가 마우스를 사용해서 콤포넌트와 상호작용을 할 때 통보받는다.void addMouseMotionListener(MouseMotionListener)
void removeMouseMotionListener(MouseMotionListener)마우스 동작 리스너(mouse motion listener )를 추가하거나 제거한다.
마우스 동작 리스너� 사용자가 해당 콤포넌트 안엣 마우스커서를 움직일 대 통보받는다.void addKeyListener(KeyListener)
void removeKeyListener(KeyListener)키 리스터(key listener)를 추가하거나 제거한다.
키 리스너는 콤포넌트가 키보드 포커스를 가지고 있고, 사용자가 키보드를 타이핑하면 통보받는다.void addComponentListener(ComponentListener)
void removeComponentListener(ComponentListener)콤포넌트 리스너(component listener )를 추가하거나 제거한다.
콤포넌트 리스너는 콤포넌트가 숨겨지거나, 보여지거나, 이동하거나, 크기변경이 될 때 통보받는다.boolean contains(int, int)
boolean contains(Point)지정된 점(point)가 콤포넌트 내부에 있는 지 결정한다.
파라메터는 콤포넌트 좌표 시스템으로 지정되어야 한다.
정수값은 각각 x, y값을 나타낸다.Component getComponentAt(int, int)
Component getComponentAt(Point)입력된 x, y지점을 포함하는 콤포넌트를 반환한다.
만약 콤포넌트가 겹쳐져 있다면 가장 왼쪽위 콤포넌트를 반환한다.
이것은 Component.contains()메소드의 인덱스가 0에 제일 가까운 콤포넌를 찾아내는 것으로 결정한다.Component setComponentZOrder(component comp, int index) 지정된 콤포넌트를 컨테이너의 지정된 z축 인덱스로 이동시킨다.
만약 콤포넌트가 다른 컨이너의 자식객체이면, 그 콤포넌트는 이 컨테이너에 추가되기 전에 이전의 컨테이너에서 제거된다.
java.awt.Container.add(Component, int)메소드와 중요한 차이점은 이 메소드는 이전 컨테이너에서 콤포넌트를 제거할 때, 허용되고 필요하지 않다면 removeNotify메소드를 호출하지 않는다는 것이다. 이 방식으로 만약 콤포넌트가 키보드 포커스를 가지고 있다면, 새로운 위치로 이동했을 때에도 키보드 포커스를 유지한다.
참고: z축은 콤포넌트가 그려지는 순서를 결정한다. z축 값이 제일 큰 콤포넌트가 먼저 그려지고, 낮은 z축 값이 가장 낮은 콤포넌트가 가장 늦게 그려진다. 콤포넌트가 겹쳐진다면, z축 값이 낮은 콤포넌트가 z축 값이 높은 콤포넌트 위에 그려진다.
Component getComponentZOrder(component comp)컨테이너 내부의 콤포넌트의 z축 값을 반환한다. z축에서 위에 있을 수록 인덱스 값은 낮다.
z축 값이 가장 낮은 콤포넌트는 가장 늦게 모든 자식 콤포넌트 위에 그려진다.
콤포넌트 그리기
(자세한 사항은 Performing Custom Painting을 참조한다.)메소드 용도 void repaint()
void repaint(int, int, int, int)콤포넌트의 전체가 다시 그려지도록 요청한다.
4개의 int형 파라메터는 다시 그릴 경계선을 지정하며, x, y, 폭, 높이를 의미한다.void repaint(Rectangle) 콤포넌트 내의 지정된 영역이 다시 그려지도록 요청한다. void reval!idate() 콤포넌트와 해당 컨테이너가 레이아웃을 다시 잡도록 요청한다. 콤포넌트가 visible된 이후에 명시적으로 크기조절, 정열 힌트 변경 조절, 포함계층구조 변경등을 하지 않았다면 이 메소드를 호출할 필요할 필요가 없다.
reval!idate메소드를 호출한 다음에는 항상 repaint메소드를 호출하도록 한다.void paintComponent(Graphics) 콤포넌트를 그린다.
이 메소드를 오버라이드해서 사용자정의 콤포넌트의 그리기를 구현한다.
포함계층구조 다루기
(더 자세한 내용은 최상위 컨테이너를 참조한다.)메소드 용도 Component add(Component)
Component add(Component, int)
void add(Component, Object)지정된 콤포넌트를 이 컨테이너에 추가한다. 파라메터가 1개 사용되는 것은 콤포넌트를 컨테이너의 끝에 추가한다. int형 파라메터는 컨테이너 내의 새로운 콤포넌트의 위치를 표시한다. Object형 파라메터는 현재의 레이아웃 관리자에게 레이아웃 제한을 제공한다. void remove(int)
void remove(Component)
void removeAll()이 컨테이너에서 1개 혹은 모든 콤포넌트를 제거한다.
int형 파라메터는 콤포넌트를 제거할 컨테이너 내부의 위치를 나타낸다.JRootPane getRootPane() Get the root pane that contains the component. Container getTopLevelAncestor() Get the topmost container for the component — a Window
,Applet!
, or null if the component has not been added to any container.Container getParent() Get the component's immediate container. int getComponentCount() Get the number of components in this container. Component getComponent(int)
Component[] getComponents()Get the one of or all of the components in this container. The int
argument indicates the position of the component to get.Component getComponentZOrder(int)
Component[] getComponentZOrder()Returns the z-order index of the component inside the container. The higher a component is in the z-order hierarchy, the lower its index. The component with the lowest z-order index is painted last, above all other child components.
Laying Out Components
(see Laying Out Components Within a Container for more information)Method Purpose void setPreferredSize(Dimension)
void setMaximumSize(Dimension)
void setMinimumSize(Dimension)Set the component's preferred, maximum, or minimum size, measured in pixels. The preferred size indicates the best size for the component. The component should be no larger than its maximum size and no smaller than its minimum size. Be aware that these are hints only and might be ignored by certain layout managers. Dimension getPreferredSize()
Dimension getMaximumSize()
Dimension getMinimumSize()Get the preferred, maximum, or minimum size of the component, measured in pixels. Many JComponent classes have setter and getter methods. For those non- JComponent
subclasses, which do not have the corresponding setter methods, you can set a component's preferred, maximum, or minimum size by creating a subclass and overriding these methods.void setAlignmentX(float)
void setAlignmentY(float)Set the alignment along the x- or y- axis. These values indicate how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, and 0.5 is centered, and so on. Be aware that these are hints only and might be ignored by certain layout managers. float getAlignmentX()
float getAlignmentY()Get the alignment of the component along the x- or y- axis. For non- JComponent
subclasses, which do not have the corresponding setter methods, you can set a component's alignment by creating a subclass and overriding these methods.void setLayout(LayoutManager)
LayoutManager getLayout()Set or get the component's layout manager. The layout manager is responsible for sizing and positioning the components within a container. void applyComponentOrientation(ComponentOrientation)void setComponentOrientation(ComponentOrientation) Set the ComponentOrientation
property of this container and all the components contained within it. See Setting the Container's Orientation for more information.
Getting Size and Position Information Method Purpose int getWidth()
int getHeight()Get the current width or height of the component measured in pixels. Dimension getSize()
Dimension getSize(Dimension)Get the component's current size measured in pixels. When using the one-argument version of this method, the caller is responsible for creating the Dimension
instance in which the result is returned.int getX()
int getY()Get the current x or y coordinate of the component's origin relative to the parent's upper left corner measured in pixels. Rectangle getBounds()
Rectangle getBounds(Rectangle)Get the bounds of the component measured in pixels. The bounds specify the component's width, height, and origin relative to its parent. When using the one-argument version of this method, the caller is responsible for creating the Rectangle
instance in which the result is returned.Point getLocation()
Point getLocation(Point)Gets the current location of the component relative to the parent's upper left corner measured in pixels. When using the one-argument version of getLocation
method, the caller is responsible for creating thePoint
instance in which the result is returned.Point getLocationOnScreen() Returns the position relative to the upper left corner of the screen. Insets getInsets() Get the size of the component's border.
Specifying Absolute Size and Position
(see Doing Without a Layout Manager (Absolute Positioning) for more information)Method Purpose void setLocation(int, int)
void setLocation(Point)Set the location of the component, in pixels, relative to the parent's upper left corner. The two int
arguments specify x and y, in that order. Use these methods to position a component when you are not using a layout manager.void setSize(int, int)
void setSize(Dimension)Set the size of the component measured in pixels. The two int
arguments specify width and height, in that order. Use these methods to size a component when you are not using a layout manager.void setBounds(int, int, int, int)
void setBounds(Rectangle)Set the size and location relative to the parent's upper left corner, in pixels, of the component. The four int
arguments specify x, y, width, and height, in that order. Use these methods to position and size a component when you are not using a layout manager.
댓글 없음:
댓글 쓰기