본문 바로가기
공부/아키텍처기반 응용소프트웨어 개발전문가 과정

swing [ 버튼으로 사진 변경하기 ]

by 자피킨치 2018. 3. 29.

버튼을 눌러 사진을 변경하는 프로그램 작성



    package five;

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

public class Main extends JFrame {
	Container contentPane;
	JLabel imageLabel;
	ImageIcon img0;
	ImageIcon img1;
	ImageIcon img2;

	public Main() {
		setTitle("Image Change");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());

		img0 = new ImageIcon("images/family.png");
		img1 = new ImageIcon("images/bart.png");
		img2 = new ImageIcon("images/risa.png");

		imageLabel = new JLabel(img0);
		contentPane.add(imageLabel, BorderLayout.CENTER);
		contentPane.add(new MenuPanel(), BorderLayout.SOUTH);

		setSize(300, 400);
		setVisible(true);
	}

	class MenuPanel extends JPanel {
		public MenuPanel() {

			JButton btn1 = new JButton("bart");
			JButton btn2 = new JButton("risa");

			add(btn1);
			add(btn2);

			btn1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					imageLabel.setIcon(img1);
				}
			});

			btn2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					imageLabel.setIcon(img2);
				}
			});
		}
	}

	public static void main(String[] args) {
		new Main();
	}
}

댓글0