/*
 * Copyright (c) 2024. Elex. All Rights Reesrved.
 * https://www.elex-project.com/
 */

package com.elex_project.examples.components.combobox;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ComboBoxRendererExample extends JPanel {
	public enum Item {
		A, B, C, D;
	}

	public static class MyRenderer extends JPanel implements ListCellRenderer<Item> {
		private JLabel label;

		MyRenderer() {
			super(new FlowLayout());
			label = new JLabel();
			setOpaque(true);

			add(label);
		}

		@Override
		public Component getListCellRendererComponent(JList<? extends Item> jList, Item item, int index,
		                                              boolean isSelected, boolean hasFocus) {

			// 선택된 항목의 색상을 변경해주고,
			if (isSelected) {
				setBackground(jList.getSelectionBackground());
				setForeground(jList.getSelectionForeground());
			} else {
				setBackground(jList.getBackground());
				setForeground(jList.getForeground());
			}
			// 선택된 항목의 값을 할당해 준다.
			label.setText(item.name());
			return this;
		}
	}

	public ComboBoxRendererExample() {
		super(new FlowLayout());

		final JComboBox<Item> comboBox = new JComboBox<>(Item.values());
		comboBox.setRenderer(new MyRenderer());
		comboBox.setMaximumRowCount(3);

		// 액션 리스너를 통해서 이벤트를 받는다.
		comboBox.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				JComboBox<Item> component = (JComboBox<Item>) actionEvent.getSource();
				Item selectedItem = (Item) component.getSelectedItem();
				System.out.println(selectedItem);
			}
		});

		// 레이아웃에 추가
		add(comboBox);

	}

	public static void main(String... args) {

		final JFrame jFrame = new JFrame();
		jFrame.setTitle("Example");
		jFrame.setSize(800, 600);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.setContentPane(new ComboBoxRendererExample());

		SwingUtilities.invokeLater(() -> {
			jFrame.setVisible(true);
		});


	}

	class DummyIcon implements Icon {

		@Override
		public void paintIcon(Component component, Graphics graphics, int x, int y) {
			graphics.setColor(Color.DARK_GRAY);
			graphics.fillRect(x, y, x + getIconWidth(), y + getIconHeight());
		}

		@Override
		public int getIconWidth() {
			return 16;
		}

		@Override
		public int getIconHeight() {
			return 16;
		}
	}
}
