2011年8月1日月曜日

フレーム内の背景色を変更または指定する(Java)

【4-1】 AWTの場合
import java.awt.Frame;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Main {
    public static void main(String[] args){
        Gui frame = new Gui();
        frame.setSize(500, 300);
        frame.setBackground(Color.red); // フレーム内の背景色変更
        frame.setVisible(true);
    }
}

class Gui extends Frame{
    public Gui(){
           addWindowListener(new WindowAdapter(){
                  public void windowClosing(WindowEvent we){
                      System.exit(0);
             }
           });
    }
}
【4-2】Swingの場合①
import javax.swing.JFrame;
import java.awt.Color;
public class Main {
    public static void main(String[] args){
        Gui frame = new Gui();
        frame.setVisible(true);
    }
}
class Gui extends JFrame{
    public Gui(){
        setSize(500, 300);
        getContentPane().setBackground(Color.red);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

【4-3】Swingの場合②
import java.awt.Color;
import javax.swing.JFrame;

public class Sample extends JFrame{
    private static final long serialVersionUID = 1L;
    public static void main(String[] args){
        new Sample();
    }

    Sample(){
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(500, 300);
        this.getContentPane().setBackground(Color.RED);
        this.setVisible(true);
    }
}

実行結果


【環境】
Mac/Win
【解説】
setBackground(Color.(色を指定))   
で背景の設定色を指定できます。

black または、BLACK
blue または、BLUE
シアンcyan または、CYAN
ダークグレイ DARK_GRAY または、darkGray
グレイ gray または、GRAY
green または、GREEN
ライトグレイ LIGHT_GRAY または、lightGray
マゼンダ magenta または、MAGENTA
オレンジ orange または、ORANGE
ピンク pink または、PINK
red または、RED
white または、WHITE
黄色 yellow または、YELLOW 

0 件のコメント: