package hello;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseListenerEx extends JFrame{
private JLabel la = new JLabel("hello");
public MouseListenerEx() {
setTitle("Mouse 이벤트 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
Container c = getContentPane();
c.addMouseListener(new MyMouseListener());
c.setLayout(null);
la.setSize(50,20);
la.setLocation(30, 30);
c.add(la);
setSize(250, 250);
setVisible(true);
}
class MyMouseListener implements MouseListener {
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
la.setLocation(x, y);
}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
public static void main(String[] args) {
new MouseListenerEx();
}
}
class MyMouseListener implements MouseListener {
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
la.setLocation(x, y);
}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
를 Adapter를 이용하여 간추릴 수 있다.
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
la.setLocation(x, y);
}
}
완성된 코드
package hello;
import javax.swing.*; // 스윙 컴포넌트 api
import java.awt.*; // 그래픽을 처리하는 api
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseListenerEx extends JFrame /*컨테이너 */{
private JLabel la = new JLabel("hello");
public MouseListenerEx() {
setTitle("Mouse 이벤트 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// EXIT_ON_CLOSE : 종료할때 에플리케이션도 함께 종료
Container c = getContentPane();
c.addMouseListener(new MyMouseAdapter());
c.setLayout(null);
la.setSize(50,20);
la.setLocation(30, 30);
c.add(la);
setSize(250, 250);
setVisible(true); // 스윙 프레임 출력
}
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
la.setLocation(x, y);
}
}
public static void main(String[] args) {
new MouseListenerEx();
}
}
결과는 첫번째 코드와 같지만 코드의 길이가 짧아진 것을 알 수 있다.
2. 상하좌우키로 텍스트 움직이기
package hello;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FlyingTextEx extends JFrame{
private final int FLYING_UNIT = 10;
private JLabel la = new JLabel("HELLO");
public FlyingTextEx() {
setTitle("상,하,좌,우 키를 이용하여 텍스트 움직이기");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
c.addKeyListener(new MyKeyListener());
la.setLocation(50,50);
la.setSize(100, 20);
c.add(la);
setSize(300,300);
setVisible(true);
c.setFocusable(true);
c.requestFocus();
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Component com = (Component)e.getSource();
com.setFocusable(true);
com.requestFocus();
}
});
}
class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int KeyCode = e.getKeyCode();
switch (KeyCode) {
case KeyEvent.VK_UP:
la.setLocation(la.getX(), la.getY()-FLYING_UNIT);
break;
case KeyEvent.VK_DOWN:
la.setLocation(la.getX(), la.getY()+FLYING_UNIT);
break;
case KeyEvent.VK_LEFT:
la.setLocation(la.getX()-FLYING_UNIT, la.getY());
break;
case KeyEvent.VK_RIGHT:
la.setLocation(la.getX()+FLYING_UNIT, la.getY());
default:
break;
}
}
}
public static void main(String[] args) {
new FlyingTextEx();
}
}
3.마우스와 마우스 모션 이벤트 활용
package hello;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseListenerAllEx extends JFrame{
private JLabel la = new JLabel("No Mouse Event");
public MouseListenerAllEx() {
setTitle("MouseListener와 MouseMotionListener 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
MyMouseListener listener = new MyMouseListener();
c.addMouseListener(listener);
c.addMouseMotionListener(listener);
c.add(la);
setSize(300, 200);
setVisible(true);
}
class MyMouseListener implements MouseListener, MouseMotionListener{
public void mousePressed(MouseEvent e) {
la.setText("mousePressed("+ e.getX()+", "+e.getY()+")");
}
public void mouseReleased(MouseEvent e) {
la.setText("mouseReleased("+ e.getX()+", "+e.getY()+")");
}
@Override
public void mouseDragged(MouseEvent e) {
la.setText("mouseDragged("+ e.getX()+", "+e.getY()+")");
}
@Override
public void mouseMoved(MouseEvent e) {
la.setText("mouseMoved("+ e.getX()+", "+e.getY()+")");
}
@Override
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
Component c = (Component)e.getSource();
c.setBackground(Color.CYAN);
}
public void mouseExited(MouseEvent e) {
Component c = (Component)e.getSource();
c.setBackground(Color.YELLOW);
}
}
public static void main(String[] args) {
new MouseListenerAllEx();
}
}
4. 키를 입력받으면 컨텐트팬의 배경을 초록색으로, % 키를 입력받으면 노란색으로 변경
package hello;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class KeyCodeEx extends JFrame{
private JLabel la = new JLabel();
public KeyCodeEx() {
setTitle("key Code 예제 : f1 키 - 초록색, %키 - 노란색");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.addKeyListener(new MyKeyListener());
c.add(la);
setSize(300, 150);
setVisible(true);
c.setFocusable(true);
c.requestFocus();
}
class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
Container contentPane = (Container)e.getSource();
la.setText(e.getKeyText(e.getKeyCode()));
if(e.getKeyChar() == '%') {
contentPane.setBackground(Color.YELLOW);
}
else if(e.getKeyCode() == KeyEvent.VK_F1) {
contentPane.setBackground(Color.GREEN);
}
}
}
public static void main(String[] args) {
new KeyCodeEx();
}
}
(원래는 화면에 f1과 %가 나오는데 캡쳐를 했더니... alt가 나왔다...)
5. 더블클릭 시 컨텐트팬의 배경색 변경
package hello;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClickAndDoubleClickEx extends JFrame{
public ClickAndDoubleClickEx() {
setTitle("Click and DoubleClick 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.addMouseListener(new MyMouseListener());
setSize(300,200);
setVisible(true);
}
class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2) {
int r = (int )(Math.random()* 256);
int g = (int )(Math.random()* 256);
int b = (int )(Math.random()* 256);
Component c = (Component)e.getSource();
c.setBackground(new Color(r,g,b));
}
}
}
public static void main(String[] args) {
new ClickAndDoubleClickEx();
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
코드
public class DEMO {
public static void main(String[] args) {
int [] array = { 0, 1, 2, };
System.out.println(array[3]);
}
}
배열의 크기가 3이고 배열이 0부터 시작하기 때문에 배열 3칸은 없음.
2. 0으로 나눌때 발생하는 ArithmeticException 예외
public class Demo2 {
public static void main(String[] args) {
int [] aa = new int[3];
try {
aa[2] = 100/0;
aa[3] = 100;
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("배열 첨자가 배열 크기보다 커요 ~~");
} catch (ArithmeticException e) {
System.out.println("0으로 나누는 등의 오류에요~~");
} finally {
System.out.println("이 부분은 무조건 나와요 ~~");
}
}
}
public class Demo3 {
public static void main(String[] args) {
int a = 100, b = 0;
int result;
try {
result = a / b;
} catch (ArithmeticException e) {
System.out.print("발생 오류 ==>");
System.out.println(e.getMessage());
}
}
}
결과
발생 오류 ==>/ by zero
3. 예외발생으로 프로그램이 강제 종료되는 경우
오류 메세지 : Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type InterruptedException
package test01;
public class Demo3 {
public static void main(String[] args) {
Thread.sleep(100);
}
}
4. 예외 잡아 처리하기 (범위를 벗어난 배열의 접근 )
try {
예외가 발생할 수 있는 실행문;
} catch (예외클래스 1 | 예외 클래스 2 변수) {
핸들러;
}
public class Demo3 {
public static void main(String[] args) {
int [] array = { 0 , 1, 2, };
try {
System.out.println("마지막 원소 => " + array[3]);
System.out.println("첫 번째 원소 => " + array[0]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("원소가 존재하지 않습니다. ");
}
System.out.println("어이쿠!!");
}
}
ArrayIndexOutOfBoundsException : 배열, 벡터 등에서 범위를 벗어난 인덱스를 사용할 때 발생한다.
package hello;
abstract class Car{
int speed = 0;
String color;
void upSpeed(int speed) {
this.speed += speed;
}
}
class Sedan extends Car{
}
class Truck extends Car{
}
public class AbstractClassExample{
public static void main(String[] args) {
Sedan sedan1 = new Sedan();
System.out.println("승용차 인스턴스 생성~");
Truck truck1 = new Truck();
System.out.println("트럭 인스턴스 생성~");
}
}
package hello;
abstract class Pokemon{
private String name;
abstract void attack();
abstract void sound();
Pokemon(String name) {
this.name = name;
}
public String getname() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Pikachu extends Pokemon{
public Pikachu() {
super("피카츄");
}
void attack() {
System.out.println("전기 공격");
}
void sound() {
System.out.println("피카피카");
}
}
class Squirtle extends Pokemon{
public Squirtle() {
super("꼬북이");
}
void attack() {
System.out.println("물 공격");
}
void sound() {
System.out.println("꼬북꼬북");
}
}
public class Sample{
public static void main(String[] args) {
Pikachu s = new Pikachu();
System.out.println("이 포켓몬의 이름은 : " + s.getname());
s.attack();
s.sound();
Squirtle a = new Squirtle();
System.out.println("이 포켓몬의 이름은 : " + a.getname());
a.attack();
a.sound();
}
}
package hello;
abstract class Car{
private int speed = 0;
private String name;
public Car(String name){
this.name = name;
}
void upSpeed(int speed) {
this.speed += speed;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
abstract void work();
}
class Sedan extends Car{
public Sedan(String name) {
super(name);
}
void work() {
System.out.println(super.getName() +"가 사람을 태우고 있습니다.");
}
}
class Truck extends Car{
public Truck(String name) {
super(name);
}
void work() {
System.out.println(super.getName() + "이 짐을 싣고 있습니다.");
}
}
public class AbstractMethodExample{
public static void main(String[] args) {
Sedan sd = new Sedan("빨간 승용차");
sd.work();
Truck tk = new Truck("노란트럭");
tk.work();
}
}
package hello;
abstract class Calculator{
public abstract int add(int a, int b);
public abstract int subtract(int a, int b);
public abstract double average(int[] a);
}
public class GoodCalc {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public double average(int[] a) {
int sum = 0;
for(int i=0; i<a.length; i++) {
sum += a[i];
}
return sum/a.length;
}
public static void main(String[] args) {
GoodCalc a = new GoodCalc();
System.out.println("2 + 3 = " + a.add(2,3));
System.out.println("2 - 3 = " + a.subtract(2, 3));
System.out.println("(2 + 3 + 4)/3 = " + a.average(new int [] {2,3,4}) );
}
}
package hello;
import java.util.Scanner;
public class Test {
String name;
String location;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public static void main(String[] arg) {
Test ct = new Test();
Scanner s = new Scanner(System.in);
System.out.print("당신의 이름은 : ");
String name = s.next();
ct.setName(name);
System.out.println(ct.getName() + "님 안녕하세요!");
System.out.print("당신의 나이를 입력하세요: ");
int age = s.nextInt();
ct.setAge(age);
System.out.print("당신의 사는 지역을 입력하세요 : ");
String location = s.next();
ct.setLocation(location);
System.out.println(ct.getName() + "님 당신은 " + ct.getLocation()+ "에 사는 " +ct.getAge() + "살입니다.");
}
}
package hello;
public class HelloJava {
private String msg;
public HelloJava() {
msg = "Hello Java!!";
}
public HelloJava(String msg) {
this.msg = msg;
}
public HelloJava(String msg, int option) {
if(option == 1)
this.msg = msg;
else if(option == 2)
this.msg = msg + ", 안녕하세요? ";
}
public void print() {
System.out.println(msg);
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package hello;
public class HelloRun {
public void go() {
HelloJava hello1 = new HelloJava();
hello1.print();
HelloJava hello2 = new HelloJava("My Hello Java!! ");
hello2.print();
HelloJava hello3 = new HelloJava("Hello",2);
hello3.print();
hello2.setMsg("반갑습니다.!!");
System.out.println(hello2.getMsg());
}
public static void main(String[] args) {
HelloRun hr = new HelloRun();
hr.go();
}
}
package hello;
import java.util.Scanner;
public class Grade {
private int math;
private int science;
private int english;
public Grade(int math, int science, int english) {
this.math = math;
this.science = science;
this.english = english;
}
public int average() {
return (math + science + english) / 3;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("점수를 입력하세요 : ");
int math = s.nextInt();
int science = s.nextInt();
int english = s.nextInt();
Grade me = new Grade(math, science, english);
System.out.println("평균은 " + me.average());
}
}
package hello;
import java.util.Scanner;
class DigitsOpr {
private int num;
public void setNum(int x) {
this.num = x;
}
public int countDigits() {
int n = num;
int count = 0;
while(n>0) {
n/=10;
count++;
}
return count;
}
}
public class number {
public static void main(String []args) {
DigitsOpr dig = new DigitsOpr();
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
dig.setNum(n);
System.out.println(n + "은 " + dig.countDigits() + "자리입니다.");
}
}
package hello;
import java.util.Scanner;
class DigitsOpr{
private int num;
public void setNum(int x) {
this.num = x;
}
public boolean isArmstrong() {
int n, sum, d;
n = num;
sum = 0;
while(n>0) {
d = n %10;
sum += (d*d*d);
n /= 10;
}
if(sum == num) return true;
else return false;
}
}
public class Armstrong {
public static void main(String[] args) {
DigitsOpr dig = new DigitsOpr();
int n;
Scanner sc = new Scanner(System.in);
System.out.print("정수를 입력하세요: ");
n = sc.nextInt();
dig.setNum(n);
if(dig.isArmstrong()) {
System.out.println(n + "은(는)Armstrong 수입니다.");
}
else {
System.out.println(n + "은(는)Armstrong 수가 아닙니다.");
}
}
}