Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Seminar Chapter 4.

Similar presentations


Presentation on theme: "Java Seminar Chapter 4."— Presentation transcript:

1 Java Seminar Chapter 4

2 래퍼클래스(Wrapper Class)

3 Wrapper Class int나 float, double같은 기본타입들은 클래스 타입이 아니므로 메소드나 필드를 가질 수 없다. 그런데 기본타입을 클래스처럼 사용하고 싶다면?

4 Wrapper Class public class Main {
public static void main(String []args) { Integer i = 10; Float f = 3.14f; Character c = 'A'; System.out.println(i.toString()); System.out.println(f.compareTo(3.15f)); System.out.println(c.toString()); }

5 일반화 프로그래밍과 Generic

6 Generic package com.jiharu.generic; public class Point { int x; int y;
} 만약 int형 필드가 아니라 다른 타입을 원한다면?

7 Generic package com.jiharu.generic; public class Point<E> { E x;
E y; } Generic으로 만들면 타입 자체를 일종의 변수로 지정할 수 있다.

8 Generic package com.jiharu.generic; public class Point<E> {
private E x; private E y; public Point(E x, E y) { this.x = x; this.y = y; } public E getX() { return x; public void setX(E x) { this.x = x; } public E getY() { return y; public void setY(E y) { this.y = y; @Override public String toString() { return "Point [x=" + x + ", y=" + y + "]";

9 Generic package com.jiharu.generic; 제네릭 인자로 class만 가능
public class Main { public static void main(String[] args) { Point<Integer> pi = new Point<Integer>(10, 20); Point<String> ps = new Point<String>("10단위", "20단위"); Point<Float> pf = new Point<>(3.5f,6.7f); System.out.println(pi.toString()); System.out.println(ps.toString()); System.out.println(pf.toString()); } 제네릭 인자로 class만 가능

10 Event

11 Event

12 Event JButton []btn = new JButton[4]; for (int i = 0; i < 4; i++) {
btn[i] = new JButton(i + "번"); rightPn.add(btn[i]); } rightPn.setLayout(new GridLayout(4, 1)); pn.setLayout(new GridLayout(1, 2)); fr.setContentPane(pn); pn.setBackground(new Color(255, 125, 125)); rightPn.setBackground(new Color(125, 255, 125)); lbl.setHorizontalAlignment(SwingConstants.CENTER); pn.add(lbl); pn.add(rightPn); fr.setSize(600, 400); fr.setVisible(true); package com.jiharu.main; import java.awt.Color; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; public class Main { public static void main(String[] args) { String result = "누른 버튼 : "; JFrame fr = new JFrame("This 프레임"); JPanel pn = new JPanel(); JPanel rightPn = new JPanel(); JLabel lbl = new JLabel(result);

13 Event 버튼을 누르면 옆 레이블에 무슨 버튼을 눌렀는지 뜨게하자!

14 Event-Action Action 이벤트는 각 컴포넌트별로 그 컴포넌트에 가장 어울리는 행동을 했을때 작동하는 기본적인 이벤트. 버튼은 보통 누르기 위해서 사용하므로 눌렀을 때 이벤트 발생.

15 Event-Action JButton []btn = new JButton[4];
for (int i = 0; i < 4; i++) { btn[i] = new JButton(i + "번"); rightPn.add(btn[i]); btn[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton thisButton = (JButton) e.getSource(); lbl.setText(result+thisButton.getText()); } }); rightPn.setLayout(new GridLayout(4, 1)); pn.setLayout(new GridLayout(1, 2)); fr.setContentPane(pn); pn.setBackground(new Color(255, 125, 125)); rightPn.setBackground(new Color(125, 255, 125)); lbl.setHorizontalAlignment(SwingConstants.CENTER); pn.add(lbl); pn.add(rightPn); fr.setSize(600, 400); fr.setVisible(true); package com.jiharu.main; import java.awt.Color; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; public class Main { public static void main(String[] args) { String result = "누른 버튼 : "; JFrame fr = new JFrame("This 프레임"); JPanel pn = new JPanel(); JPanel rightPn = new JPanel(); JLabel lbl = new JLabel(result);

16 Event-Action 누른 버튼의 번호가 레이블에 표 시된다.

17 Event-Action AectionEvent 일어난 이벤트 AectionListener 해당 이벤트를 감지하는 이벤트 리스너
btn[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton thisButton = (JButton) e.getSource(); lbl.setText(result+thisButton.getText()); } }); AectionListener 해당 이벤트를 감지하는 이벤트 리스너 e.getSource() 일어난 이벤트를 발생시킨 컴포넌트(이벤트 소스)

18 Event-Key Keyboard를 눌렀을 때 발생하는 이벤트
모든 컴포넌트가 이벤트가 발생하는게 아니라 포커스를 가져야만 발생함.

19 Event-Key JLabel lbl = new JLabel("Label");
JTextField tf = new JTextField(); JButton btn = new JButton("Button"); JList<String> ls = new JList<>(); ls.setListData(list); lbl.addKeyListener(new MyKeyListener()); tf.addKeyListener(new MyKeyListener()); btn.addKeyListener(new MyKeyListener()); ls.addKeyListener(new MyKeyListener()); pn.add(lbl); pn.add(tf); pn.add(btn); pn.add(ls); fr.setContentPane(pn); fr.setSize(500, 500); fr.setVisible(true); } package com.jiharu.main; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JList; import javax.swing.JTextField; public class Main { public static void main(String[] args) { String []list = {"자바","파이썬","R"}; JFrame fr = new JFrame("This 프레임"); JPanel pn = new JPanel(); pn.setLayout(new GridLayout(2, 2));

20 Event-Key public class MyKeyListener implements KeyListener{ @Override
public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { System.out.println(e.getSource().getClass().getName()); public void keyTyped(KeyEvent e) {

21 Event-Key 레이블에서는 키이벤트가 동작하지 않는다. 이유는 포커스 때문!

22 Event-Key key event keyTyped - 키가 타이핑 됬을때 발생하는 이벤트. 말그대로 타이핑이 되야하므로 타이핑이 되지 않는 보조키는 작동치 않음. keyReleased - 어떤 키던 상관없이 키가 놓아졌을 때 발생하는 이벤트 keyPressed - 어떤 키던 상관없이 키가 눌러졌을 때 발생하는 이벤트

23 Event-Key KeyEvent메소드 (e.으로 사용)
getKeyChar - 타이핑된 key값을 반환. 사실상 키보드랑은 무관하게 타이핑된 값을 반환. getKeyCode - 타이핑된 키보드의 배치에 따른 값을 정수로 반환. 이 메소드덕분에 왼쪽 ctrl과 오른쪽 ctrl들을 구별가능 getkeyLocation -  키보드의 배치를 총 4군데로 나누는데 1이 키보드 전체, 2가 왼쪽 보조키, 3이 오른쪽 보조키, 4가 키패드 paramString - key보드에 관련된 전체 파라메터 반환 getWhen - 얼마나 눌러졌는지 isControlDown - Control이 눌러졌는지 isShiftDown - Shift가 눌러졌는지 isAltDown - Alt가 눌러졌는지 isMetaDown = Meta키가 눌러졌는지(맥으로 따지면 cmd, 윈도우에서는 window,몇몇 키보드에 존재하는 meta(◇)키)

24 Event-Mouse Mouse의 움직임을 감지하는 리스너
다른 리스너들과 다르게 총 4가지(사실상 3가지)의 리스너가 존재한다.

25 Event-Mouse MouseListener 시리즈
MouseMotionListener : Mouse가 드래그 됬는지, 움직였는지를 포착 MouseInputListener : MouseListener + MouseMotionListener MouseWheelListener : Mouse의 휠이 움직였을때 발생하는 이벤트

26 Event-Mouse for (int i = 0; i < bt.length; i++) {
bt[i] = new JButton("Button" + i); if(i%2==0) { bt[i].addMouseListener(new MyMouseListener(i)); } else { bt[i].addMouseMotionListener(new MyMouseListener(i)); pn.add(bt[i]); pn.add(bt[0]); pn.add(bt[1]); pn.add(bt[2]); pn.add(bt[3]); fr.setContentPane(pn); fr.setSize(400, 300); fr.setVisible(true); package com.jiharu.main; import java.awt.GridLayout; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.event.MouseInputListener; public class Main { public static void main(String[] args) { JFrame fr = new JFrame("This 프레임"); JPanel pn = new JPanel(); JButton[] bt = new JButton[4]; GridLayout gl = new GridLayout(2, 2); pn.setLayout(gl);

27 Event-Mouse class MyMouseListener implements MouseInputListener {
private int btnNumber; public MyMouseListener(int btnNumber) { this.btnNumber = btnNumber; } @Override public void mouseClicked(MouseEvent e) { System.out.println(e.getSource().getClass().getName() + btnNumber); System.out.println("Click Event"); System.out.println("Click Count : " + e.getClickCount()); System.out.println("Click Point : " + e.getPoint().toString()); public void mousePressed(MouseEvent e) { System.out.println("Click Pressed");

28 Event-Mouse @Override public void mouseReleased(MouseEvent e) {
System.out.println(e.getSource().getClass().getName() + btnNumber); System.out.println("Click Released"); System.out.println("Click Count : " + e.getClickCount()); System.out.println("Click Point : " + e.getPoint().toString()); } public void mouseEntered(MouseEvent e) { System.out.println("Click Entered");

29 Event-Mouse @Override public void mouseExited(MouseEvent e) {
System.out.println(e.getSource().getClass().getName() + btnNumber); System.out.println("Click Exited"); System.out.println("Click Count : " + e.getClickCount()); System.out.println("Click Point : " + e.getPoint().toString()); } public void mouseDragged(MouseEvent e) { System.out.println("Click Dragged"); public void mouseMoved(MouseEvent e) { System.out.println("Click Moved");

30 Event-Mouse 각각의 버튼에 어떠한 이벤트가 작동하는지 확인해보자.

31 Event-Item ItemSelectable을 상속받은 컴포넌트만 사용가능

32 Event-Item package com.jiharu.main; import java.awt.GridLayout;
import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; public class Main { public static void main(String[] args) { JFrame fr = new JFrame("This 프레임"); JPanel pn = new JPanel(); JCheckBox[] chk = new JCheckBox[4]; GridLayout gl = new GridLayout(2, 2); pn.setLayout(gl); for (int i = 0; i < chk.length; i++) { chk[i] = new JCheckBox("Check" + i); chk[i].addItemListener(new MyItemListener()); pn.add(chk[i]); } pn.add(chk[0]); pn.add(chk[1]); pn.add(chk[2]); pn.add(chk[3]); fr.setContentPane(pn); fr.setSize(400, 300); fr.setVisible(true);

33 Event-Item class MyItemListener implements ItemListener { @Override
public void itemStateChanged(ItemEvent e) { JCheckBox chk = (JCheckBox) e.getSource(); System.out.println("Text : " + chk.getText()); System.out.println("Selected : " + chk.isSelected()); System.out.println("StateChange : " + e.getStateChange()); System.out.println("Item : " + e.getItem()); System.out.println("ItemSelecable :" + e.getItemSelectable()); }

34 Event-Item 체크를 풀었다 해제했다 하면서 각각의 메소드가 어떤 역할을 하는지 보자.

35 Event-Window 윈도우 창에 대한 이벤트

36 Event-Window WindowListener의 메소드 windowOpened : 윈도우가 처음 생성됬을 때 발생
windowIconified : 윈도우가 최소화 됬을 때 발생 windowDeiconified : 윈도우가 최소화에서 최대화 됬을 때 발생 windowDeactivated : 윈도우가 비활성화 됬을 때 발생 windowClosing : 윈도우의 시스템 메뉴의 닫기를 시도할 때 발생 windowClosed : 윈도우가 닫힐 때 발생 windowActivated : 윈도우가 활성활 될 때 발생

37 Event-Window package com.jiharu.main; import java.awt.GridLayout; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Main { public static void main(String[] args) { JFrame fr = new JFrame("This 프레임"); JPanel pn = new JPanel(); JLabel lbl = new JLabel("초기상황"); pn.setLayout(new GridLayout(1, 1)); pn.add(lbl); fr.setContentPane(pn); fr.addWindowListener(new WindowListener() { public void windowOpened(WindowEvent e) { System.out.println("TestSwing.main(...).new WindowListener() {...}.windowOpened()"); }

38 Event-Window public void windowIconified(WindowEvent e) { System.out.println("TestSwing.main(...).new WindowListener() {...}.windowIconified()"); } public void windowDeiconified(WindowEvent e) { System.out.println("TestSwing.main(...).new WindowListener() {...}.windowDeiconified()"); } public void windowDeactivated(WindowEvent e) { System.out.println("TestSwing.main(...).new WindowListener() {...}.windowDeactivated()"); } public void windowClosing(WindowEvent e) { System.out.println("TestSwing.main(...).new WindowListener() {...}.windowClosing()"); } public void windowClosed(WindowEvent e) { System.out.println("TestSwing.main(...).new WindowListener() {...}.windowClosed()"); } public void windowActivated(WindowEvent e) { System.out.println("TestSwing.main(...).new WindowListener() {...}.windowActivated()"); } }); fr.setSize(500, 500); fr.setVisible(true); } }

39 Event-Window 윈도우크기를 조작하면서 어떤 이벤트가 발생하는지 보자

40 Event-Window x버튼을 누른다고 종료되는게 아니라 사실은 껍데기만 종료되고 프로세서는 살아있다!
그러면 정말로 끌려면 어떻게 해야할까?

41 Event-Window @Override public void windowClosing(WindowEvent e) {
                System.exit(0); } 이제 뒤에 돌아가는 프로세서역시 같이 종료된다. 그러나 위의 방식은 AWT방식이고 Swing에서는 다른방식을 쓴다.

42 Event-Window import java.awt.GridLayout; import javax.swing.JFrame;
import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class TestSwing {     public static void main(String[] args) {         JFrame fr = new JFrame("This 프레임");         JPanel pn = new JPanel();         JLabel lbl = new JLabel("초기상황");         pn.setLayout(new GridLayout(1, 1));         pn.add(lbl);         fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         fr.setContentPane(pn);         fr.setSize(500, 500);         fr.setVisible(true);     } }

43 과제 저번 계산기를 완성하시오


Download ppt "Java Seminar Chapter 4."

Similar presentations


Ads by Google