Java

250224_ 자바 GUI 기능들..

minquu 2025. 2. 24. 22:51
반응형

자바 GUI

- .net의 윈폼처럼 자바에서 지원하는 UI Tookit 같은 클래스들의 모음집

- 주로 java.awt 나 javax.swing 의 패키지를 이용함

https://docs.oracle.com/en/java/javase/23/docs/api/java.desktop/java/awt/package-summary.html

 

java.awt (Java SE 23 & JDK 23)

A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center. The DisplayMode class encapsulates the bit depth, height, width, and refresh rate of a GraphicsDevice. Thrown when cod

docs.oracle.com

 


 

Frame 클래스

package Frame_pro;

import java.awt.*;

public class FrameTest01 {
    public static void main(String[] args) {

        //프레임 틀 만들기
        Frame frame = new Frame("First Frame");

        frame.setBounds(500,500,400,300);

        System.out.println(frame.getBounds().getWidth());
        System.out.println(frame.getBounds().getHeight());

        frame.setBackground(Color.BLUE);
        frame.setVisible(true);         //화면에 안 보임ㅋ
    }
}

- setBounds() -> x , y 위치 와 width와 height 사이즈 조절 매개변수로 받음

- setBackground() -> 백 그라운드 색 설정

- setVisible() -> 처음에 꺼져 있기 때문에 켜줘야함

 

JFrame 클래스

package Frame_pro;

import javax.swing.*;
import java.awt.*;

public class FrameTest02 {
    public static void main(String[] args) {
        JFrame jframe = new JFrame("두번 째 프레임 ");

        //너비 높이
        jframe.setSize(300, 300);
        //x좌표,y좌표
        jframe.setLocation(800,100);

        //창 닫기 가능

        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jframe.setVisible(true);

        //여러개 프레임중 하나의 프레임 만종료할 때 사용
        //jframe.dispose();

        //강제로 종료
        //System.exit(0);
    }
}

- Frame과 많이 비슷하지만, jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 처럼 끌 수 있는 기능을 제공

- JFrame 은 Frame를 사용하고 있음

 

Toolkit 클래스

package Frame_pro;

import java.awt.*;

public class FrameTest05 {
    public static void main(String[] args) {
        Frame fr = new Frame();
        fr.setSize(400, 400);

        //1. toolkit를총해서 모니터 해상도가져옴
        Toolkit tk = Toolkit.getDefaultToolkit();

        //2. Dimenstion을 통해서 중앙 좌표값 설정하기
        Dimension di = tk.getScreenSize();
        int mW = di.width;
        int mH = di.height;

        System.out.println("mW = " + mW);
        System.out.println("mH = " + mH);

        fr.setLocation(mW / 2 - fr.getWidth() / 2, mH / 2 - fr.getHeight() / 2);

        fr.setVisible(true);
    }
}

- Toolkit 클래스는 좌표 및 여러가지 기능일 제공함

   - Toolkit static 에서 get으로 디폴트 툴킷을 가져옴

- Toolkit 안에 getScreenSize를 가져오면 Dimenstion 클래스로 반환 

 

WindowListener 인터페이스

package Frame_pro;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class ListenerClass implements WindowListener {

    @Override
    public void windowOpened(WindowEvent e) {

    }

    @Override
    public void windowClosing(WindowEvent e) {

    }

    @Override
    public void windowClosed(WindowEvent e) {

    }

    @Override
    public void windowIconified(WindowEvent e) {

    }

    @Override
    public void windowDeiconified(WindowEvent e) {

    }

    @Override
    public void windowActivated(WindowEvent e) {

    }

    @Override
    public void windowDeactivated(WindowEvent e) {

    }
}

- Add이벤트로 넣을 인터페이스임

 

package Frame_pro;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class FrameTest04 {
    public static void main(String[] args) {
        MyFrame fr = new MyFrame();
        fr.setBackground(Color.pink);
        fr.setTitle("네 번 째 사용자 프레임");

        //이벤트 감지자 등록
//        MyEventListener listener = new MyEventListener();
//        fr.addWindowListener(listener);

//        WinclosingListener winclosingListener = new WinclosingListener();
//        fr.addWindowListener(winclosingListener);

        fr.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e)
            {
                System.out.println("어댑터 생성하여 감지");
                System.exit(0);
            }
        });
    }
}

- Frame의 addWindowListener메서드에 리스너 인터페이스를 넣어줌

- 위와 같이 람다로도 가능함!

 


Layout과 Button

