1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905 |
------------------------------------------------------------------------------------------
package chap09;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import School.SchoolFrame;
public class JButtonClass {
public static void main(String[] args) {
SchoolFrame sf = new SchoolFrame("버튼 컴포넌트", 300, 400);
JButton jb = new JButton("버튼1");
jb.setText("버튼을 클릭하세요.");
jb.setName("bt1");// 버튼이 부여주는 이름
jb.setBounds(10, 30, 100, 200);// 버튼의 영역
System.out.println(jb.getActionCommand());// 버튼의 커멘드 출력
jb.setActionCommand(jb.getActionCommand() + "cmd");// 버튼의 커멘드 설정
System.out.println(jb.getActionCommand());
System.out.println(jb.getName());// 버튼 이름 출력
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {// 이벤트 발생 커멘드 출력
System.out.println(e.getActionCommand());
Object obj = e.getSource();// 이벤트 발생 컴포넌트 가져옴
if (obj instanceof JButton) {// 버튼의 객체 여부 확인
JButton jb1 = (JButton) obj;// 버튼 객체로 형변환
System.out.println(jb1.getName());// 버튼 이름 출력
}
}
});
sf.getContentPane().setLayout(null);
sf.getContentPane().add(jb);
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import School.SchoolFrame;
public class JButtonFrame {
public static void main(String[] args) {
SchoolFrame sf = new SchoolFrame("버튼컴포넌트", 300, 400);
JButton jb = new JButton("버튼1");
JButton jb2 = new JButton("버튼2");
jb.setText("버튼을 클릭하세요");// 버튼에 보여지는 Text
jb.setName("btn1");// 버튼의 이름
jb2.setName("btn2");// 버튼의 이름
jb.setBounds(10, 30, 150, 150);// 버튼의 영역
jb2.setBounds(160, 30, 100, 100);// 버튼의 영역
System.out.println(jb.getActionCommand());// 버튼의 커맨드 출력
jb.setActionCommand(jb.getActionCommand() + "cmd");// 버튼의 커맨드 설정
System.out.println(jb.getActionCommand());
System.out.println(jb.getName());// 버튼의 이름 출력
jb.addActionListener(new ActionListenerClass());
jb2.addActionListener(new ActionListenerClass());
// 버튼에 ActionEvent 등록(연결)
sf.getContentPane().setLayout(null);// 버튼의 외각 수치 null
sf.getContentPane().add(jb);
sf.getContentPane().add(jb2);
sf.setVisible(true);
}
}
class ActionListenerClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
// 이벤트 발생 커맨드 출력
System.out.println(e.getActionCommand());
Object obj = e.getSource();// 이벤트 발생 컴포넌트 가져옴
if (obj instanceof JButton) {// 버튼의 객체 여부 확인
JButton jb1 = (JButton) obj;// 버튼 객체로 형변환
System.out.println(jb1.getName());// 버튼이름 출력
if (jb1.getName().equals("btn2")) {
System.out.println("두번째 버튼이 클릭되었습니다.");
}
}
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import School.SchoolFrame;
public class JCheckBoxClass {
public static void main(String[] args) {
JCheckBox chk1, chk2, chk3;// 체크박스 선언
chk1 = new JCheckBox("체크박스1");// 체크박스 객체 생성
chk2 = new JCheckBox("체크박스2");
chk3 = new JCheckBox("체크박스3");
Box box = new Box(BoxLayout.X_AXIS);// 박스 레이아웃 배치 설정
ItemListener item = new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
Object obj = ie.getItem();// Item 객체 가져오기
System.out.println(obj);
if (obj instanceof JCheckBox) {
JCheckBox jb = (JCheckBox) obj;// 형변환
System.out.println(jb.getText());
}
}
};
chk1.addItemListener(item);// 체크박스에 ItemEvent 등록
chk2.addItemListener(item);
chk3.addItemListener(item);
box.add(chk1);
box.add(chk2);
box.add(chk3);
chk2.setSelected(true);// 체크박스 선택하기
SchoolFrame sf = new SchoolFrame("체크박스", 300, 400);
sf.getContentPane().add(box);
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import School.SchoolFrame;
public class JComboBoxClass {
public static void main(String[] args) {
SchoolFrame sf = new SchoolFrame("콤보박스", 100, 200);
String fruit[] = { "사과", "딸기", "포도", "바나나", "수박" };
// 1차원배열선언 및 초기화
ItemListener item = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Object obj = e.getSource();
System.out.println(obj);
if (obj instanceof JComboBox) {
JComboBox jb = (JComboBox) obj;
System.out.println(jb.getSelectedItem());
// 콤보박스에서 선택된 아이템 출력
System.out.println(e.getItem());
// 이벤트 발생한 아이템 출력
System.out.println("인덱스:" + jb.getSelectedIndex());
System.out.println("커멘드:" + jb.getActionCommand());
System.out.println("=============================");
}
}
};
ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
System.out.println("-------------------");
}
};
JComboBox combo = new JComboBox();// 콤보박스 선언 및 초기화
combo.setEditable(true);// 콤보박스 편집가능 모드 설정
combo.addItemListener(item);// 아이템이벤트 등록
combo.addActionListener(action);// 액션이벤트 등록
for (String fr : fruit) {
combo.addItem(fr);// 콤보박스에 아이템 등록
}
sf.getContentPane().add(combo);
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------
package chap09;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import School.SchoolFrame;
public class JListClass {
public static void main(String[] args) {
String[] fruit = { "사과", "딸기", "수박", "참외", "바나나" };
DefaultListModel<String> dlm = new DefaultListModel<String>();
// 기본 리스트모델 객체선언 및 생성
for (int i = 0; i < fruit.length; i++) {
dlm.addElement(fruit[i]);// 리스트모델에 항목추가
}
dlm.addElement("구아바");
JList list = new JList(dlm);// 리스트 객체 선언 및 생성
ListSelectionListener lsl = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
Object obj = e.getSource();
System.out.println(obj);
if (obj instanceof JList) {
JList jl = (JList) obj;
dlm.addElement(jl.getSelectedValue() + "1");
System.out.println(jl.getSelectedValue());
}
}
};
dlm.removeElement("바나나");
list.addListSelectionListener(lsl);// 셀렉션이벤트 등록
SchoolFrame sf = new SchoolFrame("리스트", 200, 100);
JScrollPane jsp = new JScrollPane(list);
sf.getContentPane().add(jsp);
list.setVisibleRowCount(3);
list.setSelectedIndex(2);
sf.pack();
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import School.SchoolFrame;
public class JPanelPaint {
public static void main(String[] args) {
SchoolFrame sf = new SchoolFrame("그리기", 500, 400);
Canvus jp = new Canvus();
// Graphics g = jp.getGraphics();
// paint(g);
sf.getContentPane().add(jp);
sf.setVisible(true);
}
public static void paint(Graphics g) {
g.drawString("도형그리기", 100, 100);
}
}
class Canvus extends JPanel {
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, 500, 400);
g.setColor(Color.black);
g.drawString("도형그리기", 100, 100);
g.setColor(Color.blue);
g.drawLine(10, 10, 200, 150);
g.setColor(Color.red);
g.drawLine(480, 10, 10, 380);
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
import School.SchoolFrame;
public class JRadioButtonClass {
public static void main(String[] args) {
JRadioButton[] radio;// 객체 배열 선언
radio = new JRadioButton[5];// 객체배열 생성
for (int i = 0; i < radio.length; i++) {
radio[i] = new JRadioButton("라디오버튼" + (i + 1));
// 배열 요소 라디오버튼 객체 생성
}
radio[0].setSelected(true);// 첫번째 라디오버튼 선택
radio[1].setSelected(true);// 두번째 라디오버튼 선택
ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String comd = e.getActionCommand();
System.out.println(comd);
}
};
ButtonGroup bg = new ButtonGroup();
SchoolFrame sf = new SchoolFrame("라디오버튼", 500, 300);
sf.getContentPane().setLayout(new GridLayout(1, radio.length));
// 1행 5열 배치
for (int i = 0; i < radio.length; i++) {
bg.add(radio[i]);// 버튼 그룹에 등록
radio[i].addActionListener(action);// action이벤트 등록
sf.getContentPane().add(radio[i]);// 라디오 버튼을 기본팬에 부착
}
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.BorderLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JScrollBar;
import School.SchoolFrame;
public class JScrollBarClass {
public static void main(String[] args) {
JScrollBar jsb = new JScrollBar(JScrollBar.HORIZONTAL, 1, 1, 0, 200);
JScrollBar jsb1 = new JScrollBar(JScrollBar.VERTICAL, 1, 1, 0, 200);
AdjustmentListener al = new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.printf("가로:%d, 세로:%d%n", jsb.getValue(), jsb1.getValue());
}
};
jsb.addAdjustmentListener(al);
jsb1.addAdjustmentListener(al);
SchoolFrame sf = new SchoolFrame("스크롤바", 200, 80);
// jsb.setValue(80);
// jsb.setMaximum(120);
// jsb.setMinimum(50);
sf.getContentPane().add(jsb, BorderLayout.SOUTH);
sf.getContentPane().add(jsb1, BorderLayout.EAST);
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import School.SchoolFrame;
public class JTableClass {
public static void main(String[] args) {
String header[] = { "성명", "아이디", "나이", "이메일여부" };
// 테이블의 항목명
Object[][] data = {
{ "홍길동", "gildong", new Integer(16), new Boolean(true) },
{ "성춘향", "hyang", new Integer(15), new Boolean(false) },
{ "이몽룡", "myong", new Integer(16), new Boolean(false) }
};
// userTableModel utm = new UserTableModel(data, header);
// 테이블의 데이터
UserTableModel utm = new UserTableModel(data, header);
UserTableModel1 utm1 = new UserTableModel1(data, header);
System.out.println(utm.getColumnName(0));
// 컬럼명 변경
String header1[] = new String[2];
header[0] = header[0];
header1[1] = header[2];
utm.setHeader(header1);
// JTable jt = new JTable(data, header);// 테이블 객체선언 및 생성
JTable jt = new JTable(utm);// 테이블 객체 선언 및 생성
System.out.println("열수:" + utm1.getColumnCount());
System.out.println("행수:" + utm1.getRowCount());
// 세번째행의 세번째열의 값 출력
System.out.println("셀값:" + utm1.getValueAt(2, 2));
for (int i = 0; i < utm1.getRowCount(); i++) {
for (int j = 0; j < utm1.getColumnCount(); j++) {
// System.out.printf("셀값:%s, " +
// String.valueOf(utm1.getvalueAt(i, j)) + ", ");
Object obj = utm1.getValueAt(i, j);
// 테이블의 행, 열 번째의 값을 가져옴
if (obj instanceof String) {
System.out.printf("셀값:%s, ", String.valueOf(utm1.getvalueAt(i, j)));
if (j == 0)
utm1.setValueAt(String.valueOf(utm1.getValueAt(i, j)).concat("님"), i, j);
// 테이블의 행, 열 번째 값을 변경
} else if (obj instanceof Integer) {
System.out.printf("셀값:%s, ", String.valueOf(utm1.getvalueAt(i, j)));
utm1.setValueAt(String.valueOf(utm1.getValueAt(i, j)).concat("살"), i, j);
} else if (obj instanceof Boolean) {
System.out.printf("셀값:%s, ", String.valueOf(utm1.getvalueAt(i, j)));
}
}
System.out.println();
} /*----------공간부족으로 <<TAB두번하였음.----------*/
jt.setPreferredScrollableViewportSize(new Dimension(200, 100));
// 스크롤 뷰포인트 사이즈 변경
JScrollPane jsp = new JScrollPane(jt);
// 스크롤팬에 테이블 부착
SchoolFrame sf = new SchoolFrame("테이블", 300, 100);
sf.getContentPane().add(jsp);
sf.setVisible(true);
}
}
class UserTableModel1 extends DefaultTableModel {
private Object[][] data;
private Object[] header;
UserTableModel1(Object[][] data, Object[] header) {
super(data, header);
this.data = data;
this.header = header;
}
public int getColumnCount() {
return super.getColumnCount();
}
public String getColumnName(int arg0) {
return super.getColumnName(arg0);
}
public Vector getDataVector() {
return super.getDataVector();
}
public int getRowCount() {
return super.getRowCount();
}
public Object getvalueAt(int arg0, int arg1) {
return super.getValueAt(arg0, arg1);
}
}
class UserTableModel extends AbstractTableModel {
private Object[][] data;
private Object[] header;
UserTableModel(Object[][] data, Object[] header) {
this.data = data;
this.header = header;
}
public void setHeader(Object[] header) {
this.header = header;
}
public String getColumnName(int column) {
return String.valueOf(header[column]).concat("컬럼");// 컬럼명을 리턴 함
}
public int getColumnCount() {
return header.length;// 컬럼수를 리턴해줌, 1차원 배열 컬럼명의 갯수 리턴
}
public int getRowCount() {
return data.length;// 0=>2차원 배열의 행수를 리턴
}
public Object getValueAt(int arg0, int arg1) {
return String.valueOf(data[arg0][arg1]).concat("'");
// 2차원 배열의 해당행, 열 요소를 리턴
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import School.SchoolFrame;
public class JTextAreaClass {
public static void main(String[] args) {
JTextArea jta = new JTextArea(10, 100);// 텍스트영역 10행 100열
SchoolFrame sf = new SchoolFrame("텍스트영역", 300, 400);
JScrollPane jsp = new JScrollPane(jta);
// 스크롤팬을 이용하여 텍스트영역에 스크롤바 기능
JButton jb = new JButton("클릭");
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(jta.getText());
}
});
jta.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
System.out.println(jta.getText());
}
});
sf.getContentPane().add(jsp, BorderLayout.CENTER);
sf.getContentPane().add(jb, BorderLayout.SOUTH);
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import School.SchoolFrame;
public class JTextFieldClass {
public static void main(String[] args) {
String field[] = { "성명", "아이디", "나이", "이메일", "암호" };
// 입력항목 배열로 선언
JTextField[] jtf = new JTextField[field.length - 1];
JPasswordField[] jpf = new JPasswordField[1];
JLabel[] jl = new JLabel[field.length];
// 텍스트 필드 객체배열 선언 및 배열 생성
for (int i = 0; i < field.length; i++) {
jl[i] = new JLabel(field[i]);
jl[i].setBackground(Color.gray);
jl[i].setForeground(Color.blue);
if (field[i].equals("암호")) {
jpf[0] = new JPasswordField();
jtf[0].addActionListener(new ActionListenerJTextFieldClass());
jtf[0].addFocusListener(new FocusListenerClass());
} else {
jtf[i] = new JTextField(field[i] + "를(을) 입력하세요.", 10 * (i + 1));
// 배열요소 텍스트필드 객체 생성
jtf[i].addActionListener(new ActionListenerJTextFieldClass());
// 텍스트필드에 액션이벤트 등록
jtf[i].addFocusListener(new FocusListenerClass());
// 텍스트필드에 포커스이벤트 등록
}
}
jtf[1].setText("아이디고정");// jtf[1] "아이디" 텍스트 변경
jtf[1].setEditable(false);// jtf[1]"아이디" 편집 모드 사용 못함
SchoolFrame sf = new SchoolFrame("텍스트필드", 500, 300);
sf.setLayout(new GridLayout(field.length, 2));
for (int i = 0; i < field.length; i++) {
sf.getContentPane().add(jl[i]);
if (field[i].equals("암호")) {
sf.getContentPane().add(jpf[0]);
} else {
sf.getContentPane().add(jtf[i]);// 기본팬에 텍스트필드 부착
}
}
sf.setVisible(true);
}
}
class ActionListenerJTextFieldClass implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
Object obj = arg0.getSource();// 이벤트 발생한 컴포넌트를 가져옴
if (obj instanceof JTextField) {
JTextField jtf = (JTextField) obj;// 형변환
System.out.println("gain:" + jtf.getText());
}
}
}
class FocusListenerClass extends FocusAdapter {
private String content;
public void focusGained(FocusEvent e) {
super.focusGained(e);
Object obj = e.getSource();// 이벤트 발생한 컴포넌트를 가져옴
if (obj instanceof JTextField) {
JTextField jtf = (JTextField) obj;// 형변환
String str = jtf.getText();
content = str;
jtf.setText("");// 텍스트 필드 내용 지우기
System.out.println("gain:" + jtf.getText());
} else if (obj instanceof JPasswordField) {
JPasswordField jtf = (JPasswordField) obj;// 형변환
System.out.println("gain-password:" + jtf.getPassword());
}
}
public void focusLost(FocusEvent e) {
super.focusLost(e);
Object obj = e.getSource();
if (obj instanceof JTextField) {
JTextField jtf = (JTextField) obj;
String str = jtf.getText();
if (content.equals(str) || str == null || str.length() <= 0)
jtf.setText(content);
// 텍스트필드의 이전의 문자와 현재 문자가 같으면 이전 문자로 변경
System.out.println("lost:" + jtf.getText());
}
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import School.SchoolFrame;
public class JTreeNodeClass {
static JTextArea jta;
public static void main(String[] args) {
SchoolFrame sf = new SchoolFrame("트리", 300, 500);
jta = new JTextArea("", 20, 80);
JSplitPane jp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
JScrollPane jsp = new JScrollPane(jta);
DefaultMutableTreeNode dmtn = new DefaultMutableTreeNode("자바");
String[][] node = {
{ "파일열기", "파일저장", "다른이름으로 저장", "종료" },
{ "복사하기", "오려두기", "붙여넣기" }
};
DefaultMutableTreeNode[][] nodes = new DefaultMutableTreeNode[node.length][];
nodes[0] = new DefaultMutableTreeNode[node[0].length];
nodes[1] = new DefaultMutableTreeNode[node[1].length];
DefaultMutableTreeNode file = new DefaultMutableTreeNode("파일");
DefaultMutableTreeNode edit = new DefaultMutableTreeNode("편집");
for (int i = 0; i < node.length; i++) {
for (int j = 0; j < node[i].length; j++) {
nodes[i][j] = new DefaultMutableTreeNode(node[i][j]);
if (i == 0)
file.add(nodes[i][j]);
else
edit.add(nodes[i][j]);
}
}
dmtn.add(file);
dmtn.add(edit);
JTree jt = new JTree(dmtn);
jt.addTreeSelectionListener(new TreeSelectionListener() {// 트리선택 이벤트 등록
public void valueChanged(TreeSelectionEvent arg0) {
Object obj = arg0.getSource();
if (obj instanceof JTree) {
JTree jt = (JTree) obj;
System.out.println(jt.getLastSelectedPathComponent());
if ("파일열기".equals(String.valueOf(jt.getLastSelectedPathComponent()).trim())){
JFileChooser jfc = new JFileChooser();
int retValue = jfc.showOpenDialog(null);
if (retValue == 0) {
File f = jfc.getSelectedFile();
System.out.println(f.getName());
}
}
}
}
});
jp.setRightComponent(jsp);
jp.setLeftComponent(jt);
jt.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
sf.getContentPane().add(jt);
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JButton;
public class LatButton extends JButton {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public LatButton() {
title = "";
}
public LatButton(String title) {
this.title = title;
}
public void paint(Graphics g) {
Dimension d = this.getSize();
int x = (d.width - title.length() * 10) / 2;
int y = (d.height - 10) / 2;
g.drawString(title, x, y);
// 둥근사각형 그리기 X좌표, Y좌표, 넓이, 높이, 모서리 넓이, 모서리 높이
g.drawRoundRect(5, 5, d.width + 10, d.height + 10, 3, 3);
}
}
------------------------------------------------------------------------------------------
package chap09;
import School.SchoolFrame;
public class MyButtonClass {
public static void main(String[] args) {
LatButton lb = new LatButton();
LatButton lb1 = new LatButton("버튼1");
lb.setTitle("버튼2");
lb.setBounds(10, 20, 50, 50);
lb1.setBounds(180, 20, 50, 50);
lb.setName("btn1");
lb1.setName("btn2");
lb.addActionListener(new ActionListenerClass());
lb1.addActionListener(new ActionListenerClass());
SchoolFrame sf = new SchoolFrame("마이 버튼", 300, 400);
sf.getContentPane().setLayout(null);
sf.getContentPane().add(lb);
sf.getContentPane().add(lb1);
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------
package chap09;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import School.SchoolFrame;
public class PullDownMenu {
static JTextArea jta;
static JPopupMenu jpm;
public static void main(String[] args) {
// TODO Auto-generated method stub
SchoolFrame sf = new SchoolFrame("메뉴", 400, 300);
jta = new JTextArea("텍스트편집", 10, 80);
// 텍스트영역 객체 선언 및 생성
jpm = new JPopupMenu(); // 팝업메뉴 생성
JMenuBar jmb = new JMenuBar();
JMenu file = new JMenu("파일");
JMenu edit = new JMenu("편집");
String[][] item = { // 2차원 배열 메뉴항목명 선언
{ "파일열기", "파일저장", "다른이름으로저장", "|", "종료" },
{ "복사", "오려두기", "붙이기", "|", "편집여부" }
};
JMenuItem[][] menuItem = new JMenuItem[item.length][item[0].length];
// 2차원 메뉴아이템 객체 생성
JCheckBoxMenuItem jbmi = null;
for (int i = 0; i < item.length; i++) {
for (int j = 0; j < item[i].length; j++) {
if (item[i][j].endsWith("여부")) {
// "여부" 글자로 끝나는 메뉴아이템은 체크박스 메뉴아이템의 객체 생성
jbmi = new JCheckBoxMenuItem(item[i][j]);
jbmi.addItemListener( // 아이템이벤트 등록
new ItemListener() {
// 익명의 클래스 선언 및 생성자로 객체 생성
@Override
public void itemStateChanged(ItemEvent arg0) {
Object obj = arg0.getSource();
if (obj instanceof JCheckBoxMenuItem) {
JCheckBoxMenuItem jbmi = (JCheckBoxMenuItem) obj;
System.out.println(jbmi.getState());
if (jbmi.getState()) {
System.out.println(jbmi.getText());
}
jta.setEditable(jbmi.getState()); // 편집여부
}
}
});
} else {
menuItem[i][j] = new JMenuItem(item[i][j]);
// 2차원 요소의 객체에 메뉴아이템 객체 생성 및 초기화
menuItem[i][j].addActionListener( // 액션 이벤트 등록
new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
if ("파일열기".equals(e.getActionCommand())) {
JFileChooser jfc = new JFileChooser();
int retValue = jfc.showOpenDialog(null);
if (retValue == 0) {
File f = jfc.getSelectedFile();
jta.setText(f.getName());
}
}
}
});
}
if (i == 0) {
if (item[i][j].equals("|"))
file.addSeparator();
else
file.add(menuItem[i][j]); // 메뉴에 메뉴아이템 부착
} else {
if (item[i][j].endsWith("여부")) {
edit.add(jbmi);
} else {
if (item[i][j].equals("|"))
edit.addSeparator();
else
edit.add(menuItem[i][j]); // 메뉴에 메뉴아이템 부착
}
}
}
}
JScrollPane jsp = new JScrollPane(jta); // 스크롤팬 선언 및 생성
JMenu jm = new JMenu("팝업메뉴"); // 팝업용 메뉴 객체 선언 및 생성
JMenuItem[] jmi = new JMenuItem[3]; // 팝업용 메뉴아이템 배열 선언 및 생성
JMenuItem jmi1 = new JMenuItem("이동");
jm.add(jmi1);
for (int i = 0; i < 3; i++) {
jmi[i] = new JMenuItem(item[1][i]); // 메뉴아이템 배열요소의 객체 생성
jmi[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
});
jm.add(jmi[i]); // 메뉴에 메뉴아이템 부착
jpm.add(jmi[i]); // 팝업 메뉴에 메뉴 아이템 부착
}
jpm.add(jm); // 팝업메뉴에 메뉴 부착
jta.addMouseListener( // 마우스 이벤트 등록
new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
super.mouseReleased(arg0);
if (arg0.isPopupTrigger()) { // 팝업이벤트 여부 확인
jpm.show(arg0.getComponent(), arg0.getX(), arg0.getY());
// 팝업메뉴 보기
}
}
});
jmb.add(file); // 메뉴바에 메뉴 추가
jmb.add(edit); // 메뉴바에 메뉴 추가
jta.setEditable(false);
sf.getContentPane().add(jsp); // 기본팬에 스크롤팬 부착
sf.setMenuBar(jmb); // 메뉴바 부착
sf.setVisible(true);
}
}
------------------------------------------------------------------------------------------ |
cs |
'Legend 개발자 > Java' 카테고리의 다른 글
Read Code(Chap.08) (0) | 2017.07.20 |
---|---|
Read Code(Chap.07) (0) | 2017.07.20 |
Read Code(Chap.06) (0) | 2017.07.20 |
Read Code(Chap.05) (0) | 2017.07.20 |
Read Code(Chap.04) (0) | 2017.07.20 |