Chillax in dev

[java] swing 으로 간단한 응용프로그램을 만들어보자 본문

Java 공부/Java

[java] swing 으로 간단한 응용프로그램을 만들어보자

Seong Story 2020. 12. 29. 16:00
728x90

[java] swing 으로 간단한 응용프로그램을 만들어보자

- 자바 프로그래밍은 어떤 코딩을 해도 공부하다 보면 딱딱한 콘솔 창만 보게 된다. 이번엔 자바로 응용프로그램을 만들 수 있는 방법이 있어 배워보고자 한다. 이를 swing이라고 하는데 JFrame 클래스를 통해 응용프로그램을 실행하고 프레임과 페널을 이용해 응용프로그램을 구성하는 방식으로 매우 재미있다.

 

1. 계산기 응용프로그램 만들기 

기본적인 예제이다. 윈도우 환경에서 사용하던 계산기를 떠올리며 계산기를 만들어보자 아래 코드를 공유하니 참고해도 됩니다.

더보기
package days14;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

class Calculator extends JFrame implements ActionListener {
	JTextField jt;
	int num1=0;
	int num2=0;
	
	int op=0;
	
	
	Calculator() {
		
		
		// 컨테이너의 레이아웃 : 5행 1열의 GridLayout
		// 1행에는 panel p1 배치 -> p1에는 FlowLayout 으로 TextField 한개 배치
		// 2행에는 panel p2 배치 -> p2에는 GridLayout 으로 버튼 4개(7 8 9 +)
		// 3행에는 panel p3 배치 -> p3에는 GridLayout 으로 버튼 4개(4 5 6 -)
		// 4행에는 panel p4 배치 -> p4에는 GridLayout 으로 버튼 4개(1 2 3 x)
		// 5행에는 panel p5 배치 -> p5에는 GridLayout 으로 버튼 4개(C 0 = ÷)

		Container con = getContentPane();
		con.setLayout(new GridLayout(6, 1));//5행1열 텍스트 + 숫자 덩이 4개

		JPanel p1 = new JPanel();
		p1.setLayout(new FlowLayout(FlowLayout.CENTER));
		jt = new JTextField(16);
		p1.add(jt);
		con.add(p1);
		
		//폰트 
		Font f = new Font("나눔고딕",Font.BOLD,25);
		jt.setFont(f);
		jt.setText("0");
		jt.setHorizontalAlignment(SwingConstants.RIGHT);//오른정렬
		jt.setEditable(false);//마우스,키보드 편집 할수없음 설정
		
	
		
		JPanel p2 = new JPanel();
		p2.setLayout(new GridLayout(1, 4));
		JButton b7 = new JButton("7");
		p2.add(b7);
		JButton b8 = new JButton("8");
		p2.add(b8);
		JButton b9 = new JButton("9");
		p2.add(b9);
		JButton b11 = new JButton("+");
		p2.add(b11);
		con.add(p2);
		
		JPanel p3 = new JPanel();
		p3.setLayout(new GridLayout(1, 4));
		JButton b4 = new JButton("4");
		p3.add(b4);
		JButton b5 = new JButton("5");
		p3.add(b5);
		JButton b6 = new JButton("6");
		p3.add(b6);
		JButton b12 = new JButton("-");
		p3.add(b12);
		con.add(p3);
		
		JPanel p4 = new JPanel();
		p4.setLayout(new GridLayout(1, 4));
		JButton b1 = new JButton("1");
		p4.add(b1);
		JButton b2 = new JButton("2");
		p4.add(b2);
		JButton b3 = new JButton("3");
		p4.add(b3);
		JButton b13 = new JButton("x");
		p4.add(b13);
		con.add(p4);
		
		JPanel p5 = new JPanel();
		p5.setLayout(new GridLayout(1, 4));
		JButton b15 = new JButton("C");
		p5.add(b15);
		JButton b0 = new JButton("0");
		p5.add(b0);
		JButton b16 = new JButton("=");
		p5.add(b16);
		JButton b14 = new JButton("÷");
		p5.add(b14);
		con.add(p5);
		
		JPanel p6 = new JPanel();
		p6.setLayout(new GridLayout(1,4));
		JButton b17 = new JButton("<-");
		p6.add(b17);
		con.add(p6);
		
		
		JButton b18 = new JButton("1/x");
		b18.addActionListener(this);
		p6.add(b18);
		b18.setFont(f);
		
		JButton b19 = new JButton("Sqr");
		b19.addActionListener(this);
		p6.add(b19);
		b19.setFont(f);

		JButton b20 = new JButton("%");
		b20.addActionListener(this);
		p6.add(b20);
		b20.setFont(f);

		setTitle("계산기 실습");
		setSize(500, 500);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);