package Layout;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ButtonTest02 {
    public static void main(String[] args) {
        Frame f = new Frame();
        f.setBounds(800, 100, 1000, 500);
        f.setLayout(new FlowLayout());

        Button btn1 = new Button("1");
        Button btn2 = new Button("2");
        Button btn3 = new Button("3");
        Button btn4 = new Button("4");

        btn1.setPreferredSize(new Dimension(200, 100));
        btn2.setPreferredSize(new Dimension(200, 100));
        btn3.setPreferredSize(new Dimension(200, 100));
        btn4.setPreferredSize(new Dimension(200, 100));

        f.add(btn1);
        f.add(btn2);
        f.add(btn3);
        f.add(btn4);

        f.setVisible(true);

        //버튼 이벤트 감지자 등록
        btn1.addActionListener(al);
        btn2.addActionListener(al);
        btn3.addActionListener(al);
        btn4.addActionListener(al);

        //종료버튼 감지
        f.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    static ActionListener al = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(e.getActionCommand());

            if(e.getActionCommand().equals("1"))
                System.out.println("1번 버튼 누름");
            else if (e.getActionCommand().equals("2"))
                System.out.println("2번 버튼 누름");
            else if (e.getActionCommand().equals("3"))
                System.out.println("3번 버튼 누름");
            else if (e.getActionCommand().equals(""))
                System.out.println("4번 버튼 누름");

            System.out.println("------------------------------");
            }
        };
    }

- frame.setLayout에서 레이아웃 세팅을 해 줄 수 있음 (https://yoo11052.tistory.com/45)

 

[Java/Swing] 3강) Layout의 종류

저번강의 에서 컨테이너와 컴포넌트의 개념과 컨테이너에 컴포넌트를 추가하는 방법에 대해 간략하게 알아보았습니다. 이번강의에서는 컴포넌트들의 위치를 자동으로 지정해주는 Layout에 대해

yoo11052.tistory.com

레이아웃 종류들 참고

 

- button를 통해서 버튼을 생성 할 수 있음

  - 버튼은 꼭 프레임에 .add를 해줘야함

  - addActionListener를 통해서 이벤트를 물려줄 수 있음!

 

 

ImageIcon

package Layout;

import javax.swing.*;
import java.awt.*;

public class ButtonTest03 extends JFrame {

    JPanel main_panel;
    JButton button;

    ImageIcon icon1 = new ImageIcon("btn.jpeg");
    ImageIcon icon2 = new ImageIcon("btn1_1.jpeg");

    public ButtonTest03() {
        setTitle("JButton 이미지 넣기");
        setSize(500, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        main_panel = new JPanel();
        main_panel.setBackground(Color.white);

        button = new JButton(icon1);
        button.setRolloverIcon(icon2);
        button.setBorderPainted(false);
        button.setPreferredSize(new Dimension(150, 50));

        //패널 > 버튼  => 둘 다 사용하기 위해서는 애드를 서로 해줘야함
        main_panel.add(button);
        add(main_panel);

        setVisible(true);
    }

    public static void main(String[] args) {
        ButtonTest03 buttonTest03 = new ButtonTest03();

    }
}

- ImageIcon으로 이미지 가져와서 클래스 생성

  - JButton 생성 시 - 이미지 매개변수로 전달

  - setRollverIcon은 마우스가 오버되었을 때 아이콘을 변경해주는 것

- Panel 사용해줌 -> 패널은 구조적인 것...

  - 구조 설계 시 프레임 > 패널 > 컴포넌트로 짜면 될듯?

 


 

Check Box

package check_choice;

import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class CheckBoxText extends Frame {

    public static void main(String[] args) {

        Frame f = new Frame();
        f.setBounds(500,100,800,250);
        f.setLayout(new FlowLayout());

        //폰트 변경
        Font font = new Font("맑은 고딕", Font.BOLD, 30);

        Label q1 = new Label("1. 관심 분야는 무엇입니까?");
        Checkbox news =new Checkbox("news", true);
        Checkbox sport =new Checkbox("sport");
        Checkbox movie =new Checkbox("movie");
        Checkbox music =new Checkbox("music");

        news.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                String str = e.getStateChange() ==1? "뉴스 선택됨" : "뉴스 선택해제";
                System.out.println(str);

            }
        });

        q1.setFont(font);
        f.add(q1);
        f.add(news);
        f.add(sport);
        f.add(movie);
        f.add(music);

        Label q2 = new Label("2. 한달에 영화는 얼마나 자주 보나요?");
        CheckboxGroup group = new CheckboxGroup();
        //GROUP - RADIO 처럼 단일선택
        Checkbox one = new Checkbox("한 번", group, true);
        Checkbox two = new Checkbox("두 번", group, false);
        Checkbox three = new Checkbox("세 번", group, false);

        one.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                System.out.println("한 번 봅니다.");

            }
        });

        two.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                System.out.println("두 번 봅니다.");

            }
        });

        three.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                System.out.println("세 번 봅니다.");

            }
        });

        q2.setFont(font);
        f.add(q2);
        f.add(one);
        f.add(two);
        f.add(three);

        f.setVisible(true);

        f.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

}

- 체크 박스 사용가능.

  - 이벤트는 itemStateChanged에서 캐치 가능

  - Group 옵션을 주면 단일 체크 박스만 가능!

 

Choice 클래스 

package check_choice;

