저장소 : GitHub Repositories leeconomy1121/java-study
package timer_Ex;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.swing.JOptionPane;
class Task1 extends TimerTask {
private int i = 0;
@Override
public void run() {
i += 1;
System.out.println("계란 삶는 중 " + i);
}
}
class Task2 implements Runnable {
public void run() {
JOptionPane.showMessageDialog(null, "계란 삶기 완료");
};
}
public class App {
public static void main(String[] args) {
// 1. 5초 간격 타이머 "계란 삶는 중"
Timer egg = new Timer();
egg.scheduleAtFixedRate(new Task1(), 5000L, 5000L); // 5초에 한번씩 반복
// 2. 30초 간격 타이머 "계란 삶기 완료"
ScheduledExecutorService finish = Executors.newScheduledThreadPool(30);
finish.scheduleAtFixedRate(new Task2(), 30L, 30L, TimeUnit.SECONDS); // 30초에 한번씩 반복
// JOptionPane.showMessageDialog(null, "계란 삶기 완료");
}
}
결과
package innerClasses;
public class App implements Runnable {
private String name = "미키 마우스";
public static void main(String[] args) {
new App().start();
}
private void start() {
// activate 메소드를 사용해서 이너클래스들로 실행방법
// 1. App에 인터페이스 Runnable을 구현해서 실행
activate(this);
// 2. 익명클래스
activate(new Runnable() {
public void run() {
System.out.println(name);
}
});
// 3. 메소드 이너 클래스
class Runner1 implements Runnable {
public void run() {
System.out.println(name);
}
}
activate(new Runner1());
}
public void activate(Runnable runnable) {
runnable.run();
}
@Override
public void run() {
System.out.println(name);
}
}
package gui;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JToolBar;
//class ColorButtonListener implements ActionListener {
// private MainPanel mainPanel;
// private Color c;
//
// public ColorButtonListener(MainPanel mainPanel, Color c) {
// this.mainPanel = mainPanel;
// this.c = c;
// }
//
// @Override
// public void actionPerformed(ActionEvent e) {
// // System.out.println("빨간색 버튼 클릭!");
// mainPanel.setBackground(c);
// }
//}
//class BlueButtonListener implements ActionListener {
// private MainPanel mainPanel;
//
// public BlueButtonListener(MainPanel mainPanel) {
// this.mainPanel = mainPanel;
// }
//
// @Override
// public void actionPerformed(ActionEvent e) {
// // System.out.println("파란색 버튼 클릭!");
// mainPanel.setBackground(Color.BLUE);
// }
//}
public class Toolbar extends JToolBar{
private static final long serialVersionUID = 1L;
public Toolbar(MainPanel mainPanel) {
final JButton redButton = new JButton("RED");
final JButton blueButton = new JButton("BLUE");
// 버튼에 이벤트를 연결('클릭' 이벤트)
// 익명클래스 -> 람다식(Lambda Expression) 구현
redButton.addActionListener(e -> mainPanel.setBackground(Color.RED));
blueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainPanel.setBackground(Color.BLUE);
}
});
// 툴바에 버튼을 붙임
add(redButton);
add(blueButton);
}
}
결과
RED 버튼 클릭 시
BLUE 버튼 클릭 시