- 자바 스윙을 이용한 중고 상품 거래 시스템 만들기 -

 

 

Domain

Order.java

package domain;

public class Order {
	
	/*
	 * Field
	 */
	private int orderId;
	private int buyerId;
	private int saleId;
	private int orderPrice;
	private int orderQuantity;


	/*
	 * Method
	 */
	
	public int getOrderId() {
		return orderId;
	}
	public void setOrderId(int orderId) {
		this.orderId = orderId;
	}
	public int getBuyerId() {
		return buyerId;
	}
	public void setBuyerId(int buyerId) {
		this.buyerId = buyerId;
	}
	public int getSaleId() {
		return saleId;
	}
	public void setSaleId(int saleId) {
		this.saleId = saleId;
	}
	public int getOrderPrice() {
		return orderPrice;
	}
	public void setOrderPrice(int orderPrice) {
		this.orderPrice = orderPrice;
	}
	public int getOrderQuantity() {
		return orderQuantity;
	}
	public void setOrderQuantity(int orderQuantity) {
		this.orderQuantity = orderQuantity;
	}
	@Override
	public String toString() {
		return "Order [orderId=" + orderId + ", buyerId=" + buyerId + ", saleId=" + saleId + ", orderPrice="
				+ orderPrice + ", orderQuantity=" + orderQuantity + "]";
	}
	
}

 

Message.java

package domain;

import java.sql.Date;

public class Message {
	
	/*
	 * Field
	 */
	private int messageId;
	private int senderId;
	private int receiverId;
	private String content;
	private Date sendDate;
	private int productId;
	
	

	/*
	 * Method
	 */
	public int getMessageId() {
		return messageId;
	}
	public void setMessageId(int messageId) {
		this.messageId = messageId;
	}
	public int getSenderId() {
		return senderId;
	}
	public void setSenderId(int senderId) {
		this.senderId = senderId;
	}
	public int getReceiverId() {
		return receiverId;
	}
	public void setReceiverId(int receiverId) {
		this.receiverId = receiverId;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getSendDate() {
		return sendDate;
	}
	public void setSendDate(Date sendDate) {
		this.sendDate = sendDate;
	}
	public int getProductId() {
		return productId;
	}
	public void setProductId(int productId) {
		this.productId = productId;
	}
	@Override
	public String toString() {
		return "Message [messageId=" + messageId + ", senderId=" + senderId + ", receiverId=" + receiverId
				+ ", content=" + content + ", sendDate=" + sendDate + "]";
	}
}

 

Repository

JdbcOrderRepository.java

package repository.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import domain.MyTrade;
import domain.Order;
import domain.TopInfo;
import repository.inerface.OrderRepository;

public class JdbcOrderRepository extends DAO implements OrderRepository {

	/*
	 * Field
	 */
	// 싱글톤
	private static OrderRepository orderRepository = null;

	
	/*
	 * Constructor
	 */
	// 싱글톤
	private JdbcOrderRepository() {
	}

	
	/*
	 * Method
	 */
	// 싱글톤 -> 메서드로 인스턴스 생성
	public static OrderRepository getOrderRepository() {
		if (orderRepository == null) {
			orderRepository = new JdbcOrderRepository();
		}
		return orderRepository;
	}

