본문 바로가기
JAVA

JTextField와 JButton으로 간단한 로그인 창 구현하기

by 소힌 2022. 1. 3.

1. 로그인 정보 (id와 pw) 를 담고

입력받은 두개의 문자열과 비교하여 boolean 값을 돌려받는  메소드가 있는  memberRepository 클래스

 

2. 아이디와 비밀번호를 입력을 받아 로그인하는 창을 만들 MyFrame 클래스 

 

3. Myframe을 인스턴스화하여 보여지게 할 Main 클래스 

 

 

 

1. memberRepository 클래스  

package review;

import java.util.HashMap;
import java.util.Map;

public class MemberRepository {
	private Map<String, String> repo;

	public MemberRepository() {
		repo = new HashMap<>();
		repo.put("qwerty", "12345");
		repo.put("asdfg", "246810");

	}

	public boolean checkMember(String id, String PassWord) {
		if (!repo.containsKey(id)) {
			return false;
		}
		String insertedPassword = repo.get(id);
		return repo.containsValue(insertedPassword);
	}
}

 

2. MyFrame 클래스 + Main 클래스 

 

package review;

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;
import javax.swing.JTextField;

class MyFrame extends JFrame {

	JLabel resultment;

	public MyFrame() {
		super("로그인,초기화하기");
		setSize(600, 600);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		JPanel j = new JPanel();
		JLabel id = new JLabel("아이디");
		JTextField tfId = new JTextField(10);
		JLabel pw = new JLabel("비밀번호");
		JTextField tfPw = new JPasswordField(10);
		JButton login = new JButton("로그인");
		JButton reset = new JButton("초기화");

		MemberRepository repo = new MemberRepository();



// 로그인 버튼을 누른 경우에 사용할 ActionListener 
		ActionListener li = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String id = tfId.getText();
				String pw = tfPw.getText();
				boolean result = repo.checkMember(id, pw);
				resultment.setText(result ? "성공" : "실패");
			}

		};
//초기화 버튼을 누른 경우 사용할 ActionListener 
		ActionListener li2 = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				tfId.setText("");
				tfPw.setText("");

			}
		};

		login.addActionListener(li);
		reset.addActionListener(li2);

		j.add(id);
		j.add(tfId);
		j.add(pw);
		j.add(tfPw);
		j.add(login);
		j.add(reset);

		JPanel jS = new JPanel();
		resultment = new JLabel("");
		jS.add(resultment);

		add(jS, "South");
		add(j);
	}
}

public class LoginPractice {
	public static void main(String[] args) {
		MyFrame frame = new MyFrame();
		frame.setVisible(true);
	}
}