概要
Javaで「色とりどりの楕円を重ねて表示する」の動作を確認してみました。
実装
以下のファイルを作成しました。
Daen.java
import java.awt.*;
import javax.swing.*;
import java.util.Timer;
import java.util.TimerTask;
public class Daen {
public static void main(String[] args) {
JFrame frame = new JFrame();
// タイトル名を設定
frame.setTitle( "タイトル" );
// フレームの大きさを設定
frame.setSize( 500, 500 );
// ”×”ボタンを押した時の処理を設定
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// フレームにパネルを追加
MyPanel3 panel = new MyPanel3();
frame.getContentPane().add( panel );
// フレームを表示
frame.setVisible( true );
}
}
// JPanelを継承したMyPanelを作成
class MyPanel3 extends JPanel {
public MyPanel3() {
TimerTask task = new TimerTask(){
public void run(){
repaint();
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 1000);
}
// 描画
public void paintComponent( Graphics g ) {
super.paintComponent( g );
}
public void paint(Graphics g){
setBackground( Color.black );
g.setColor(Color.white);
g.fillRect(0,0,500,500);
for(int i=0; i<100; i++){
g.setColor(new Color((int)(Math.random()*256.0),
(int)(Math.random()*256.0),
(int)(Math.random()*256.0)));
double x = Math.random();
double y = Math.random();
g.fillOval((int)(x*256.0),
(int)(y*256.0),
(int)(x*256.0)+1,
(int)(y*256.0)+1);
}
}
}
以下のコマンドを実行しました。
$ javac Daen.java
$ java Daen
実行結果は以下の通りでした。
まとめ
何かの役に立てばと。