	@Override
	public void insert(Order order) {
		try {
			connect();

			String sql = "INSERT INTO orders VALUES (orders_seq.nextval ,?, ?, ?, ?)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, order.getBuyerId());
			ps.setInt(2, order.getSaleId());
			ps.setInt(3, order.getOrderQuantity());
			ps.setInt(4, order.getOrderPrice());

			int result = ps.executeUpdate();

			if (result > 0) {
				System.out.println(result + "행 삽입에 성공했습니다.");
			} else {
				System.out.println("삽입에 실패했습니다.");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
	}

	@Override
	public void update(Order order) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(int orderId) {
		try {
			connect();

			String sql = "DELETE FROM orders WHERE order_id = ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, orderId);

			int result = ps.executeUpdate();

			if (result > 0) {
				System.out.println(result + "행 삭제에 성공했습니다.");
			} else {
				System.out.println("삭제에 실패했습니다.");
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
	}

	@Override
	public Order selectOne(int orderId) {
		Order order = null;

		try {
			connect();

			String sql = "SELECT * FROM orders WHERE order_id = ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, orderId);

			rs = ps.executeQuery();

			if (rs.next()) {
				order = new Order();
				order.setOrderId(rs.getInt(1));
				order.setBuyerId(rs.getInt(2));
				order.setSaleId(rs.getInt(3));
				order.setOrderQuantity(rs.getInt(4));
				order.setOrderPrice(rs.getInt(5));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
		return order;
	}

	@Override
	public List<Order> selectAll() {
		List<Order> list = new ArrayList<Order>();

		try {
			connect();

			String sql = "SELECT * FROM orders";
			ps = conn.prepareStatement(sql);

			rs = ps.executeQuery();

			while (rs.next()) {
				Order order = new Order();
				order.setOrderId(rs.getInt(1));
				order.setBuyerId(rs.getInt(2));
				order.setSaleId(rs.getInt(3));
				order.setOrderQuantity(rs.getInt(4));
				order.setOrderPrice(rs.getInt(5));

				list.add(order);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
		return list;
	}

	// 내 구매내역
	@Override
	public List<MyTrade> selectMyOrders(int buyerId) {
		List<MyTrade> list = new ArrayList<MyTrade>();

		try {
			connect();

			String sql = "SELECT o.order_id, s.seller_id, m.identification, p.name, o.order_quantity, o.order_price "
						+ "FROM orders o " 
						+ "JOIN sales s ON (o.sale_id = s.sale_id) "
						+ "JOIN products p ON (s.product_id = p.product_id) "
						+ "JOIN members m ON (s.seller_id = m.member_id) " 
						+ "WHERE o.buyer_id = ? "
						+ "ORDER BY o.order_id DESC";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, buyerId);

			rs = ps.executeQuery();

			while (rs.next()) {
				MyTrade myTrade = new MyTrade();

				myTrade.setOrderId(rs.getInt(1));
				myTrade.setSellerId(rs.getInt(2));
				myTrade.setIdentification(rs.getString(3));
				myTrade.setProductName(rs.getString(4));
				myTrade.setOrderQuatity(rs.getInt(5));
				myTrade.setOrderPrice(rs.getInt(6));

				list.add(myTrade);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
		return list;
	}

	// 내 판매내역 - 주문이 이루어져야 판매가 등록이 되어서 주문 리포지토리에 있는 것임
	@Override
	public List<MyTrade> selectMySales(int sellerId) {
		List<MyTrade> list = new ArrayList<MyTrade>();

		try {
			connect();

			String sql = "SELECT s.sale_id, o.buyer_id, m.identification, p.name, o.order_quantity, o.order_price "
						+ "FROM orders o "
						+ "JOIN sales s ON (o.sale_id = s.sale_id) " 
						+ "JOIN products p ON (s.product_id = p.product_id) "
						+ "JOIN members m ON (o.buyer_id = m.member_id) " 
						+ "WHERE s.seller_id = ? "
						+ "ORDER BY s.sale_id DESC";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, sellerId);

			rs = ps.executeQuery();

			while (rs.next()) {
				MyTrade myTrade = new MyTrade();

				myTrade.setSaleId(rs.getInt(1));
				myTrade.setBuyerId(rs.getInt(2));
				myTrade.setIdentification(rs.getString(3));
				myTrade.setProductName(rs.getString(4));
				myTrade.setOrderQuatity(rs.getInt(5));
				myTrade.setOrderPrice(rs.getInt(6));

				list.add(myTrade);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
		return list;
	}

	// 구매왕
	@Override
	public List<TopInfo> topBuyer() {
		List<TopInfo> list = new ArrayList<TopInfo>();
		try {
			connect();

			String sql = "SELECT m.identification, o.구매빈도수 " 
						+ "FROM members m "
						+ "JOIN (SELECT buyer_id, count(*) AS 구매빈도수 FROM orders GROUP BY buyer_id) o "
						+ "ON (m.member_id = o.buyer_id)";
			ps = conn.prepareStatement(sql);

			rs = ps.executeQuery();
			while (rs.next()) {
				TopInfo topInfo = new TopInfo();
				
				topInfo.setIdentification(rs.getString(1));
				topInfo.setSaleOrBuyCnt(rs.getInt(2));
				
				list.add(topInfo);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
		return list;
	}

	// 판매왕
	@Override
	public List<TopInfo> topSeller() {
		List<TopInfo> list = new ArrayList<TopInfo>();
		
		try {
			connect();

			String sql = "SELECT m.identification, k.판매빈도수 " 
						+ "FROM members m "
						+ "JOIN (SELECT s.seller_id, count(*) AS 판매빈도수 FROM orders o "
						+ "JOIN sales s ON (o.sale_id = s.sale_id) "
						+ "GROUP BY s.seller_id) k ON (k.seller_id = m.member_id)";
			ps = conn.prepareStatement(sql);

			rs = ps.executeQuery();
			while (rs.next()) {
				TopInfo topInfo = new TopInfo();
				
				topInfo.setIdentification(rs.getString(1));
				topInfo.setSaleOrBuyCnt(rs.getInt(2));
				
				list.add(topInfo);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
		return list;
	}
}

 

JdbcMessageRepository.java

package repository.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import domain.Message;
import domain.MessageInfo;
import repository.inerface.MessageRepository;

public class JdbcMessageRepository extends DAO implements MessageRepository {

	/*
	 * Field
	 */
	// 싱글톤
	private static MessageRepository messageRepository = null;

	/*
	 * Constructor
	 */
	// 싱글톤
	private JdbcMessageRepository() {
	}

	/*
	 * Method
	 */
	public static MessageRepository getMessageRepository() {
		if (messageRepository == null) {
			messageRepository = new JdbcMessageRepository();
		}
		return messageRepository;
	}

	@Override
	public void insert(Message message) {
		try {
			connect();

			String sql = "INSERT INTO messages VALUES (messages_seq.nextval, ?, ?, ?, sysdate, ?)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, message.getSenderId());
			ps.setInt(2, message.getReceiverId());
			ps.setString(3, message.getContent());
			ps.setInt(4, message.getProductId());

			int result = ps.executeUpdate();

			if (result > 0) {
				System.out.println(result + "행 삽입에 성공했습니다.");
			} else {
				System.out.println("삽입에 실패했습니다.");
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}

	}

	@Override
	public void update(Message message) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(int messageId) {
		try {
			connect();

			String sql = "DELETE FROM messages WHERE message_id = ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, messageId);

			int result = ps.executeUpdate();

			if (result > 0) {
				System.out.println(result + "행 삭제에 성공했습니다.");
			} else {
				System.out.println("삭제에 실패했습니다.");
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
	}

	@Override
	public Message selectOne(int messageId) {
		Message message = null;

		try {
			connect();

			String sql = "SELECT * FROM messages WHERE message_id = ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, messageId);

			rs = ps.executeQuery();

			if (rs.next()) {
				message = new Message();
				message.setMessageId(rs.getInt(1));
				message.setSenderId(rs.getInt(2));
				message.setReceiverId(rs.getInt(3));
				message.setContent(rs.getString(4));
				message.setSendDate(rs.getDate(5));
				message.setProductId(rs.getInt(6));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
		return message;
	}

	// 메세지 조회는 로그인멤버를 기준으로 자기 것만 조회
	@Override
	public List<MessageInfo> selectAllByReceiver(int receiver_id) {
		List<MessageInfo> list = new ArrayList<MessageInfo>();

		try {
			connect();

			String sql = "SELECT m.identification, t.content, p.name, t.send_date, t.sender_id, t.product_id, t.message_id "
						+ "FROM messages t "
						+ "JOIN members m ON (m.member_id = t.sender_id) "
						+ "JOIN products p ON (p.product_id = t.product_id)"
						+ "WHERE t.receiver_id = ?"
						+ "ORDER BY t.message_id DESC";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, receiver_id);

			rs = ps.executeQuery();

			while (rs.next()) {
				MessageInfo messageInfo = new MessageInfo();
				
				messageInfo.setSenderidentification(rs.getString(1));
				messageInfo.setContent(rs.getString(2));
				messageInfo.setProductName(rs.getString(3));
				messageInfo.setSendDate(rs.getDate(4));
				messageInfo.setSenderId(rs.getInt(5));
				messageInfo.setProductId(rs.getInt(6));
				messageInfo.setMessageId(rs.getInt(7));
				
				list.add(messageInfo);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			disconnect();
		}
		return list;
	}
}

 

Service

OrderService.java

package service;

import java.util.List;

import domain.MyTrade;
import domain.Order;
import domain.Product;
import domain.Sale;
import domain.TopInfo;
import repository.inerface.OrderRepository;
import repository.inerface.ProductRepository;
import repository.inerface.SaleRepository;
import repository.jdbc.JdbcProductRepository;
import repository.jdbc.JdbcSaleRepository;

public class OrderService {
	
	/*
	 * Field
	 */
	private final OrderRepository orderRepository;
	private SaleRepository saleRepository  = JdbcSaleRepository.getSaleRepository();
	private ProductRepository productRepository = JdbcProductRepository.getProductRepository();
	
	
	/*
	 * Constructor
	 */
	public OrderService(OrderRepository orderRepository) {
		this.orderRepository = orderRepository;
	}
	
	
	/*
	 * Method
	 */
	// 주문 생성
	public void createOrder(Order order) {
		orderRepository.insert(order);
		// 주문 생성 시점 --> 해당 상품의 수량 업데이트 (주문후 수량 = 상품수량 - 주문수량)
		// order -> sale -> product 으로 엔티티가 접근
		Sale sale = saleRepository.selectOne(order.getSaleId());
		Product product = productRepository.selectOne(sale.getProductId());
		// 주문 후 수량 계산 로직 - 엔티티에 비즈니스 로직으로 있음.
		product.removeQuantity(order.getOrderQuantity(), product);
		// 주문 후 수량으로 product tbl 업데이트
		productRepository.update(product.getProductId(), product.getQuantity());
	}
	
	// 주문 수정
	public void updateOrder(Order order) {
		orderRepository.update(order);
	}
	
	// 주문 삭제
	public void deleteOrder(int orderId) {
		orderRepository.delete(orderId);
	}
	
	// 주문 단건조회
	public Order findOneOrder(int orderId) {
		return orderRepository.selectOne(orderId);
	}
	
	// 주문 전체조회
	public List<Order> findAllOrders() {
		return orderRepository.selectAll();
	}
	
	// 내 구매내역 조회
	public List<MyTrade> findMyOrders(int buyerId) {
		return orderRepository.selectMyOrders(buyerId);
	}
	
	// 내 판매내역 조회
	public List<MyTrade> findMySales(int sellerId) {
		return orderRepository.selectMySales(sellerId);
	}

	// 구매왕
	public List<TopInfo> findTopBuyer() {
		return orderRepository.topBuyer();
	}

	// 구매왕
	public List<TopInfo> findTopSeller() {
		return orderRepository.topSeller();
	}
}

주문 생성 시점에서 주문이 등록된 상품의 수량을 수정하기 위한 로직이 들어가 있음

	// -- 비즈니스 로직 -- // 
	public void removeQuantity(int orderQuantity, Product product) {
		int restQuantity = product.getQuantity() - orderQuantity;
		
		if (restQuantity < 0) {
			throw new NotEnoughStockException("상품수량이 부족합니다.");
		}
		product.setQuantity(restQuantity);
	}

Product.java 엔티티의 비즈니스 로직으로 주문에 의한 상품수량 감소 로직

 

MessageService.java

package service;

import java.util.List;

import domain.Message;
import domain.MessageInfo;
import repository.inerface.MessageRepository;

public class MessageService {

	/*
	 * Field
	 */
	private final MessageRepository messageRepository;
	

	/*
	 * Constructor
	 */
	public MessageService(MessageRepository messageRepository) {
		this.messageRepository = messageRepository;
	}

	
	/*
	 * Method
	 */
	// 메세지 작성
	public void writeMessage(Message message) {
		messageRepository.insert(message);
	}
	
	// 메세지 수정
	public void modifyMessage(Message message) {
		messageRepository.update(message);
	}
	
	// 메세지 삭제
	public void deleteMessage(int messageId) {
		messageRepository.delete(messageId);
	}
	
	// 메세지 단건조회
	public Message findOneMessage(int messageId) {
		return messageRepository.selectOne(messageId);
	}
	
	// 메세지 전체조회
	public List<MessageInfo> findAllMessageByReceiver(int receiver_id) {
		return messageRepository.selectAllByReceiver(receiver_id);
	}
}

 

View

ShopFrame.java

	// 상품 버튼 생성
	private RoundedButton drawProductButton(String name, SaleInfo saleInfo, int numOfBtn) { //
		RoundedButton saleBtn = new RoundedButton(name);

		saleBtn.setFont(new Font("Arial", Font.BOLD, 18));
		saleBtn.setSize(100, 100);

		saleBtn.setLocation(saleBtn_X, saleBtn_Y);
		// 상품 버튼 그리드 형식으로 출력
		saleBtn_X += 130;
		if (saleBtn_X >= 650) {
			saleBtn_X = 15;
			saleBtn_Y += 130;
		}

		saleBtn.setBackground(Color.LIGHT_GRAY);

		// 상품 버튼 클리시 디테일창 팝업
		saleBtn.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				// 디테일창
				JFrame jf = new JFrame("Details");
				jf.setLayout(null);
				jf.setBounds(900, 120, 500, 700);
				jf.setVisible(true);

				// 상품 이미지 출력
				Icon icon = new ImageIcon(ShopFrame.class.getResource("").getPath() + "img/productImg/" + saleInfo.getProductImage());
				// 디폴트 이미지 설정 - 아이콘에 이미지를 담지 못하면 width 가 -1 이 나옴
				if (icon.getIconWidth() == -1) {
					icon = new ImageIcon(ShopFrame.class.getResource("").getPath() + "img/productImg/homeview.jpg");
				}

				JButton imgBtn = new JButton();
				imgBtn.setIcon(icon);
				imgBtn.setBounds(0, 0, 500, 300);
				jf.add(imgBtn);

				// 판매상품의 디테일정보 출력할 text area 생성
				TextArea textArea = new TextArea();
				textArea.setBounds(0, 300, 500, 300);
				textArea.setEditable(false); // 읽기 전용
				textArea.setText(saleInfo.toString()); // 판매상품 정보 쓰기
				jf.add(textArea);

				// 뒤로가기 버튼
				RoundedButton backBtn = new RoundedButton("BACK");
				backBtn.setBounds(300, 610, 60, 40);
				backBtn.setBackground(Color.pink);
				jf.add(backBtn);

				// 뒤로가기 버튼 클릭시 Details 창 끄기
				backBtn.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent e) {
						jf.dispose();
					}
				});

				// 메세지 버튼
				RoundedButton messageBtn = new RoundedButton("MSG");
				messageBtn.setBounds(25, 610, 60, 40);
				messageBtn.setBackground(Color.pink);
				jf.add(messageBtn);

				// 메세지 버튼 클릭시 메세지 입력 창 팝업
				messageBtn.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent e) {
						JFrame jf3 = new JFrame("MESSAGE");
						jf3.setLayout(null);
//						jf.setBackground(Color.BLACK);
						jf3.setBounds(900, 120, 500, 350);
						jf3.setVisible(true);

						String title = "Send a message to ' " + saleInfo.getIdentification() + " '";
						JLabel label = new JLabel(title);
						label.setBounds(10, 0, 400, 50);
						label.setFont(new Font("굴림", Font.BOLD, 16));
						jf3.add(label);

						JTextArea textCreateMessage = new JTextArea();
						textCreateMessage.setBounds(10, 70, 460, 225);
						textCreateMessage.setLineWrap(true); // 자동 줄바꿈
						jf3.add(textCreateMessage);

						// 뒤로가기 버튼
						RoundedButton backBtn = new RoundedButton("BACK");
						backBtn.setBounds(300, 10, 60, 40);
						backBtn.setBackground(Color.pink);
						jf3.add(backBtn);

						// 뒤로가기 버튼 클릭시 MESSAGE 창 끄기
						backBtn.addMouseListener(new MouseAdapter() {
							public void mouseClicked(MouseEvent e) {
								jf3.dispose();
							}
						});

						// 보내기 버튼
						RoundedButton sendBtn = new RoundedButton("SEND");
						sendBtn.setBounds(400, 10, 60, 40);
						sendBtn.setBackground(Color.pink);
						jf3.add(sendBtn);

						// 보내기 버튼 클릭시 message DB 저장
						sendBtn.addMouseListener(new MouseAdapter() {
							public void mouseClicked(MouseEvent e) {

								Message message = new Message();
								message.setSenderId(HomeFrame.logInMember.getMemberId());
								message.setReceiverId(saleInfo.getSellerId());
								message.setContent(textCreateMessage.getText());
								message.setProductId(saleInfo.getProduct_id());

//								System.out.println(message.toString());

								// 빈 메세지 예외처리
								if (textCreateMessage.getText().length() != 0) {
									messageService.writeMessage(message);
//									System.out.println("윈도우 - 메세지 전송 선공");
									JOptionPane.showMessageDialog(frame, "Sending message successful !",
											"Congratulations !", JOptionPane.INFORMATION_MESSAGE);
									jf3.dispose();
									jf.dispose();
									searchFrame.dispose();
								} else {
									JOptionPane.showMessageDialog(frame, "Please fill in the message.",
											"Sending message failed !", JOptionPane.INFORMATION_MESSAGE);
								}

							}
						});

					}
				});

				// 주문버튼
				RoundedButton orderBtn = new RoundedButton("ORDER");
				orderBtn.setBounds(400, 610, 60, 40);
				orderBtn.setBackground(Color.pink);
				jf.add(orderBtn);

				// 주문 버튼 클릭시 주문 입력 폼 팝업
				orderBtn.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent e) {

						// 주문 입력폼
						JFrame jf2 = new JFrame("ORDER");
						jf2.setLayout(null);
						jf2.setBackground(Color.BLACK);
						jf2.setBounds(900, 120, 500, 300);
						jf2.setVisible(true);

						// 구매상품 수량 입력
						JLabel lblNewLabel2_1 = new JLabel("QUANTITY");
						lblNewLabel2_1.setBounds(30, 100, 100, 80);
						lblNewLabel2_1.setFont(new Font("굴림", Font.BOLD, 16));
						jf2.add(lblNewLabel2_1);

						JTextField textCreateQuantity = new JTextField();
						textCreateQuantity.setBounds(180, 125, 231, 27);
						jf2.add(textCreateQuantity);
						textCreateQuantity.setColumns(10);

						// 구매상품 가격 출력
						JLabel lblNewLabel2_2 = new JLabel("TOTAL_PRICE");
						lblNewLabel2_2.setBounds(30, 149, 150, 80);
						lblNewLabel2_2.setFont(new Font("굴림", Font.BOLD, 16));
						jf2.add(lblNewLabel2_2);

						// 선택 수량에따라 가격표시
						textCreateTotalPrice = new JTextField();
						textCreateTotalPrice.setBounds(180, 173, 231, 27);
						textCreateTotalPrice.setEnabled(false); // 읽기전용
						jf2.add(textCreateTotalPrice);
						textCreateTotalPrice.setColumns(10);

						// 수량 입력 후 엔터 치면 total price 텍스트필드에 가격 출력
						textCreateQuantity.addActionListener(new ActionListener() {

							public void actionPerformed(ActionEvent e) {

								// 구매 수량 과 가격 계산 -> total 가격 텍스트필드에 뿌리기
								quantity = Integer.parseInt(textCreateQuantity.getText());
								totalPrice = saleInfo.getProductPrice() * quantity;
								textCreateTotalPrice.setText(Integer.toString(totalPrice));
								textCreateTotalPrice.setFont(new Font("굴림", Font.BOLD, 16));
							}
						});

						// 뒤로가기 버튼
						RoundedButton backBtn = new RoundedButton("BACK");
						backBtn.setBounds(300, 213, 60, 40);
						backBtn.setBackground(Color.pink);
						jf2.add(backBtn);

						// 뒤로가기 버튼 클릭시 Details 창 끄기
						backBtn.addMouseListener(new MouseAdapter() {
							public void mouseClicked(MouseEvent e) {
								jf2.dispose();
							}
						});

						// 구매 버튼
						RoundedButton buyBtn = new RoundedButton("BUY");
						buyBtn.setBounds(400, 213, 60, 40);
						buyBtn.setBackground(Color.pink);
						jf2.add(buyBtn);

						// 구매 버튼 클릭시 order DB 저장
						buyBtn.addMouseListener(new MouseAdapter() {
							public void mouseClicked(MouseEvent e) {

								// 주문수량 0개 or 미기입 예외처리
								if (quantity == 0 || textCreateQuantity.getText().length() == 0) {
									// 예외처리 팝업
									JOptionPane.showMessageDialog(frame, "Zero and empty must not exist.",
											"Order failed !", JOptionPane.INFORMATION_MESSAGE);
									return;
								}
								// (주문수량 > 상품재고) 인 경우 예외처리
								else if (quantity > saleInfo.getProductQuantity()) {
									JOptionPane.showMessageDialog(frame, "The product is out of stock.",
											"Order failed !", JOptionPane.INFORMATION_MESSAGE);
								} else {
									Order order = new Order();
									order.setBuyerId(HomeFrame.logInMember.getMemberId());
									order.setSaleId(saleInfo.getSaleId());
									order.setOrderQuantity(quantity);
									order.setOrderPrice(totalPrice);

									JOptionPane.showMessageDialog(frame, "Order successfully.", "Congratulation !",
											JOptionPane.INFORMATION_MESSAGE);
									orderService.createOrder(order);

									// 주문 완료 후 구매, 주문 창 다 닫기
									jf2.dispose();
									jf.dispose();
									searchFrame.dispose();

								}
							}
						});
					}
				});
			}
		});

		return saleBtn;
	}

 

실행 화면

 

 

 

- Just Do It -

 

반응형
복사했습니다!