내부클래스
현재는 잘사용되지 않으며 목적성이 분명하게 사용하지 않는 이상은 오히려 안좋음
다만 해외에서는 특히 안드로이드로 개발하는 경우 내부클래스를 자주 이용한다고 한다.
국내에서는 접근이나 사용이 불편해지기 때문에 크게 활용에 대해 생각하려하지 않는다고 한다.
최종 이용 목적은 사실 어나니머스클래스르 이용하려고 사용하는 쪽에 가깝다.
객체지향과 상속의 개념이 발달하게 됨으로써 기본적인 장점을 잃었다.
Map.Entry 같은 특정 목적아닌 이상 확장성이 매우 떨어지게 되므로 지양하는 것이 좋다.
익명클래스(anonymous class)
- 인터페이스를 구현하는 클래스가 필요한데 한번만 쓸 경우
- 추상클래스를 구현하는 클래스가 필요한데 한번만 쓸 경우
- 상속받은 클래스를 한번만 사용하는데 오버라이딩 혹은 그대로 쓰는 경우
package com.bit;
interface Inter {
void func();
}
abstract class Lec05{
void func02() {
System.out.println("추상클래스의 기능");
}
public abstract void func();
}
class Lec55{
void func() {
System.out.println("본래 기능");
}
void func02() {
System.out.println("본래 기능 2");
}
}
class Outter05 {
// anonymous 클래스
// 사용성이 높다 - 한번쓰고 말 클래스를 정의할 때
static void func01() {
Lec55 obj = new Lec55() {
// Lec55에서 필요한 기능만 오버라이딩 할 수 있음
public void func() {
System.out.println("익명클래스만들기");
}
};
obj.func();
obj.func02();
}
}
public class Ex05 {
public static void main(String[] args) {
Outter05 outt = new Outter05();
outt.func01();
/////////////////////////////////
(new Inter() {
public void func() {
System.out.println("기능 구현");
}
}).func();
Inter obj = new Inter() {
public void func() {
System.out.println("기능 구현");
}
};
obj.func();
Ex06.obj.func();
//////////////////////////////////
// 예시
ArrayList<Integer> list;
list = new ArrayList<Integer>();
list.add(1111);
list.add(4444);
list.add(2222);
list.add(3333);
list.add(5555);
// 내림차순
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
// 오름차순
list.sort((a,b) -> a-b);
Iterator<Integer> ite = list.iterator();
while(ite.hasNext()) {
System.out.println(ite.next());
}
}
Java.Util
Calendar 클래스
Calendar cal;
cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.MONTH) + 1); // 0~11
System.out.println(cal.get(Calendar.DATE));
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.DAY_OF_WEEK)); // 1=일요일,2=월요일...
switch(cal.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY: System.out.println("일요일"); break;
case Calendar.MONDAY: System.out.println("월요일"); break;
case Calendar.TUESDAY: System.out.println("화요일"); break;
case Calendar.WEDNESDAY: System.out.println("수요일"); break;
case Calendar.THURSDAY: System.out.println("목요일"); break;
case Calendar.FRIDAY: System.out.println("금요일"); break;
case Calendar.SATURDAY: System.out.println("토요일"); break;
}
System.out.println(cal.get(Calendar.AM_PM)); //AM=0, PM=1
switch(cal.get(Calendar.AM_PM)) {
case Calendar.AM: System.out.println("AM"); break;
case Calendar.PM: System.out.println("PM"); break;
}
System.out.println(cal.get(Calendar.HOUR)); // 12시
System.out.println(cal.get(Calendar.HOUR_OF_DAY)); //24시
System.out.println(cal.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.SECOND));
int before = cal.get(Calendar.DAY_OF_YEAR);
cal.set(2022, 12-1, 6, 0, 0, 0);
System.out.println(cal.get(Calendar.YEAR) + "년"
+ (cal.get(Calendar.MONTH)+1) +"월"
+ cal.get(Calendar.DATE) +"일"
+ cal.get(Calendar.HOUR) +"시"
);
int after = cal.get(Calendar.DAY_OF_YEAR);
System.out.println(before+"+"+after+"="+(before - after));// 일수차이
Calendar cal2 = Calendar.getInstance();
System.out.println(cal.before(cal2)); // true
System.out.println(cal2.after(cal)); // true
System.out.println(cal2.compareTo(cal)); // 같으면0,이후1,이전-1
Date 클래스
Date의 대부분의 메서드들은 Deprecated 되었지만 Date가 너무 폭넓게 쓰여지긴해서 사용은 가능하다.
그래도 Calendar 클래스를 통해 생성된 객체를 Date로 받는 방식을 이용하는 것이 편하고 좋다.
Format 관련 클래스들
Date date = new Date();
System.out.println(date);
DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.KOREA);
String msg = df.format(date);
System.out.println(msg);
Date d = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd a hh:mm:ss");
//sdf.applyPattern("yyyy-MM-dd a hh:mm:ss");
String msg = sdf.format(d);
System.out.println(msg);
Properties 클래스
Properties props;
props = new Properties();
props = System.getProperties();
//props.setProperty("key1", "value1");
//System.out.println(props);
Set set = props.keySet();
Iterator ite = set.iterator();
while(ite.hasNext()) {
Object obj = ite.next();
System.out.print(ite.next() + "===>");
System.out.println(props.get(obj));
}
Scanner 클래스
java.io.InputStream inn = System.in;
Scanner sc;
sc = new Scanner("abcd\nefg\nhifk\nlmno");
System.out.println(sc.nextLine()); // abcd
System.out.println(sc.nextLine()); // efg
System.out.println(sc.nextLine()); // hifk
System.out.println(sc.nextLine()); // lmno
sc = new Scanner("12 34\n56");
System.out.println(sc.nextInt() + 1); // 13
System.out.println(sc.next() + 1); // 341
System.out.println(sc.nextLine() + 1); // 개행을 기준으로 함
System.out.println(sc.nextLine() + 1); // 개행을 기준으로 함
Random 클래스
Random ran = new Random();
System.out.println(ran.nextDouble());
System.out.println(ran.nextInt(45)+1);
StringTokenizer 클래스
split과 비슷한 역할을 해줌
예시를 생각해보았을 때 게시글에 대해 비속어 등 금지어를 검토할 때
긴 문자열을 StringTokenizer를 이용해서 단어마다 분리하여 얻어 낸 다음
비속어 필터링에 집어넣어서 결과값을 받을 수 있을 것 같다.
String target = "java,web,DB,Framework";
StringTokenizer stk = new StringTokenizer(target, ",");
while(stk.hasMoreTokens()) {
System.out.println(stk.nextToken());
}
// split에 비해 공백구분이 탁월하다
String target2 = "java web DB Framework";
StringTokenizer stk2 = new StringTokenizer(target2); //매개변수 없으면 공백 기준
System.out.println("요소의 갯수 : "+ stk2.countTokens());
while(stk2.hasMoreTokens()) {
System.out.println(stk2.nextToken());
}
Arrays 클래스
String[] arr1 = {
"java",
"DB",
"Web",
"Framework"
};
System.out.println(Arrays.toString(arr1));
String[] arr2 = Arrays.copyOf(arr1, arr1.length -1);
System.out.println(Arrays.toString(arr2));
String[] arr3 = Arrays.copyOfRange(arr1, 1, arr1.length);
System.out.println(Arrays.toString(arr3));
int[] arr4 = new int[2];
Arrays.fill(arr4, 1234);
System.out.println(Arrays.toString(arr4));
int[] arr5 = {1234,1234};
System.out.println(Arrays.equals(arr4, arr5));//객체끼리 비교는 주의
int[] lotto = {45,3,26,7,25,31};
Arrays.sort(lotto);
System.out.println(Arrays.toString(lotto));
System.out.println(Arrays.binarySearch(lotto, 31));// 정렬 필수 index번호를 리턴해줌 없으면 음수 리턴
List<Integer> list = Arrays.asList(45,3,26,7,25,31);
for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
Thread
- Thread를 상속받고 run() 메서드를 오버라이딩하고 내 객체 생성한 뒤 start() 통해서 새로운 쓰레드로 run()을 실행
public class Ex02 extends Thread {
public Ex02() {
// super("뉴 스레드"); 이름설정
setName("뉴스레드"); // 이름은 자유롭게 변경할 수 있기 때문에 비교는 getId()를 통해서 하는 것이 좋다.
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()); // Thread-0
System.out.println("새로운 쓰레드로 작업 시작");
Thread thr = this;
System.out.println(thr.getName()); // Thread-0
System.out.println(this.getName()); // Thread-0
System.out.println(getName()); // Thread-0
Thread thr2 = Thread.currentThread();
System.out.println(thr2==this); // true
System.out.println(this.getId()); //10
System.out.println(thr.getId()); //10
System.out.println("sleep start");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sleep end");
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + " start"); // main start
Ex02 thr = new Ex02();
thr.start();
System.out.println(Thread.currentThread().getName() + " end"); // main end
}
}
- Runnable 인터페이스를 구현하여 run() 메서드 오버라이딩 후 Thread 객체 생성 시 Runnable 구현한 내 객체 매개변수로 전달 후 start()로 실행
public class Ex03 implements Runnable{
public static void main(String[] args) {
Thread thr = Thread.currentThread();
String name = thr.getName();
System.out.println(name + " start"); // main start
Thread thr2 = new Thread(new Ex03());
thr2.start();
System.out.println(name + " end"); // main end
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " start"); // Thread-0 start
System.out.println(name + " end"); // Thread-0 end
// Thread thr = this; 불가능 this->Ex07
}
}
- Runnable 인터페이스를 구현하는 Anonymous 클래스 객체를 정의 후(run()메서드 구현 강제) Thread 객체 생성 시 전달한 뒤 start()로 실행
public class Ex04 {
public static void main(String[] args) {
Thread thr = new Thread(new Runnable() {
@Override
public void run() {
Thread thr = Thread.currentThread();
String name = thr.getName();
System.out.println(name + " start");
}
});
thr.start();
}
}
- Thread를 상속받는 Anonymous 클래스를 생성해서 run()만 오버라이딩해서 Thread 객체 생성 후 start()로 실행
public class Ex05 {
public static void main(String[] args) {
Thread thr = new Thread() {
@Override
public void run() {
Thread thr = Thread.currentThread();
String name = thr.getName();
System.out.println(name + " start");
}
};
thr.start();
}
}
I/O
내입장 기준(객체 기준)
OutputStream 줄 때 덮어씌워져서 기존 데이터 날아가니 주의!
read할 때 -1이 return 되면 더이상 값이 없음을 의미
메모장으로 열었을 때 문자로 나오는 이유? 바이너리숫자를 문자로 보여주는 프로그램이니까!
File
파일 조회
public class Ex10 {
public static void main(String[] args) {
// File file = new File("./Lec01.txt");
File file = new File("E:\\java\\day16\\src\\com\\bit");
System.out.println("유무?" + file.exists());
if (file.exists()) {
System.out.println("dir?" + file.isDirectory());
System.out.println("file?" + file.isFile());
System.out.println("경로 : " + file.getPath());
System.out.println("상위경로 : " + file.getParent());
System.out.println("이름 : " + file.getName());
System.out.println("절대경로 : " + file.getAbsolutePath());
try {
System.out.println("표준경로 : " + file.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
// 권한 확인
System.out.println("r : "+file.canRead());
System.out.println("w : "+file.canWrite());
System.out.println("x : "+file.canExecute());
System.out.println("size : "+file.length() + "byte");
System.out.println(new Date(file.lastModified())); // 밀리초
String[] arr = file.list();
System.out.println(Arrays.toString(arr));
}
}
}
파일 생성
public class Ex12 {
public static void main(String[] args) {
File f = new File(".\\test02\\newText.txt");
if(f.exists()) {
System.out.println("존재합니다");
} else {
try {
boolean boo = f.createNewFile();
if(boo) System.out.println("파일생성");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
파일, 경로(디렉토리) 삭제
public class Ex13 {
public static void main(String[] args) {
File f = new File("test02");
if(f.exists()) {
boolean boo = f.delete();
if(boo) System.out.println("삭제완료");
else {
System.out.println("하위도 모두 지우시겠습니까?y");
File[] files = f.listFiles();
for(File file : files) {
file.delete();
}
f.delete();
System.out.println("삭제완료");
}
} else {
System.out.println("존재하지않음");
}
}
}
경로(디렉토리) 생성
public class Ex14 {
public static void main(String[] args) {
File f = new File(".\\test02\\tdir");
if(f.exists()) {
System.out.println("이미 존재함");
} else {
boolean boo = f.mkdirs();
if(boo) System.out.println("생성완료");
}
}
}
OS에서 관리하는 Temp폴더에 파일 생성
public class Ex15 {
public static void main(String[] args) {
try {
File file2 = File.createTempFile("abcdefg", ".txt");
// 운영체제가 관리하는 위치(Temp)에 abcdefg{랜덤숫자}.txt 형태로 파일이 생성됨
System.out.println(file2.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
파일 쓰기 write
public class Ex16 {
public static void main(String[] args) {
String msg = "한";
byte[] arr = msg.getBytes();
File f = new File("Lec16.bin");
OutputStream os;
try {
if(!f.exists()) {
f.createNewFile();
}
os = new FileOutputStream(f);
for(int i = 0; i < arr.length; i++) {
os.write(arr[i]);
}
// os.write('a');
// os.write('b');
// os.write('c');
// os.write('d');
os.close();
System.out.println("작성완료");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
파일 읽기 read
public class Ex17 {
public static void main(String[] args) {
File f = new File("Lec16.bin");
InputStream is;
if(f.exists()) {
try {
is = new FileInputStream(f);
int su = -1;
while(true) {
su = is.read(); // 값 없을 경우 -1 return
if(su == -1)break;
System.out.println(su); // binary값 리턴됨
}
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
파일 복사
public class Ex18 {
public static void main(String[] args) {
File target = new File("Lec01.txt");
File result = new File("copy.txt");
InputStream is;
OutputStream os;
if(!result.exists()) {
try {
result.createNewFile();
is = new FileInputStream(target);
os = new FileOutputStream(result);
while(true) {
int su = is.read();
if(su == -1)break;
os.write(su);
}
is.close();
os.close();
System.out.println("복사완료");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Scanner를 이용한 파일 읽기
public class Ex20 {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("E:\\java\\day16\\src\\com\\bit\\Ex01.java"); // 읽을 java 파일
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
String msg = sc.nextLine();
System.out.println(msg);
}
}
}
한번에 쓰기
public class Ex21 {
public static void main(String[] args) {
// 한번에 쓰기
String msg = "버퍼를 달아서 성능을 올립시다.";
byte[] arr = msg.getBytes();
File file = new File("Lec21.txt");
OutputStream os;
try {
if (file.exists()) {
file.createNewFile();
}
os = new FileOutputStream(file);
os.write(arr); // for문 대신에 그냥 write에 배열 전달
os.close();
System.out.println("한번에 작성");
} catch (IOException e) {
e.printStackTrace();
}
}
}
한번에 읽기
public class Ex22 {
public static void main(String[] args) {
// 한번에 읽기
File file = new File("Lec21.txt");
byte[] arr = new byte[(int) file.length()];
InputStream is;
try {
is = new FileInputStream(file);
is.read(arr);
is.close();
System.out.println(new String(arr));
} catch (IOException e) {
e.printStackTrace();
}
}
}
byte buffer
public class Ex01 {
public static void main(String[] args) {
String msg = "abcdefghijklmn";
byte[] buf = new byte[2];
File file = new File("lec01.bin");
OutputStream os;
try {
if(!file.exists()) file.createNewFile();
os = new FileOutputStream(file);
for(int i = 0; i < msg.length(); i+=2) {
buf[i] = (byte)msg.charAt(i);
}
os.close();
System.out.println("작성완료");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
필터클래스
데코레이션 패턴으로 만들어진 클래스이며 버퍼클래스라고도 불린다. 버프를 줌으로써 I/O의 성능을 향상 시켜준다.
I/O를 사용할 때 항상 셋트로 같이 사용하는 것이 좋을 것 같다.
BufferedStream
// 필터 클래스를 이용한 파일 쓰기
public class Ex03 {
public static void main(String[] args) {
String msg = "ABCDEFG HIJKLMN";
File file = new File("lec03.bin");
OutputStream os = null;
BufferedOutputStream bos = null;
try {
if(file.exists()) {
file.createNewFile();
}
os = new FileOutputStream(file);
bos = new BufferedOutputStream(os);
for(int i = 0; i < msg.length(); i++) {
bos.write(msg.charAt(i));
}
// Buffer를 쓸땐 꼭 close를 해줘야한다. 그렇지않으면 값이 날라감
if(bos != null) bos.close();
if(os != null) os.close();
System.out.println("끝");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 필터 클래스를 이용한 파일 읽기
public class Ex04 {
public static void main(String[] args) {
File file = new File("lec03.bin");
InputStream is = null;
BufferedInputStream bis = null;
try {
if(file.exists()) {
is = new FileInputStream(file);
bis = new BufferedInputStream(is);
while(true) {
int su = bis.read();
if(su == -1)break;
System.out.print((char)su);
}
}
// Buffer를 쓸땐 꼭 close를 해줘야한다. 그렇지않으면 값이 날라감
if(bis != null) bis.close();
if(is != null) is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 핕터 클래스를 이용한 파일 복사
public class Ex05 {
public static void main(String[] args) {
File file = new File("lec03.bin");
File copy = new File("copy.bin");
InputStream is = null;
OutputStream os = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
if(file.exists()) {
if(!copy.exists()) copy.createNewFile();
is = new FileInputStream(file);
os = new FileOutputStream(copy);
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(os);
// 버퍼 변수를 사용해야만 효과를 적용받을 수 있다.
while(true) {
int su = bis.read();
if(su == -1) break;
bos.write(su);
}
if(bos != null) bos.close();
if(bis != null) bis.close();
if(os != null) os.close();
if(is != null) is.close();
}
System.out.println("complete");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
DataStream
// DataStream 으로 쓰기
public class Ex06 {
public static void main(String[] args) {
File file = new File("lec06.bin");
OutputStream os = null;
DataOutputStream dos = null;
try {
if(!file.exists()) file.createNewFile();
os = new FileOutputStream(file);
dos = new DataOutputStream(os);
dos.write(65);
dos.writeInt(1234);
dos.writeDouble(3.14);
dos.writeChar('가');
dos.writeBoolean(true);
dos.writeUTF("한글과 english and 1234");
if(dos != null) dos.close();
if(os != null) os.close();
System.out.println("write complete");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//DataStream 으로 읽기
public class Ex07 {
public static void main(String[] args) {
File file = new File("lec06.bin");
InputStream is = null;
DataInputStream dis = null;
try {
if(file.exists()) {
is = new FileInputStream(file);
dis = new DataInputStream(is);
// 반드시 작성한 순서대로만 읽어야한다!!!
int su1 = dis.read();
int su2 = dis.readInt();
double su3 = dis.readDouble();
char su4 = dis.readChar();
boolean boo = dis.readBoolean();
// String msg = dis.readUTF();
System.out.println(su1);
System.out.println(su2);
System.out.println(su3);
System.out.println(su4);
System.out.println(boo);
// System.out.println(msg);
}
if(dis != null) dis.close();
if(is != null) is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
PrintStream
// PrintStream 으로 쓰기
public class Ex08 {
public static void main(String[] args) {
File file = new File("lec06.bin");
OutputStream os = null;
PrintStream ps = null;
try {
os = new FileOutputStream(file);
ps = new PrintStream(os);
ps.print(65);
ps.print(1234);
ps.print(3.14);
ps.print('가');
ps.print(true);
ps.print("한글과 english and 1234");
if(ps != null) ps.close();
if(os != null) os.close();
System.out.println("print complete");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java GUI
java.awt & java.swing
기존 awt로 만든거랑 swing의 차이는 클래스명 swing의 J가 붙어있음
보통 Frame 클래스를 상속받아 사용하는게 사용성이 좋다.
레이아웃
public class Ex03 extends Frame{
// static CardLayout cl;
public Ex03() {
LayoutManager lm;
// lm = new FlowLayout();
// lm = new GridLayout(3,2);
// lm = new BorderLayout();
// cl = new CardLayout();
lm = new GridBagLayout();
setLayout(lm);
Button btn1 = new Button();
btn1.setLabel("btn1");
add(btn1);
// add(btn1, BorderLayout.NORTH);
Button btn2 = new Button();
btn2.setLabel("btn2");
add(btn2);
// add(btn2, BorderLayout.CENTER);
Button btn3 = new Button();
btn3.setLabel("btn3");
add(btn3);
// add(btn3, BorderLayout.SOUTH);
Button btn4 = new Button();
btn4.setLabel("btn4");
add(btn4);
// add(btn4, BorderLayout.WEST);
Button btn5 = new Button();
btn5.setLabel("btn5");
add(btn5);
// add(btn5, BorderLayout.EAST);
setSize(300, 200);
setLocation(200, 200);
setVisible(true);
}
public static void main(String[] args){
new Ex03();
}
}
GridBagLayout() 예제
public class Ex04 extends Frame{
public Ex04() {
LayoutManager lm = new GridBagLayout();
GridBagConstraints gbc;
gbc = new GridBagConstraints();
setLayout(lm);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill=GridBagConstraints.BOTH;
Button btn1 = new Button();
btn1.setLabel("btn1");
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
add(btn1,gbc);
Button btn2 = new Button();
btn2.setLabel("btn2");
gbc.gridx=1;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
add(btn2,gbc);
Button btn3 = new Button();
btn3.setLabel("btn3");
gbc.gridx=2;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
add(btn3,gbc);
Button btn4 = new Button();
btn4.setLabel("btn4");
gbc.gridx=3;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
add(btn4,gbc);
Button btn5 = new Button();
btn5.setLabel("btn5");
gbc.gridx=0;
gbc.gridy=1;
gbc.gridwidth=1;
gbc.gridheight=1;
add(btn5,gbc);
Button btn6 = new Button();
btn6.setLabel("btn6");
gbc.gridx=1;
gbc.gridy=1;
gbc.gridwidth=2;
gbc.gridheight=1;
add(btn6,gbc);
Button btn7 = new Button();
btn7.setLabel("btn7");
gbc.gridx=3;
gbc.gridy=1;
gbc.gridwidth=1;
gbc.gridheight=2;
add(btn7,gbc);
Button btn8 = new Button();
btn8.setLabel("btn8");
gbc.gridx=0;
gbc.gridy=2;
gbc.gridwidth=1;
gbc.gridheight=1;
add(btn8,gbc);
Button btn9 = new Button();
btn9.setLabel("btn9");
gbc.gridx=1;
gbc.gridy=2;
gbc.gridwidth=1;
gbc.gridheight=1;
add(btn9,gbc);
Button btn10 = new Button();
btn10.setLabel("btn10");
gbc.gridx=2;
gbc.gridy=2;
gbc.gridwidth=1;
gbc.gridheight=1;
add(btn10,gbc);
setSize(500,400);
setLocation(200, 200);
setVisible(true);
}
public static void main(String[] args) {
Ex04 me = new Ex04();
}
}
컴포넌트
public class Ex07 extends Frame{
public Ex07() {
Panel p = new Panel();
Button btn1 = new Button("aaaaa");
btn1.setEnabled(false);
p.add(btn1);
JButton btn2 = new JButton("한글");
btn2.setText("수정");
// 버튼에 이미지 넣기
byte[] arr = new byte[1611];
File f = new File("img01.png");
InputStream is = null;
try {
is = new FileInputStream(f);
for(int i = 0; i < arr.length; i++) {
arr[i] = (byte)is.read();
}
if(is!=null)is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Icon defaultIcon = new ImageIcon(arr);
btn2.setIcon(defaultIcon);
p.add(btn2);
TextField tf = new TextField(10);
tf.setText("start");
tf.setEchoChar('*');
p.add(tf);
TextArea ta = new TextArea("aaa", 5, 10, TextArea.SCROLLBARS_BOTH);
p.add(ta);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox cb1 = new Checkbox("item1",false,cbg);
Checkbox cb2 = new Checkbox("item2",true,cbg);
Checkbox cb3 = new Checkbox("item3",false,cbg);
p.add(cb1);
p.add(cb2);
p.add(cb3);
Choice c1 = new Choice();
c1.addItem("item1");
c1.addItem("item2");
c1.addItem("item3");
c1.addItem("item4");
c1.select("item3");
p.add(c1);
List li = new List(5, true);
li.add("item1");
li.add("item2");
li.add("item3");
li.select(2);
p.add(li);
Label la = new Label("AAAA");
p.add(la);
JLabel jla = new JLabel("JJJJ");
jla.setIcon(defaultIcon);
p.add(jla);
add(p);
setSize(300,300);
setLocation(100,100);
setVisible(true);
}
public static void main(String[] args) {
new Ex07();
}
}
컴포넌트 + Listener들
Panel, Label, Font, Color
public class Ex03 extends Frame{
public Ex03() {
Panel p = new Panel();
Label la = new Label("한글");
Font f = new Font(Font.DIALOG, Font.BOLD, 30);
la.setFont(f);
Color fcol = Color.magenta;
Color bcol = Color.BLACK;
la.setForeground(fcol);
la.setBackground(bcol);
p.add(la);
TextField tf = new TextField(10);
tf.setFont(f);
// tf.setEditable(false);
p.add(tf);
Button btn = new Button("버튼");
p.add(btn);
// btn.setVisible(false);
// btn.setEnabled(false);
add(p);
setBounds(100,100,400,300);
setVisible(true);
}
public static void main(String[] args) {
new Ex03();
}
}
Canvas
public class Ex04 extends Frame{
static Ex04 me;
Canvas can = new MyCanvas();
class MyCanvas extends Canvas {
@Override
public void paint(Graphics g) {
char[] arr = "한글".toCharArray();
g.drawChars(arr, 0, arr.length, 100, 100);
g.drawLine(100, 100, 200, 200);
g.setColor(Color.red);
g.drawRect(200, 200, 100, 100);
g.drawOval(300, 300, 100, 100);
g.setColor(Color.blue);
g.fillRect(200, 300, 100, 100);
ImageIcon icon = new ImageIcon("img01.png");
Image img = icon.getImage();
g.drawImage(img,100,100,me);
g.drawArc(100, 100, 100, 100, 0, 180);
}
}
public Ex04() {
add(can);
setBounds(100,100,500,500);
setVisible(true);
}
public static void main(String[] args) {
me = new Ex04();
}
}
Menu 생성
public class Ex05 extends Frame{
public Ex05() {
MenuBar mb = new MenuBar();
Menu m = new Menu("메뉴1");
m.add("1-1");
m.add("1-2");
m.add("1-3");
mb.add(m);
Menu m2 = new Menu("메뉴2");
MenuItem mi = new MenuItem("2-1");
m2.add(mi);
MenuItem mi2= new MenuItem("2-2");
m2.add(mi2);
mb.add(m2);
Menu m3 = new Menu("메뉴3");
Menu m4 = new Menu("3-1");
MenuItem mi3 = new MenuItem("3-1-1");
CheckboxMenuItem cmi = new CheckboxMenuItem("3-1-2");
m4.add(cmi);
m4.add(mi3);
m3.add(m4);
mb.add(m3);
setMenuBar(mb);
setBounds(100,100,200,200);
setLocation(200, 200);
setVisible(true);
}
public static void main(String[] args) {
new Ex05();
}
}
Dialog
public class Ex06 {
public static void main(String[] args) throws InterruptedException {
Frame f = new Frame();
f.setBounds(100,100,200,200);
f.setVisible(true);
// Dialog dia = new Dialog(f);
// dia.setVisible(true);
// dia.setBounds(250,250,100,100);
FileDialog dia2 = new FileDialog(f, "팝업창", FileDialog.SAVE);
dia2.setTitle("열기창");
dia2.setLocation(100, 100);
dia2.setVisible(true);
String msg = dia2.getFile();
String path = dia2.getDirectory();
String name = dia2.getName();
System.out.println(msg +"\r\n" + path + "\r\n" + name);
Frame f2 = new Frame();
f2.setBounds(110,110,200,200);
f2.setVisible(true);
Thread.sleep(3000);
f.dispose();
}
}
WindowListener
public class Ex07 extends Frame implements WindowListener{
public Ex07() {
addWindowListener(this);
setLocation(200,200);
setBounds(100, 100, 300, 300);
setVisible(true);
}
@Override
public void windowOpened(WindowEvent e) {
System.out.println("열기");
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("닫기버튼");
dispose();
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("dispose() 호출된 후");
}
@Override
public void windowIconified(WindowEvent e) {
System.out.println("최소화");
}
@Override
public void windowDeiconified(WindowEvent e) {
System.out.println("복원");
}
@Override
public void windowActivated(WindowEvent e) {
System.out.println("활성화");
}
@Override
public void windowDeactivated(WindowEvent e) {
System.out.println("비활성화");
}
public static void main(String[] args) {
Ex07 me = new Ex07();
}
}
MouseListener
public class Ex08 extends Frame implements MouseListener{
public Ex08() {
Panel p = new Panel();
Button btn = new Button("버튼");
p.addMouseListener(this);
btn.setBounds(100, 50, 100, 100);
p.add(btn);
add(p);
setBounds(600, 100, 300, 300);
setVisible(true);
}
public static void main(String[] args) {
Ex08 me = new Ex08();
}
@Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("클릭했을 때 x="+x+"y="+y);
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("눌렀을 때");
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("땠을 때");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("마우스가 들어왔을 때");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("마우스가 나갔을 때");
}
}
MouseMotionListener
public class Ex09 extends Frame implements MouseMotionListener{
Label la;
public Ex09() {
Panel p = new Panel();
p.addMouseMotionListener(this);
la = new Label("★");
la.setSize(35,35);
la.setLocation(100,100);
p.add(la);
add(p);
setBounds(200,200,300,300);
setVisible(true);
}
public static void main(String[] args) {
Ex09 me = new Ex09();
}
@Override
public void mouseDragged(MouseEvent e) {
int x = e.getX(); // 기준 이벤트 객체
int y = e.getY();
int sx = e.getXOnScreen(); // 스크린 기준
int sy = e.getYOnScreen();
System.out.println("드래그 x="+x+"y="+y+"sx="+sx+"sy="+sy);
la.setLocation(x,y);
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("움직임");
}
}
KeyListener
public class Ex10 extends Frame implements KeyListener{
static Label la;
static TextField tf;
public Ex10() {
Panel p = new Panel();
tf = new TextField(10);
tf.addKeyListener(this);
la = new Label("★");
la.setSize(35, 35);
p.add(la);
p.add(tf);
add(p);
setBounds(200, 200, 300, 300);
setVisible(true);
}
public static void main(String[] args) throws InterruptedException {
new Ex10();
// while(true) {
// Thread.sleep(1000);
// la.setLocation(la.getX(), la.getY()+10);
// }
}
@Override
public void keyTyped(KeyEvent e) {
// char ch = e.getKeyChar();
// int su = e.getKeyCode();
// System.out.println(ch + "눌렸고 "+ su);
}
@Override
public void keyPressed(KeyEvent e) {
// char ch = e.getKeyChar();
// int su = e.getKeyCode();
// System.out.println(ch + "누르는 중이고 "+ su);
}
@Override
public void keyReleased(KeyEvent e) {
// System.out.println("뗌");
char ch = e.getKeyChar();
int su = e.getKeyCode();
System.out.println(tf.getText());
// int x = la.getX();
// int y = la.getY();
// if(su == 39) {
// System.out.println(e.getKeyCode());
// la.setLocation(x+10, y);
// } else if(su == 37) {
// System.out.println(e.getKeyCode());
// la.setLocation(x-10, y);
// } else if(su == 38) {
// System.out.println(e.getKeyCode());
// la.setLocation(x, y-10);
// } else if(su == 40) {
// System.out.println(e.getKeyCode());
// la.setLocation(x, y+10);
// }
}
}
TextListener
public class Ex11 extends Frame implements TextListener{
@Override
public void textValueChanged(TextEvent e) {
String msg = ((TextField) e.getSource()).getText();
System.out.println(msg);
}
Panel p = new Panel();
TextField tf = new TextField();
public Ex11() {
tf.addTextListener(this);
p.add(tf);
add(p);
setBounds(500, 100, 300, 300);
setVisible(true);
}
public static void main(String[] args) {
new Ex11();
}
}
ItemListener
public class Ex12 extends Frame implements ItemListener{
@Override
public void itemStateChanged(ItemEvent e) {
Choice cho = (Choice) e.getSource();
System.out.println(cho.getSelectedItem());
System.out.println(cho.getSelectedIndex());
}
public Ex12() {
Panel p = new Panel();
Choice c = new Choice();
c.addItem("item1");
c.addItem("item2");
c.addItem("item3");
c.addItem("item4");
c.addItemListener(this);
p.add(c);
add(p);
setBounds(200, 200, 200, 200);
setVisible(true);
}
public static void main(String[] args) {
new Ex12();
}
}
FocusListener
public class Ex13 extends Frame implements FocusListener, TextListener{
@Override
public void textValueChanged(TextEvent e) {
TextField tf = (TextField)e.getSource();
if(tf.getText().length() == 4) {
tf.nextFocus();
}
}
@Override
public void focusGained(FocusEvent e) {
TextField tf = (TextField)e.getSource();
System.out.println(tf.getText()+"포커스 얻음");
}
@Override
public void focusLost(FocusEvent e) {
System.out.println("포커스 잃음");
}
public Ex13(){
Panel p = new Panel();
TextField[] arr = new TextField[5];
for(int i = 0; i < arr.length; i++) {
arr[i] = new TextField(10);
arr[i].addFocusListener(this);
arr[i].addTextListener(this);
p.add(arr[i]);
}
add(p);
setBounds(500, 100, 300, 400);
setVisible(true);
}
public static void main(String[] args) {
Ex13 me = new Ex13();
}
}
ContainerListener
public class Ex14 extends Frame implements MouseListener, ContainerListener{
@Override
public void componentAdded(ContainerEvent e) {
System.out.println("추가됨");
}
@Override
public void componentRemoved(ContainerEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
Label la = new Label("추가");
la.addMouseListener(this);
p.add(la);
validate(); // 검사
// revalidate(); // 재검사
// repaint(); // 화면 새로고침
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
if(e.getSource() != btn) {
Label la = (Label)e.getSource();
la.setVisible(false);
// validate();
}
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
Panel p = new Panel();
Button btn = new Button("추가");
public Ex14() {
p.addContainerListener(this);
btn.addMouseListener(this);
p.add(btn);
add(p);
setBounds(500, 100, 200, 200);
setVisible(true);
}
public static void main(String[] args) {
Ex14 me = new Ex14();
}
}
ActionListener
public class Ex15 extends Frame implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("action...");
}
public Ex15() {
MenuBar mb = new MenuBar();
Menu m = new Menu("메뉴1");
MenuItem mi = new MenuItem("1-1");
mi.addActionListener(this);
m.add(mi);
mb.add(m);
setMenuBar(mb);
Panel p = new Panel();
Label la = new Label("label");
Button btn = new Button("btn");
TextField tf = new TextField(10);
TextArea ta = new TextArea();
Choice cho = new Choice();
cho.addItem("item1");
cho.addItem("item2");
List li = new List();
li.add("list1");
li.add("list2");
Checkbox cb1 = new Checkbox("chk1");
Checkbox cb2= new Checkbox("chk2");
Checkbox cb3 = new Checkbox("chk3");
p.add(la);
p.add(btn);
p.add(tf);
p.add(ta);
p.add(cho);
p.add(li);
p.add(cb1);
p.add(cb2);
p.add(cb3);
btn.addActionListener(this); // 클릭했을 떄
tf.addActionListener(this); // 엔터키 쳤을 떄
li.addActionListener(this); // 선택 후 엔터 or 더블클릭
add(p);
setBounds(500, 100, 300, 500);
setVisible(true);
}
public static void main(String[] args) {
new Ex15();
}
}
Listener Adapter
실제 사용은 각 기능을 구현할 때 Listener의 모든 기능이 필요하지 않기 때문에 interface를 구현하게 될 경우 필요없는 메서드도 정의 해줘야 하기 때문에
코드가 지저분해진다. Adapter를 통해 익명클래스를 구현하는 방식으로 하게되면 필요한 기능만 재정의 해서 불필요한 코드량을 줄일 수 있다.
public class Ex16 extends JFrame{
public Ex16() {
addWindowListener(new WindowAdapter() { // 닫기버튼 구현
@Override
public void windowClosing(WindowEvent e) {
dispose();
}
});
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // JFrame은 닫기버튼을 미리 구현해뒀다.
setBounds(500, 100, 300, 300);
setVisible(true);
}
public static void main(String[] args) {
Ex16 me = new Ex16();
}
}
'회고록(TIL&WIL)' 카테고리의 다른 글
WIL 2023.01.05 ~ 2023.01.06 통신, 네트워크 (0) | 2023.01.16 |
---|---|
WIL 2023.01.02 ~ 2023.01.05 java 공부 (1) | 2023.01.09 |
TIL 2022.12.28 내가 쓰는 단축키 모음집 (0) | 2022.12.28 |
WIL 2022.12.19 ~ 2022.12.23 java 공부 (1) | 2022.12.23 |
WIL 2022.12.12 ~ 2022.12.16 java 공부 (1) | 2022.12.20 |