import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ChoiceTest {
    public static void main(String[] args) {
        Frame frame = new Frame("질문");
        frame.setSize(500,250);
        frame.setLocation(400,100);

        //레이아웃 자동배치
        frame.setLayout(null);

        //=========================
        Choice choice = new Choice();
        choice.add("요일 선택");
        choice.add("SUN");
        choice.add("MON");
        choice.add("TUE");
        choice.add("WEN");
        choice.add("THU");
        choice.add("FRI");
        choice.add("SAT");

        choice.setSize(300, 50);
        choice.setLocation(50,100);

        choice.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                System.out.println("요일" + choice.getSelectedItem());
            }
        });

        frame.add(choice);
        frame.setVisible(true);

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

- 드롭 박스 같은 역할을 하는 클래스

 

TextArea, TextField 클래스

package check_choice;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class TetFieldTest {
    public static void main(String[] args) {
        Frame frame = new Frame("문장 입력기");
        frame.setBounds(800, 100, 400, 400);
        frame.setBackground(Color.pink);

        //폰트
        Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 18);

        //북쪽
        Panel pNorth = new Panel();
        pNorth.setBackground(Color.CYAN);

        //입력 상자
        TextField tf = new TextField(10);
        Button btn = new Button("입력");
        btn.setEnabled(false);

        //panel에 입력 상자 넣기
        pNorth.add(tf);
        pNorth.add(btn);
        pNorth.setFont(font);

        //중앙단(String text, int row, int columns,스클로 종류)
        TextArea ta = new TextArea("", 0, 0, TextArea.SCROLLBARS_VERTICAL_ONLY);
        ta.setBackground(Color.WHITE);
        ta.setFont(font);
        ta.setEditable(false);

            //남쪽단
            Panel pSouth = new Panel();
        pSouth.setFont(font);
        pSouth.setBackground(Color.MAGENTA);

            Button btnSave = new Button("저장");
            Button btnLoad = new Button("불러오기");
            Button btnClose = new Button("닫기");

        pSouth.add(btnSave);
        pSouth.add(btnLoad);
        pSouth.add(btnClose);

            //컴포넌트에배치
        frame.add(pNorth, BorderLayout.NORTH);
        frame.add(ta, BorderLayout.CENTER);
        frame.add(pSouth, BorderLayout.SOUTH);

        frame.setVisible(true);
        frame.setResizable(false);

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        //------------------------Key 이벤트-----------------
      /*즉, 사용자가 텍스트 필드에 입력한 후 엔터 키를 누르면,
      해당 내용이 텍스트 영역에 출력되고 텍스트 필드는 초기화되어 다음 입력을 받을 준비를 합니다.*/
        tf.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if(e.getKeyChar() == KeyEvent.VK_ENTER) {
                    ta.append(tf.getText()+ "\n");
                    tf.setText("");
                    tf.requestFocus();
                }
            }
        });


        //------------------Button이벤트(입력)--------------------
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ta.append(tf.getText()+"\n");

                tf.setText("");
                tf.requestFocus();

            }
        });
        //------------------Button이벤트(닫기)--------------------
        btnClose.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        //------------------Button이벤트(저장)--------------------
        btnSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String message=ta.getText();

                try {
                    //FileDialog : 저장, 로드할 때 사용되는 대화상자
                    FileDialog fd=new FileDialog(frame, "저장",FileDialog.SAVE );
                    fd.setVisible(true);

                    String path=fd.getDirectory()+fd.getFile();

                    if(!message.equals("")) { //message에 데이터가 비워있지 않다면
                        FileWriter fw=new FileWriter(path);
                        BufferedWriter bw=new BufferedWriter(fw);
                        bw.write(message);
                        if(fd.getFile() != null) {
                            JOptionPane.showMessageDialog(frame, path+"\n 경로에 저장했습니다.");
                        }
                        bw.close();
                    }else {
                        JOptionPane.showMessageDialog(frame, "저장 할 내용이 없습니다.");
                    }

                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });

        //파일불러오기
        btnLoad.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                FileDialog fileDialog = new FileDialog(frame, "파일 불러오기", FileDialog.LOAD);
                fileDialog.setVisible(true);

                String directory = fileDialog.getDirectory();
                String fileName = fileDialog.getFile();

                if (directory != null && fileName != null) {
                    String filePath = directory + fileName;
                    try {
                        StringBuilder fileContent = new StringBuilder();
                        BufferedReader br = new BufferedReader(new FileReader(filePath));
                        String line;
                        while ((line = br.readLine()) != null) {
                            fileContent.append(line).append("\n");
                        }
                        br.close();

                        ta.setText(fileContent.toString());
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(frame, "파일을 불러오는 도중 오류가 발생했습니다.");
                    }
                }
            }
        });

        //종료
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

- 텍스트Area와 텍스트필드 클래스로 텍스트 기능 구현 가능 

- 폰트 또한 변경 가능

반응형

'Java' 카테고리의 다른 글

250213_자바 FileIOStream 클래스들  (0) 2025.02.13
250212_자바 람다식, 스트림, 예외처리  (1) 2025.02.12
250211_Java 중첩 클래스  (0) 2025.02.11