		 //버튼 폰트적용
			b1.setFont(f);
			b2.setFont(f);
			b3.setFont(f);
			b4.setFont(f);
			b5.setFont(f);
			b6.setFont(f);
			b7.setFont(f);
			b8.setFont(f);
			b9.setFont(f);
			b0.setFont(f);
			b11.setFont(f);
			b12.setFont(f);
			b13.setFont(f);
			b14.setFont(f);
			b15.setFont(f);
			b16.setFont(f);
			b17.setFont(f);
			//버튼 호출 
			b1.addActionListener(this);
			b2.addActionListener(this);
			b3.addActionListener(this);
			b4.addActionListener(this);
			b5.addActionListener(this);
			b6.addActionListener(this);
			b7.addActionListener(this);
			b8.addActionListener(this);
			b9.addActionListener(this);
			b0.addActionListener(this);
			b11.addActionListener(this);
			b12.addActionListener(this);
			b13.addActionListener(this);
			b14.addActionListener(this);
			b15.addActionListener(this);
			b16.addActionListener(this);
			b17.addActionListener(this);
			
			
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String s =e.getActionCommand();
		switch(s) {
		case"0":case"1":case"2":case"3":
		case"4":case"5":case"6":
		case"7":case"8":case"9":
			if(jt.getText().equals("0")) {jt.setText("");}
			jt.setText(jt.getText() +s);
			break;
		case "C":
			jt.setText("0"); break;
		case "+":
			num1 = Integer.parseInt(jt.getText());
			jt.setText("0");
			op = 1;
			break;
		case "-":
			num1 = Integer.parseInt(jt.getText());
			jt.setText("0");
			op = 2;
			break;
		case "x":
			num1 = Integer.parseInt(jt.getText());
			jt.setText("0");
			op = 3;
			break;
		case "÷":
			num1 = Integer.parseInt(jt.getText());
			jt.setText("0");
			op = 4;
			break;
		case "1/x":
			num1 = Integer.parseInt(jt.getText());
			jt.setText("0");
			op = 5;
			break;
		case "Sqr":
			num1 = Integer.parseInt(jt.getText());
			jt.setText("0");
			op = 6;
			break;
		case "%":
			num1 = Integer.parseInt(jt.getText());
			jt.setText("0");
			op = 7;
			break;
		case "=":
			int result =0;
			double resultd=0.0;
			num2=Integer.parseInt(jt.getText());
			switch(op) {
			case 1:result=num1 + num2; break;
			case 2:result=num1 - num2;break;
			case 3:result=num1 * num2; break;
			case 4:resultd=num1 / (double)num2; break;
			case 5: resultd =1/(double)Integer.parseInt(jt.getText());
            jt.setText(String.valueOf(resultd));
            break;
			case 6: resultd = Math.sqrt(Integer.parseInt(jt.getText()));jt.setText(String.valueOf(resultd));break;
			case 7:resultd=num1 %(double) num2; break;
			}
			if(result !=0)jt.setText(String.valueOf(result));
			else jt.setText(String.valueOf(resultd));
			break;
		case "<-":
			if(jt.getText().length() ==1) jt.setText("0");
			else {
				String t = jt.getText();
				jt.setText(t.substring(0,t.length()-1));
			}
			break;
			
		}
	}
}

public class Swing_12 {
	public static void main(String[] args) {
		new Calculator();

	}
}

 

2. 회원가입 응용프로그램으로 만들기

 간단하게 정보를 입력받고 이를 콘솔로 보내 확인하는 간단한 응용프로그램을 만들어보자

더보기
package days14;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

class Resume extends JFrame implements ActionListener {
	JTextField jt_name;
	JRadioButton jr1;
	JRadioButton jr2;
	JCheckBox jc1;
	JCheckBox jc2;
	JCheckBox jc3;
	JCheckBox jc4;
	JComboBox<String> jcb;
	JTextField jt_phone2;
	JTextField jt_phone3;
	JComboBox<String> jcb2;

