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

package com.elex_project.examples.components.button;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;

public class ToggleButtonExample extends JPanel {
	public ToggleButtonExample() {
		super(new FlowLayout());

		final JToggleButton button1 = new JToggleButton("Button 1");
		button1.setMnemonic(KeyEvent.VK_A);
		button1.setSelected(true);

		final JToggleButton button2 = new JToggleButton("Button 2");
		button2.setMnemonic(KeyEvent.VK_B);

		// 레이아웃에 추가한다.
		add(button1);
		add(button2);

		// 아이템 리스너를 통해서 이벤트를 받는다.
		final ItemListener itemListener = new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent itemEvent) {
				ItemSelectable source = itemEvent.getItemSelectable();
				if(source==button1){
					System.out.println(button1.getText() + " is "
							+ (button1.isSelected()?"selected.":"not selected."));
				} else if (source==button2) {
					System.out.println(button2.getText() + " is "
							+ (button2.isSelected()?"selected.":"not selected."));
				}
			}
		};
		button1.addItemListener(itemListener);
		button2.addItemListener(itemListener);
	}

	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 ToggleButtonExample());

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


	}

}
