mojo's Blog

명품 JAVA Programming 제 11장 Open Challenge 본문

Java

명품 JAVA Programming 제 11장 Open Challenge

_mojo_ 2021. 7. 29. 11:21

이미지 갤러리 만들기 코드

import javax.swing.*; // JFrame
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import java.awt.*; // Container
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Vector;
import java.awt.*;

class CenterPanel extends JPanel{
	
	private ImageIcon []images= {
			new ImageIcon("C:\\Temp/apple.jpg"),
			new ImageIcon("C:\\Temp/bear.jpg"),
			new ImageIcon("C:\\Temp/cherry.png")
	};
	private static Vector<ImageIcon> v=new Vector<ImageIcon>();
	private static JLabel jl;
	private static int idx=0;
	
	CenterPanel(){
		setLayout(new FlowLayout(FlowLayout.CENTER));
		
		for(int i=0;i<images.length;i++) {
			v.add(images[i]);
		}
		
		jl=new JLabel(v.get(0));
		add(jl);
	}
	
	static void change_Left() {
		idx = idx-1 < 0 ? v.size() - 1 : idx - 1;
		jl.setIcon(v.get(idx));
	}
	
	static void change_Right() {
		idx = idx+1 == v.size() ? 0 : idx + 1;
		jl.setIcon(v.get(idx));
	}
}

class SouthPanel extends JPanel{
	
	private JButton []jbtn=new JButton[2];
	
	SouthPanel(){
		setLayout(new FlowLayout(FlowLayout.CENTER));
		setBackground(Color.GRAY);
		
		jbtn[0]=new JButton(new ImageIcon("C:\\Temp/left.png"));
		jbtn[1]=new JButton(new ImageIcon("C:\\Temp/right.png"));
		
		add(jbtn[0]);
		add(jbtn[1]);
		
		jbtn[0].addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				CenterPanel.change_Left();
			}
		});
		
		jbtn[1].addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				CenterPanel.change_Right();
			}
		});
	}
}

public class MyFrame extends JFrame{
	
	MyFrame(){
		setTitle("11장 Open Challenge");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(new BorderLayout());
	
		c.add(new CenterPanel(),BorderLayout.CENTER);
		c.add(new SouthPanel(),BorderLayout.SOUTH);
		
		setSize(300, 300); // 프레임 크기 300x300
		setVisible(true); // 프레임 출력
		
		c.setFocusable(true);
		c.requestFocus();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new MyFrame();
	}

}
Comments