	Resume() {
		Container con = getContentPane(); // 메인 컨테이너
		con.setLayout(new BorderLayout());
		JPanel jp1 = new JPanel(); // 메인 컨테이너에 올라갈 패널1
		JPanel jp2 = new JPanel(); // 메인 컨테이너에 올라갈 패널2
		jp1.setLayout(new GridLayout(6, 1));
		jp2.setLayout(new GridLayout(6, 1));
		jp1.add(new JLabel("  성        명  : "));
		jp1.add(new JLabel("  성        별  : "));
		jp1.add(new JLabel("  취        미  : "));
		jp1.add(new JLabel("  전화번호  : "));
		jp1.add(new JLabel("  거주지역  : "));

		JPanel jp21 = new JPanel();
		JPanel jp22 = new JPanel();
		JPanel jp23 = new JPanel();
		JPanel jp24 = new JPanel();
		JPanel jp25 = new JPanel();
		JPanel jp26 = new JPanel();

		jp21.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
		jp22.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
		jp23.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
		jp24.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
		jp25.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
		jp26.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));

		jt_name = new JTextField(10);
		jp21.add(jt_name);

		jr1 = new JRadioButton("남성");
		jr2 = new JRadioButton("여성");
		ButtonGroup bg1 = new ButtonGroup();
		bg1.add(jr1);
		bg1.add(jr2);
		jp22.add(jr1);
		jp22.add(jr2);

		jc1 = new JCheckBox("스포츠");
		jc2 = new JCheckBox("영화");
		jc3 = new JCheckBox("독서");
		jc4 = new JCheckBox("기타");
		jp23.add(jc1);
		jp23.add(jc2);
		jp23.add(jc3);
		jp23.add(jc4);

		jcb = new JComboBox<String>();
		jcb.addItem("010");
		jcb.addItem("011");
		jcb.addItem("02");
		jcb.addItem("032");
		jcb.addItem("031");

		jt_phone2 = new JTextField(10);
		jt_phone3 = new JTextField(10);

		jp24.add(jcb);
		jp24.add(new JLabel("-"));
		jp24.add(jt_phone2);
		jp24.add(new JLabel("-"));
		jp24.add(jt_phone3);

		jcb2 = new JComboBox<String>();
		jcb2.addItem("서울");
		jcb2.addItem("경기도");
		jcb2.addItem("강원도");
		jcb2.addItem("충청도");
		jcb2.addItem("경상도");
		jcb2.addItem("전라도");
		jcb2.addItem("제주도");
		jp25.add(jcb2);

		JButton jb = new JButton("확인");
		jp26.add(jb);

		jb.addActionListener(this);

		jp2.add(jp21);
		jp2.add(jp22);
		jp2.add(jp23);
		jp2.add(jp24);
		jp2.add(jp25);
		jp2.add(jp26);

		con.add(jp1, BorderLayout.WEST);
		con.add(jp2, BorderLayout.CENTER);
		setTitle("구성  실습");
		setSize(500, 300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String s;
		System.out.println("성 명 : " + jt_name.getText());

		if (jr1.isSelected())
			s = "남성";
		else
			s = "여성";
		System.out.println("성 별 : " + s);

		s = "";
		if (jc1.isSelected())
			s = s + jc1.getText() + "  ";
		if (jc2.isSelected())
			s = s + jc2.getText() + "  ";
		if (jc3.isSelected())
			s = s + jc3.getText() + "  ";
		if (jc4.isSelected())
			s = s + jc4.getText() + "  ";
		System.out.println("취 미 : " + s);

		s = (String) jcb.getSelectedItem();
		s = s + "-" + jt_phone2.getText();
		s = s + "-" + jt_phone3.getText();

		System.out.println("전화번호 : " + s);
		System.out.println("거주지역 : " + jcb2.getSelectedItem());

	}

}

public class Swing_17 {

	public static void main(String[] args) {
		new Resume();

	}

}

3.  달력 만들어보기

역시 윈도우에서 쉽게 볼 수 있는 달력을 직접 만들어봤다 윤년도 구별해야 하고 달력의 일수도 적절히 위치하도록 하면 좋겠다. 난이도가 제일 높았던 것 같다

더보기
package days14;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

class Calendars extends JFrame implements ActionListener {
	JTextField y;
	JComboBox<String> m;
	static int year = 0;
	static int month = 0;
	static JTextField[] jt = new JTextField[42];

