본문 바로가기
JAVA/예제

[JAVA] Label 클릭시 위치 랜덤 이동

by JJH0100 2022. 10. 28.
728x90
반응형
package Ex01;

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

public class CClick extends JFrame{
	private JLabel la = new JLabel("C");
	public CClick() {
		setTitle("클릭");
		setSize(300, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container c = getContentPane();
		c.setLayout(null);
		la.setSize(20,20);
		la.setLocation(100,100);
		c.add(la);
		la.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				JLabel la = (JLabel)e.getSource();
				Container c = la.getParent();
				//컨테이너 크기 내에서 랜덤한 레이블 위치 설정
				int xBound = c.getWidth() - la.getWidth();
				int yBound = c.getHeight() - la.getHeight();
				
				int x = (int)(Math.random()*xBound);
				int y = (int)(Math.random()*yBound);
				
				la.setLocation(x, y);
			}
		});
		
		setVisible(true);
	}
	public static void main(String[] args) {
		new CClick();
	}
}

클릭 시 랜덤한 위치로 이동

 

(int)(Math.random()*xBound) 처럼 Math.random()*xBound를 ()처리 해주어야 함.

728x90
반응형

댓글