[Applet] 자바 애플릿(Java Applet)에서 마우스 이벤트 구현하기 [Programming Assignment for Module 5]

2023. 8. 25. 00:54·◎ Java/Applet🧳
728x90

- 자바 애플릿(Java Applet)에서 마우스 이벤트 구현하기

1. mouseMoved() 메서드 구현

사용자가 마우스를 움직일 때 이벤트 핸들러에 의해 mouseMoved()가 호출되면 지진 마커의 경우 지진 제목을, 도시의 경우 이름, 국가 및 인구를 표시한다.

- EarthquakeCityMap.java

/** Event handler that gets called automatically when the 
 * mouse moves.
 */
@Override
public void mouseMoved() {
    // clear the last selection
    if (lastSelected != null) {
        lastSelected.setSelected(false);
        lastSelected = null;

    }
    selectMarkerIfHover(quakeMarkers);
    selectMarkerIfHover(cityMarkers);
    //loop();
}

// If there is a marker selected 
private void selectMarkerIfHover(List<Marker> markers) {
    // Abort if there's already a marker selected
    if (lastSelected != null) {
        return;
    }

    for (Marker m : markers) {
        CommonMarker marker = (CommonMarker)m;
        if (marker.isInside(map,  mouseX, mouseY)) {
            lastSelected = marker;
            marker.setSelected(true);
            return;
        }
    }
}

- CommonMarker.java

// Common piece of drawing method for markers; 
// YOU WILL IMPLEMENT. 
// Note that you should implement this by making calls 
// drawMarker and showTitle, which are abstract methods 
// implemented in subclasses
public void draw(PGraphics pg, float x, float y) {
    // For starter code just drawMaker(...)
    if (!hidden) {
        drawMarker(pg, x, y);
        if (selected) {
            showTitle(pg, x, y);
        }
    }
}
public abstract void drawMarker(PGraphics pg, float x, float y);
public abstract void showTitle(PGraphics pg, float x, float y);

- EarthquakeMarker.java

/** Show the title of the earthquake if this marker is selected */
public void showTitle(PGraphics pg, float x, float y) {
    String title = getTitle();
    pg.pushStyle();

    pg.rectMode(PConstants.CORNER);

    pg.stroke(110);
    pg.fill(255,255,255);
    pg.rect(x, y + 15, pg.textWidth(title) +6, 18, 5);

    pg.textAlign(PConstants.LEFT, PConstants.TOP);
    pg.fill(0);
    pg.text(title, x + 3 , y +18);


    pg.popStyle();

}

- CityMarker.java

/** Show the title of the city if this marker is selected */
public void showTitle(PGraphics pg, float x, float y) {
    String name = getCity() + " " + getCountry() + " ";
    String pop = "Pop: " + getPopulation() + " Million";

    pg.pushStyle();

    pg.fill(255, 255, 255);
    pg.textSize(12);
    pg.rectMode(PConstants.CORNER);
    pg.rect(x, y-TRI_SIZE-39, Math.max(pg.textWidth(name), pg.textWidth(pop)) + 6, 39);
    pg.fill(0, 0, 0);
    pg.textAlign(PConstants.LEFT, PConstants.TOP);
    pg.text(name, x+3, y-TRI_SIZE-33);
    pg.text(pop, x+3, y - TRI_SIZE -18);

    pg.popStyle();
}

mouseMoved() 메서드 구현


2. mouseClicked() 메서드 구현

지진 표시를 선택하면 해당 지진의 위협 범위 내에 있는 모든 도시가 지도에 표시되고 다른 모든 도시와 지진은 숨겨지며, 도시의 마커를 선택하면 위협 범위에 해당 도시가 포함된 모든 지진이 지도에 표시되고 다른 모든 도시와 지진은 숨겨진다.

- EarthquakeCityMap.java

/** The event handler for mouse clicks
 * It will display an earthquake and its threat circle of cities
 * Or if a city is clicked, it will display all the earthquakes 
 * where the city is in the threat circle
 */
@Override
public void mouseClicked() {
    if (lastClicked != null) {
        unhideMarkers();
        lastClicked = null;
    }
    else if (lastClicked == null) {
        checkEarthquakesForClick();
        if (lastClicked == null) {
            checkCitiesForClick();
        }
    }
}

