2020년 12월 04일 9시 ~ 15시 30분 zoom으로 수업 진행
GUI
컨테이너와 컴포넌트
컨테이너
다른 컴포넌트를 포함할 수 있는 GUI 컴포넌트이다
다른 컨테이너에 포함될 수 있다
다른 컨테이너에 속하지 않고 독립적으로 존재가능
스스로 화면에 자기 자신을 출력하는 컨테이너로는 JFrame, JDialog, JApplet 이 있다.
컴포넌트
화면에 출력되는 친구들(버튼, 텍스트필드 , 라디오, 콤보박스 등)
컨테이너에 포함되어야 화면에 출력될 수 있는 GUI객체이다
java.awt.Component 클래스는 모든 GUI 컴포넌트의 최상위 클래스이다
스윙 컴포넌트의 최상위 클래스는 javax.swing.JComponent 이다.
GUI 작업순서
컨테이너 객체 생성
배치 방식을 컨테이너에 세팅
컴포넌트 객체 생성
컨테이너에 컴포넌트 배치
이벤트 처리
컨테이너 객체 생성하는 방법 3가지
1. JFrame 상속을 이용한 방법
import javax.swing.*;
public class 클래스명 extends JFrame { public 클래스명() { super(“MyMemo”); } public static void main(String[] args) { } } |
2. 상속 받지 않고 객체 생성하기
import javax.swing.*;
public class 클래스명{ public static void main(String[] args) { JFrame mainframe = new JFrame(“MyMemo”); } } |
3. JFrame 상속 받은 클래스 작성하고, 실행용 클래스가 실행
import javax.swing.*;
public class 클래스명 extends JFrame { public 클래스명() { super(); } }
class 클래스명1 { public static void main(String[] args) { 클래스명 레퍼런스 = new 클래스명(); } } |
컨테이너 배치 방식 지정
1. borderLayout
모두 5개 영역으로 나누고, 각 영역에 하나의 컴포넌트를 넣을 수 있다.
(NORTH, SOUTH, EAST, WEST, CENTER)
한 영역에 하나 이상의 컴포넌트를 넣고 싶으면 Panel을 사용한다.
2. FlowLayout
컴포넌트를 워드프로세서와 같은 방식, 즉 왼쪽에서 오른쪽으로 배치한다.
4가지 정렬 방식(왼쪽, 가운데, 오른쪽) 이 가능하다.
3. GridLayout
컴포넌트들을 가로, 세로의 일정 수만큼 배치하고자 할 때 주로 사용한다
행과 열을 지정하고, 각 컴포넌트는 동일한 사이즈를 가진다
4. CardLayout
여러 컨테이너를 슬라이드처럼 바꿔가며 보여줄 수 있다
앨범이나 퀴즈 또는 설치프로그램에 주로 사용한다
5. GridBagLayout
컴포넌트의 위치와 크기를 자유롭게 만들 수 있다.
사용하기 복잡함
package com.test01.container;
public class MTest {
public static void main(String[] args) {
//new JFrameTest();
new JFrameTest2().mainFrame();
}
}
package com.test01.container;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class JFrameTest extends JFrame{
//프레임을 생성하는 방법1
//javax.swing.JFrame 클래스 상속 후 생성자에 프레임 관련 설정
public JFrameTest() {
//프레임 크기 설정
//this.setLocation(300, 200);//만들 위치
//this.setSize(800, 500);//프레임 사이즈
//위치와 크기를 한번에 지정
this.setBounds(300, 200, 800, 500);
//프레임이 보여지도록 해당 메소드 실행
this.setVisible(true);//보이게할것인가
//닫기 버튼 눌렀을때 프로세스도 종료되게 하는 메소드
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//프레임 상단에 이름 설정하기
this.setTitle("MyFrame");
//프레임 상단에 표시되는 아이콘 이미지 변경하기
try {
this.setIconImage(ImageIO.read(new File("images/logo.png")));
} catch (IOException e) {
e.printStackTrace();
}
//프레임 사이즈 변경 비활성화
this.setResizable(false);
}
}
package com.test01.container;
import java.awt.Rectangle;
import javax.swing.JFrame;
public class JFrameTest2{
//프레임 생성 방법2
//JFrame 클래스로 객체 생성 후 해당 프레임 객체의 설정 값을 변경하는 방법
public void mainFrame() {
//JFrame mainFrame = new JFrame();
//mainFrame.setTitle("myTitle");
//프레임 생성 시 프레임 상단의 텍스트 함께 지정
JFrame mainFrame = new JFrame("MyFrame2");
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Rectangle r = new Rectangle(300, 200, 800, 500);
mainFrame.setBounds(r);
}
}
package com.test02.layout;
public class MTest {
public static void main(String[] args) {
// new A_Border();
// new B_Flow();
// new C_Grid();
// new D_Card();
new E_Panel();
}
}
package com.test02.layout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class A_Border extends JFrame{
//BorderLayout -> 컴포넌트의 배치 위치 지정 가능
//위치를 지정하지 않으면 배치한 컨테이너의 공간 전체에 배치된다.
public A_Border() {
this.setTitle("BorderLayout");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//size
this.setBounds(300, 200, 800, 500);
//
JButton north = new JButton("북");
JButton south = new JButton("남");
JButton east = new JButton("동");
JButton west = new JButton("서");
JButton center = new JButton("가");
//버튼 배치 위치 지정 , 대소문자 구분
this.add(north, "North");
// this.add(south, "South");
this.add(new JButton("남"), "South");
this.add(east, "East");
this.add(west, "West");
this.add(center, "Center");
}
}
package com.test02.layout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class B_Flow extends JFrame{
public B_Flow() {
super("FlowLayout");//생성되는 프레임의 타이틀 지정
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(300, 200, 800, 500);
//FlowLayout 설정
//this.setLayout(new FlowLayout());//FlowLayout.CENTER가 기본 값
//프레임의 크기를 넘어설 정도로 컴포넌트를 생성하게 될 경우
//줄을 넘겨서 생성된 컴포넌트를 다음 줄에 배치시킨다
//this.setLayout(new FlowLayout(FlowLayout.LEFT));//좌측정렬
this.setLayout(new FlowLayout(FlowLayout.RIGHT));//우측정렬
this.add(new JButton("1번"));
this.add(new JButton("2번"));
this.add(new JButton("3번"));
this.add(new JButton("4번"));
this.add(new JButton("5번"));
this.add(new JButton("6번"));
this.add(new JButton("7번"));
this.add(new JButton("8번"));
this.add(new JButton("9번"));
this.add(new JButton("10번"));
this.add(new JButton("11번"));
this.add(new JButton("12번"));
this.add(new JButton("13번"));
//14번 버튼부터는 두번째 줄에 배치된다.
this.add(new JButton("14번"));
this.add(new JButton("15번"));
}
}
package com.test02.layout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class C_Grid extends JFrame{
public C_Grid() {
super("GridLayout");//생성되는 프레임의 타이틀 지정
this.setBounds(300, 200, 800, 500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//GridLayout(가로, 세로)
//this.setLayout(new GridLayout(5, 5));
//GridLayout(가로, 세로, 가로여백, 세로여백)
this.setLayout(new GridLayout(5, 5, 10, 10));
for(int i=1; i<26; ++i) {
String str = String.valueOf(i);
this.add(new JButton(str));
}
}
}
package com.test02.layout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class D_Card extends JFrame{
public D_Card() {
super("CardLayout");
this.setBounds(300, 200, 800, 500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//CardLayout
//this.setLayout(new CardLayout());
//이렇게 변경 한 이유 -> 이벤트 리스너 사용하면서 패널 변경해주려구
CardLayout card = new CardLayout();
this.setLayout(card);
//Panel
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
JPanel card3 = new JPanel();
//panel 배경색 지정
card1.setBackground(Color.BLUE);
card2.setBackground(Color.DARK_GRAY);
card3.setBackground(new Color(50, 100, 10));//RGB값
//라벨 추가
card1.add(new JLabel("Card1"));
card2.add(new JLabel("Card2"));
card3.add(new JLabel("Card3"));
this.add(card1);
this.add(card2);
this.add(card3);
//실행시켜보면 맨 위에 배치한 card1 프레임만 보임
//진짜 저렇게 배치 한 순서대로 겹쳐져있다고 보면 된다
//패널에 이벤트 추가 -> 마우스 관련 이벤트
card1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getButton());
if(e.getButton() == 1) {
card.next(card1.getParent());
//카드에 부착되어있는 컴포넌트 변경
//card2로 바꿔준당
}
}
});
card2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getButton());
if(e.getButton() == 1) {
card.next(card3.getParent());
}
}
});
card3.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getButton());
if(e.getButton() == 1) {
card.next(card1.getParent());
}
}
});
}
}
package com.test02.layout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class E_Panel extends JFrame{
public E_Panel() {
super("JPanelLayout Test");
this.setBounds(200, 200, 500, 500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println(this.getLayout());//java.awt.BorderLayout[hgap=0,vgap=0]
//컴포넌트 생성 + 설정
JLabel lb = new JLabel("이름 : ");
lb.setLocation(50, 100);
lb.setSize(150, 50);
JTextField tf = new JTextField(20);//20글자
tf.setLocation(110, 100);
tf.setSize(200, 50);
JButton btn = new JButton("추가");
btn.setLocation(550, 100);
btn.setSize(100, 50);
//패널 추가
JPanel panel = new JPanel();
panel.setSize(500,500);
panel.setLayout(null);
System.out.println(panel.getLayout());//null
//컴포넌트들의 위치와 크기가 변경되었다.
//패널에 컴포넌트 배치
panel.add(lb);
panel.add(tf);
panel.add(btn);
panel.setBackground(Color.ORANGE);
//패널을 프레임에 추가
this.add(panel);
}
}
package com.test03.container;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
public class A_TextTest {
public static void main(String[] args) {
JFrame mf = new JFrame();
mf.setSize(800, 300);
mf.setTitle("TestTest");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 2));
panel.setSize(800, 300);
//글을 입력할 수 있는 텍스트 상자
TextField id = new TextField();
panel.add(new JLabel("id : "));
panel.add(id);
//비밀번호를 입력할 수 있는 TextFiled를 JPasswordField라고 함
//입력되는 값을 화면에서 볼 수 없으며, 한글을 입력할 수도 없더
JPasswordField passwd = new JPasswordField();
panel.add(new JLabel("password : "));
panel.add(passwd);
//여러 줄의 텍스트를 입력할 수 있는 상자 TextArea
TextArea textarea = new TextArea(10, 30);//10줄, 30글자
// panel.add(textarea);
textarea.setEnabled(false);//readOnly (내용 수정 불가)
JButton btn = new JButton("보내기");
mf.add(panel, BorderLayout.NORTH);
mf.add(textarea, BorderLayout.CENTER);
mf.add(btn, BorderLayout.SOUTH);
//panel은 Grid를 이용해 칸별로 배치되게 구성한 것
//jframe은 border레이아웃을 이용해 위치별로 배치시킨 것
//보내기 버튼을 눌렀을 때 이벤트 연결
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = "id = " + id.getText() + " , password = " + passwd.getPassword() + "\n";
text += textarea.getText() + "\n";
//문자 배열에 담아서 출력
char[] pass = passwd.getPassword();
for(int i=0; i<pass.length; ++i) {
System.out.println(pass[i]);
//콘솔에는 정상적으로 한 글자씩 얻어오지만
}
textarea.append(text);
//TextArea에 출력시켰을 때는 암호화되어 출력된다
}
});
mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mf.setVisible(true);
}
}
'기록 > 자바_국비' 카테고리의 다른 글
[배운내용정리] 1209 자바 국비교육 (0) | 2020.12.20 |
---|---|
[배운내용정리] 1207 자바 국비교육 (0) | 2020.12.13 |
[배운내용정리] 1203 자바 국비교육 (0) | 2020.12.10 |
[배운내용정리] 1202 자바 국비교육 (2) | 2020.12.10 |
[배운내용정리] 1201 자바 국비교육 (0) | 2020.12.02 |