標籤:
問題:
聲明顏色類Color。一種顏色由(紅、綠、藍)三元色值組成,稱為RGB值。一個int整數可表示一種顏色,結構為:最高位元組全1,其後3位元組分別儲存“紅、綠、藍”單色值,單色值範圍是0~255。例如,0xff00ff00表示綠色,RGB值為(0,255,0)。
聲明Color顏色類
RGB顏色值說明見教材實驗3,RGB整數結構3.4所示,常用顏色及其RGB值如表3-1所示。
圖1.1 顏色RGB整數結構圖
表1-1 顏色及其RGB值
顏色 |
RGB值 |
RGB值的十六進位 |
java.awt.Color常量 |
紅 |
(255,0,0) |
0xffff0000 |
Color.red |
綠 |
(0,255,0) |
0xff00ff00 |
Color.green |
藍 |
(0,0,255) |
0xff0000ff |
Color.blue |
黑 |
(0,0,0) |
0xff000000 |
Color.black |
白 |
(255,255,255) |
0xffffffff |
Color.white |
Color顏色類主要成員聲明如下,再聲明表示紅、綠、藍、黑、白等顏色的常量。
public class Color { //顏色類 private int value; //顏色值 public Color(int red, int green, int blue) //以三元色構造顏色對象 public Color(int rgb) //以三元色構造顏色對象 public int getRGB() //返回顏色對象的RGB值 public int getRed() //返回顏色對象的紅色值 public int getGreen() //返回顏色對象的綠色值 public int getBlue() //返回顏色對象的藍色值 public String toString() //返回顏色對象的字串描述}
代碼實現:
import java.util.*;public class Color{private int value;int red,green,blue;public Color(int red,int green,int blue){this.set(red,green,blue);this.value=blue+(green<<8)+(red<<16)+(255<<24);}public Color(int rgb){this.value=rgb;this.set(rgb);}public void set(int rgb){this.blue=this.value&255;this.green=(this.value&(255<<8))>>8;this.red=(this.value&(255<<16))>>16;}public void set(int red,int green,int blue){this.red=red;this.green=green;this.blue=blue;}public String getRGB(){return Integer.toHexString(this.value);}public int getRed(){return this.red;}public int getGreen(){return this.green;}public int getBlue(){return this.blue;}public String toString(){return "( red , green , blue ) === ( "+this.red+" , "+this.green+" , "+this.blue+" )";}}class Main{public static void main(String[] args){final int MIN=-16777216;Scanner sc=new Scanner(System.in);int a=(255<<24)+(255<<16)+(255<<8)+255;//System.out.println("Please input n ( "+a+"<=a<="+(255<<24)+")");System.out.println("Please input red ,green and blue`s single color value");System.out.println("( 0<=value <=255 ) :");while(sc.hasNext()){Color c=new Color(sc.nextInt(),sc.nextInt(),sc.nextInt());System.out.println(c);System.out.println("RGB = 0x"+c.getRGB());System.out.println("Red = "+c.getRed());System.out.println("Green = "+c.getGreen());System.out.println("Blue = "+c.getBlue());System.out.println("-----------------");System.out.println("Please input n ( "+MIN+" <= n <= -1) : ");c=new Color(sc.nextInt());System.out.println(c);System.out.println("RGB = 0x"+c.getRGB());System.out.println("Red = "+c.getRed());System.out.println("Green "+c.getGreen());System.out.println("Blue = "+c.getBlue());System.out.println();System.out.println("Please input red ,green and blue`s single color value :");}}}
java之 ------ 類的封裝、繼承和多態(四)