// Helper method that will check if a city marker was clicked on
// and respond appropriately
private void checkCitiesForClick() {
    if (lastClicked != null) return;
    // Loop over the earthquake markers to see if one of them is selected
    for (Marker marker : cityMarkers) {
        if (!marker.isHidden() && marker.isInside(map, mouseX, mouseY)) {
            lastClicked = (CommonMarker)marker;
            // Hide all the other earthquakes and hide
            for (Marker mhide : cityMarkers) {
                if (mhide != lastClicked) {
                    mhide.setHidden(true);
                }
            }
            for (Marker mhide : quakeMarkers) {
                EarthquakeMarker quakeMarker = (EarthquakeMarker)mhide;
                if (quakeMarker.getDistanceTo(marker.getLocation()) > quakeMarker.threatCircle()) {
                    quakeMarker.setHidden(true);
                }
            }
            return;
        }
    }		
}

// Helper method that will check if an earthquake marker was clicked on
// and respond appropriately
private void checkEarthquakesForClick() {
    if (lastClicked != null) return;
    // Loop over the earthquake markers to see if one of them is selected
    for (Marker m : quakeMarkers) {
        EarthquakeMarker marker = (EarthquakeMarker)m;
        if (!marker.isHidden() && marker.isInside(map, mouseX, mouseY)) {
            lastClicked = marker;
            // Hide all the other earthquakes and hide
            for (Marker mhide : quakeMarkers) {
                if (mhide != lastClicked) {
                    mhide.setHidden(true);
                }
            }
            for (Marker mhide : cityMarkers) {
                if (mhide.getDistanceTo(marker.getLocation()) > marker.threatCircle()) {
                    mhide.setHidden(true);
                }
            }
            return;
        }
    }
}

// loop over and unhide all markers
private void unhideMarkers() {
    for(Marker marker : quakeMarkers) {
        marker.setHidden(false);
    }

    for(Marker marker : cityMarkers) {
        marker.setHidden(false);
    }
}

- EarthquakeMarker.java

/**
 * Return the "threat circle" radius, or distance up to 
 * which this earthquake can affect things, for this earthquake.   
 * DISCLAIMER: this formula is for illustration purposes
 *  only and is not intended to be used for safety-critical 
 *  or predictive applications.
 */
 public double threatCircle() {	
    double miles = 20.0f * Math.pow(1.8, 2*getMagnitude()-5);
    double km = (miles * kmPerMile);
    return km;
}

mouseClicked() 메서드 구현


728x90
'◎ Java/Applet🧳' 카테고리의 다른 글
  • [Applet] 자바 애플릿(Java Applet)으로 지진 종류 시각화하기 [Programming Assignment for Module 4]
  • [Applet] 자바 애플릿(Java Applet)으로 지진 강도 시각화하기 [Programming Assignment for Module 3]
  • [Applet] 자바 애플릿(Java Applet)으로 전세계 기대수명 시각화하기 [Bonus: Visualizing life expectancy]
  • [Applet] 자바 애플릿(Java Applet)으로 우리 동네 지도 표시하기 [Programming Assignment for Module 1]
