유수봉 교수의 자바프로그램 15주차 스윙 컴포넌트 활용

// JLable을 이용한 레이블 만들기
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComponentEx extends JFrame {

	public JComponentEx() {
	
		super("JComponent의 공통 메소드 예제");
	
		Container c = getContentPane();
	
		c.setLayout(new FlowLayout());
		
		JButton b1 = new JButton("Magenta/Yellow Button");
		JButton b2 = new JButton("    Disabled Button    ");
		JButton b3 = new JButton("getX(), getY()");
		
		b1.setBackground(Color.YELLOW); // 배경색 설정
		b1.setForeground(Color.MAGENTA); // 글자색 설정
		b1.setFont(new Font("Arial", Font.ITALIC, 20)); // Arial, 20 픽셀 폰트 설정
	
		b2.setEnabled(false); // 버튼 비활성화
	
		b3.addActionListener(new ActionListener() {
	
			public void actionPerformed(ActionEvent e) {
	
				JButton b = (JButton)e.getSource();
	
				JComponentEx frame = (JComponentEx)b.getTopLevelAncestor();
	
				frame.setTitle(b.getX() + "," + b.getY()); // 타이틀에 버튼 좌표 출력
	
			}
	
		});
		
		c.add(b1); c.add(b2); c.add(b3); // 컨텐트팬에 버튼 부착
		
		setSize(260,200); 
	
		setVisible(true);
	
	}
	
	public static void main(String[] args) {
	
		new JComponentEx();
	
	}

}

실행 화면

// JLable을 이용한 레이블 만들기
import javax.swing.*;
import java.awt.*;

public class LabelEx extends JFrame {

	public LabelEx() {
	
		setTitle("레이블 예제");
	
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
		Container c = getContentPane();
	
		c.setLayout(new FlowLayout());

		// 문자열 레이블 생성
		JLabel textLabel = new JLabel("java.");
		
		// 이미지 레이블 생성
		ImageIcon beauty = new ImageIcon("images/beauty.jpg"); // 이미지 로딩
	
		JLabel imageLabel = new JLabel(beauty); // 이미지 레이블 생성
		
		// 문자열과 이미지를 모두 가진 레이블 생성
		ImageIcon normalIcon = new ImageIcon("images/normalIcon.gif"); // 이미지 로딩
	
		JLabel label = new JLabel("hello world", 
	
			normalIcon, SwingConstants.CENTER); // 레이블 생성

		// 컨텐트팬에 3개의 레이블 부착
		c.add(textLabel);
		c.add(imageLabel);
		c.add(label);
		
		setSize(400,600);
		
		setVisible(true);
	
	}
	
	public static void main(String [] args) {
	
		new LabelEx();
	
	}

}
  • 실행 결과

// JButton을 이용한 버튼 만들기
import javax.swing.*;
import java.awt.*;

public class ButtonEx extends JFrame {

	public ButtonEx() {
	
		setTitle("이미지 버튼 예제");
	
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
		Container c = getContentPane();
	
		c.setLayout(new FlowLayout());

		// 3개의 이미지를 파일로부터 읽어들인다.
		ImageIcon normalIcon = new ImageIcon("images/normalIcon.gif"); 
		ImageIcon rolloverIcon = new ImageIcon("images/rolloverIcon.gif"); 
		ImageIcon pressedIcon = new ImageIcon("images/pressedIcon.gif"); 
		
		// 3개의 이미지를 가진 버튼 생성
		JButton btn = new JButton("call~~", normalIcon); // normalIcon용 이미지 등록
	
		btn.setPressedIcon(pressedIcon); // pressedIcon용 이미지 등록
		btn.setRolloverIcon(rolloverIcon); // rolloverIcon용 이미지 등록
	
		c.add(btn);
		
		setSize(250,150);
	
		setVisible(true);
	
	}
	
	public static void main(String [] args) {
	
		new ButtonEx();
	
	}

}

실행 결과

좋은 웹페이지 즐겨찾기