반응형

문제

클릭 연습용 스윙 응용프로그램을 작성하라. "C"를 출력하는 JLabel을 하나 만들고 초기 위치를 (100, 100)으로 하고, "C"를 클릭할 때마다 컨텐트팬 내에 랸덤한 위치로 움직이게 하라.

 

소스 코드

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

public class Main6 extends JFrame{
	public Main6() {
		setTitle("클릭 연습 용 응용프로그램");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		Container c = getContentPane();
		
		c.setLayout(null);
		
		JLabel l = new JLabel("C");
		l.setSize(10,10);
		l.setLocation(100, 100);
		
		c.add(l);
		
		l.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int x = (int)(Math.random()*250);
				int y = (int)(Math.random()*250);
				l.setLocation(x, y);
			}
		});
		
		setSize(300,300);
		setVisible(true);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Main6();
	}

}
반응형
반응형

문제

컨텐트팬의 배경색은 초록색으로 하고 마우스를 드래깅하는 동안만 노란색으로 유지하는 스윙 응용프로그램을 작성하라.

 

소스 코드

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

public class Main2 extends JFrame{
	public Main2() {
		setTitle("드래깅동안 YELLOW...");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		Container c = getContentPane();
		Panel p = new Panel();
		p.setBackground(Color.green);
		
		p.addMouseMotionListener(new MouseAdapter() {
			public void mouseDragged(MouseEvent e) {
				p.setBackground(Color.yellow);
			}
		});
		p.addMouseListener(new MouseAdapter() {
			public void mouseReleased(MouseEvent e) {
				p.setBackground(Color.green);
			}
		});
		c.add(p);
		
		setSize(300,200);
		setVisible(true);
	}
	public static void main(String[] args) {
		new Main2();
		
	}

}

 

반응형

+ Recent posts