예르미(yermi)
예르미(yermi)
끊임없이 제 자신을 계발하는 개발자입니다👨🏻‍💻
  • 예르미(yermi)
    예르미의 코딩노트
    예르미(yermi)
  • 전체
    오늘
    어제
    • 분류 전체보기 (937)
      • ◎ Java (133)
        • Java☕ (93)
        • JSP📋 (26)
        • Applet🧳 (6)
        • Interview👨🏻‍🏫 (8)
      • ◎ JavaScript (48)
        • JavaScript🦎 (25)
        • jQuery🌊 (8)
        • React🌐 (2)
        • Vue.js🔰 (6)
        • Node.js🫒 (3)
        • Google App Script🐑 (4)
      • ◎ HTML5+CSS3 (17)
        • HTML5📝 (8)
        • CSS3🎨 (9)
      • ──────────── (0)
      • ▣ Framework (67)
        • Spring🍃 (36)
        • Spring Boot🍀 (12)
        • Bootstrap💜 (3)
        • Selenium🌕 (6)
        • MyBatis🐣 (10)
      • ▣ Tools (47)
        • API🎯 (18)
        • Library🎲 (15)
        • JitPack🚀 (3)
        • Jenkins👨🏻 (7)
        • Thymeleaf🌿 (4)
      • ▣ Server (32)
        • Apache Tomcat🐱 (14)
        • Apache HTTP Server🛡️ (1)
        • Nginx🧶 (7)
        • OracleXE💿 (4)
        • VisualSVN📡 (4)
      • ▣ OS : 운영체제 (18)
        • cmd : 명령프롬프트💻 (10)
        • Linux🐧 (8)
      • ▣ SQL : Database (56)
        • Oracle SQL🏮 (26)
        • PL SQL💾 (9)
        • MySQL🐬 (6)
        • MariaDB🦦 (6)
        • H2 Database🔠 (3)
        • SQL 실전문제🐌 (6)
      • ────────── (0)
      • ◈ Human Project (86)
        • Mini : Library Service📚 (15)
        • 화면 설계 [HTML]🐯 (10)
        • 서버 프로그램 구현🦁 (15)
        • Team : 여수어때🛫 (19)
        • Custom : Student🏫 (9)
        • Custom : Board📖 (18)
      • ◈ Yermi Project (40)
        • 조사모아(Josa-moa)📬 (5)
        • Riddle-Game🧩 (6)
        • 맛있을 지도🍚 (2)
        • 어디 가! 박대리!🙋🏻‍♂️ (5)
        • 조크베어🐻‍❄️ (4)
        • Looks Like Thirty🦉 (2)
        • Toy Project💎 (12)
        • 오픈소스 파헤치기🪐 (4)
      • ◈ Refactoring (15)
        • Mini : Library Service📚 (8)
        • 서버 프로그램 구현🦁 (1)
        • Team : 여수어때🛫 (0)
        • 쿼리 튜닝일지🔧 (6)
      • ◈ Coding Test (89)
        • 백준(BOJ)👨🏻‍💻 (70)
        • 프로그래머스😎 (2)
        • 코드트리🌳 (7)
        • 알고리즘(Algorithm)🎡 (10)
      • ◈ Study (102)
        • 기초튼튼 개발지식🥔 (25)
        • HTTP 웹 지식💡 (4)
        • 클린코드(Clean Code)🩺 (1)
        • 디자인패턴(GoF)🥞 (12)
        • 다이어그램(Diagram)📈 (4)
        • 파이썬(Python)🐍 (16)
        • 에러노트(Error Note)🧱 (34)
        • 웹 보안(Web Security)🔐 (6)
      • ◈ 공부모임 (39)
        • 혼공학습단⏰ (18)
        • 코드트리 챌린지👊🏻 (2)
        • 개발도서 100독👟 (8)
        • 나는 리뷰어다🌾 (11)
      • ◈ 자격증 공부 (37)
        • 정보처리기사🔱 (16)
        • 정보처리산업기사🔅 (9)
        • 컴퓨터활용능력 1급📼 (12)
      • ─────────── (0)
      • ◐ 기타 (113)
        • 알아두면 좋은 팁(tip)✨ (46)
        • 개발자의 일상🎈 (44)
        • 개발도서 서평🔍 (10)
        • 개발관련 세미나🎤 (2)
        • 블로그 꾸미기🎀 (9)
        • 사도신경 프로젝트🎚️ (2)
  • 인기 글

  • 최근 댓글

  • 태그

    BOJ
    spring
    SQL
    Java
    jsp
    백준 티어
    javascript
    코딩 테스트
    프로그래밍
    꿀팁
    백준
    Error Note
    자바스크립트
    일상
    Oracle
    코딩
    CSS
    html
    Project
    Database
  • 250x250
  • hELLO· Designed By정상우.v4.10.3
예르미(yermi)
[Applet] 자바 애플릿(Java Applet)에서 마우스 이벤트 구현하기 [Programming Assignment for Module 5]
상단으로

티스토리툴바