	Calendars() {
		Container con = getContentPane();
		con.setLayout(new BorderLayout());

		JPanel jp1 = new JPanel();
		JPanel jp2 = new JPanel();
		JPanel jp3 = new JPanel();

		jp1.setLayout(new GridLayout(1, 7));
		jp2.setLayout(new GridLayout(6, 7));
		jp3.setLayout(new FlowLayout());

		jp1.add(new JButton("일")).setForeground(Color.RED);
		jp1.add(new JButton("월"));
		jp1.add(new JButton("화"));
		jp1.add(new JButton("수"));
		jp1.add(new JButton("목"));
		jp1.add(new JButton("금"));
		jp1.add(new JButton("토")).setForeground(Color.BLUE);

		Font f = new Font("굴림", Font.BOLD, 20);
		for (int i = 0; i < jt.length; i++) {
			jt[i] = new JTextField();
			jt[i].setFont(f);
			jt[i].setHorizontalAlignment(SwingConstants.RIGHT);
			jt[i].setEditable(false);
			jt[i].setBackground(Color.white);
			jp2.add(jt[i]);
			if (i % 7 == 6)
				jt[i].setForeground(Color.BLUE);
			else if (i % 7 == 0)
				jt[i].setForeground(Color.RED);
			else
				jt[i].setForeground(Color.BLACK);
		}
		y = new JTextField(8);
		y.setFont(f);
		y.setHorizontalAlignment(SwingConstants.CENTER);

		Calendar today = Calendar.getInstance();
		y.setText(String.valueOf(today.get(Calendar.YEAR)));
		m = new JComboBox<String>();
		for (int i = 1; i <= 12; i++)
			m.addItem(String.valueOf(i));
		m.setSelectedIndex(today.get(Calendar.MONTH));
		m.setFont(f);

		con.add(jp1, BorderLayout.NORTH);
		con.add(jp2, BorderLayout.CENTER);
		con.add(jp3, BorderLayout.SOUTH);

		JButton b = new JButton("확인");
		JButton b1 = new JButton("이전달");
		JButton b2 = new JButton("다음달");

		b.addActionListener(this);
		b1.addActionListener(this);
		b2.addActionListener(this);

		jp3.add(b1);
		jp3.add(y);
		jp3.add(new JLabel("년 "));
		jp3.add(m);
		jp3.add(new JLabel("월 "));
		jp3.add(b);
		jp3.add(b2);

		setTitle("스윙 캘린더");
		setSize(500, 500);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);

		year = Integer.parseInt(y.getText());
		month = Integer.parseInt((String) m.getSelectedItem());
		drawCalendar();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String s = e.getActionCommand();
		Calendar temp = Calendar.getInstance();
		temp.set(year, month - 1, 1);
		switch (s) {
		case "확인":
			year = Integer.parseInt(y.getText());
			month = Integer.parseInt((String) m.getSelectedItem());
			break;
		case "이전달":
			temp.add(Calendar.MONTH, -1); // 이전달 계산
			year = temp.get(Calendar.YEAR); // 년도 추출
			month = temp.get(Calendar.MONTH) + 1; // 월 추출
			y.setText(String.valueOf(year)); // 텍스트 상자에 이전달 년도 세트
			m.setSelectedIndex(month - 1); // 콤보상자에 이전달 월 세트
			break;
		case "다음달":
			temp.add(Calendar.MONTH, 1);
			year = temp.get(Calendar.YEAR);
			month = temp.get(Calendar.MONTH) + 1;
			y.setText(String.valueOf(year));
			m.setSelectedIndex(month - 1);
			break;
		}
		for (int i = 0; i < jt.length; i++)
			jt[i].setText("");
		drawCalendar();
	}

	public static void drawCalendar() {
		Calendar sDay = Calendar.getInstance();
		Calendar eDay = Calendar.getInstance();
		sDay.set(year, month - 1, 1);
		eDay.set(year, month, 1);
		eDay.add(Calendar.DATE, -1);
		int START_WEEK = sDay.get(Calendar.DAY_OF_WEEK);
		int END_WEEK = eDay.get(Calendar.DAY_OF_WEEK);
		sDay.add(Calendar.DATE, -1 * (START_WEEK - 1)); // 전달 날짜로
		eDay.add(Calendar.DATE, 7 - END_WEEK); // 다음달 날짜로
		for (int i = 0; sDay.before(eDay) || sDay.equals(eDay); sDay.add(Calendar.DATE, 1)) {
			int day = sDay.get(Calendar.DATE);
			jt[i].setText(String.valueOf(day));
			i++;
		}
	}
}

public class Swing_Calendar {
	public static void main(String[] args) {
		new Calendars();
	}
}
728x90
LIST
Comments