CodeGym /Java Blog /Toto sisi /Java.Awt.Color 類
John Squirrels
等級 41
San Francisco

Java.Awt.Color 類

在 Toto sisi 群組發布
如果你正在掌握 Java Abstract Toolkit,你將不得不學習 Java AWT Color Class 的應用。由於涉及到很多構造函數和方法,因此一開始可能會讓人感到害怕。但不用擔心,我們已經為您準備好了:) 通過這個關於 Java AWT Color 的完整概述,您將學習如何創建新的顏色類型並立即對其進行管理。我們還將提供一些練習測試,幫助您磨練技能。

什麼是 Java 中的 AWT 顏色類?

AWT Color 的主要目的是允許開發人員使用 RGB(紅、綠、藍)、RGBA(紅、綠、藍、alpha)或 HSB(色調、飽和度、BRI 組件)包使用 Java 代碼創建新顏色。該類包含兩個值 - 陰影代碼和不透明度/透明度值。Java.Awt.Color 類 - 1以下是聲明類 java.awt.Color 的方式:

public class Color
   extends Object
      implements Paint, Serializable
要使用 Class.java.awt.Color 聲明不同類型的顏色,開發人員使用構造函數 - 我們現在將了解它們。

Java 中的 AWT.Color 構造函數

根據您要創建的顏色參數,您需要使用特定類型的顏色構造函數。其中有一些 - 讓我們一一檢查。
  • Color(float r, float g, float b)是用於在不透明的 RGB 配色方案中定義顏色的類。您可以指定 0.0 到 0.1 之間的任意顏色範圍。
  • Color(float r, float b, float g, float a)是定義 RGBA 顏色的類(可用值的範圍是 0.0 和 0.1)。
  • Color(ColorSpace c, float[], co, float a)在您預先指定的 ColorSpace 中定義顏色。開發人員在定義的 alpha 的浮點數組中指定顏色分量的範圍。
  • Color(int, rgb)是創建 RGB 顏色(不透明)的類。請務必注意構造函數的組件值 - 紅色為 16-23,綠色為 8-15,藍色為 0-7。
  • Color(int r, int g, int b)- 一種用於定義不透明 RGB 顏色的方法。顏色值應介於 0 和 255 之間。
  • Color(int r, int g, int b, int a)- 在 RGBA 方案 (0-255) 中創建顏色。
  • Color(int rgba, boolean b)用於在定義的組合值內創建 sRGB 顏色。alpha 的值範圍為 24-31,紅色為 16-23,綠色為 8-15,藍色為 0-7。
除此之外,class.awt.color 對繼承自的字段進行操作Java.awt.Transparency
  • TRANSLUCENT表示顏色是否包含 alpha 值並具有兩個值 - 0 和 1。
  • OPAQUE將 alpha 值 1 分配給保證其完全不透明的對象。
  • BITMASK表示絕對不透明度或透明度值,位於 (0;1) 範圍內,其中 0 是完全透明,1 是極度不透明。

使用 Java AWT 顏色類的前 15 種方法

要操縱顏色、調整其暗度或亮度,Java 開發人員依賴不同的方法。有幾十個這樣的,所以你不必記住所有的人。但是,當談到使用最廣泛的 Java AWT Color 方法時,我們將列表縮小到十五個。記住這些而不必參考 Java API 文檔將對開發人員有所幫助。

較暗()

該方法用於創建一種新顏色,該顏色是您已經定義的顏色的深色版本。 示例

Color.green.darker()
如果應用darker()一次不足以創建所需的陰影,請隨意多次重新應用該方法,如下所示:

Color.green.darker().darker().darker().darker().darker()

更亮()

顧名思義,Color brighter()用於提亮您已有的陰影。與 類似darker(),它可以對一種顏色使用多次。 示例

Color myColor = Color.RED;          

    JLabel label = new JLabel("First Name");
    label.setForeground(myColor.brighter());

int getAlpha() 函數

如果要返回顏色的 alpha 分量,請使用此方法。請記住,alpha 值位於 0-255 範圍內。下面是方法的應用和返回的例子。 示例

alpha = Color.black.getAlpha();
return new Color(components[0], components[1], components[2], alpha);

靜態顏色 getColor(String nm)

Java 開發人員可以使用此方法通過系統屬性定位顏色。還有其他處理類似目標的方法:
  • static Color getColor(String nm, int v)
  • static Color getColor(String nm, Color v)

靜態顏色解碼(字符串 nm)

此方法用於將顏色顯示為字符串。轉換完成後,開發人員將獲得定義的不透明顏色。 示例

public static Color decodeColor(String hexColor) {

 return Color.decode(hexColor);

PaintContext createContext(ColorModel cm,Rectangle r,Rectangle2D r2d,AffineTransform xform,RenderingHints hints)

這種方法看起來很複雜,但它比看起來更容易操作。Paint Context CreateContext()用於定義重複的純色圖案。 示例

 public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds,

                  AffineTransform xform, RenderingHints hints)

 {
   try
   {
     return new AxialShadingContext(shading, cm, xform, matrix, deviceBounds);
   }
   catch (IOException e)

   {

     LOG.error("An error occurred while painting", e);

     return new Color(0, 0, 0, 0).createContext(cm, deviceBounds, userBounds, xform, hints);

   }
 }
}

float[] getComponents(ColorSpace cspace, float[] compArray)

這是一個 Java 方法,您可以將其應用於顏色以返回其浮點數組和 alpha 組件。該方法適用於ColorSpace由 cspace 定義的給定。 示例

public float[] getComponents(ColorSpace cspace, float[] compArray) {

return myColor.getComponents(cspace, compArray);

}

色彩空間 getColorSpace()

Java 開發人員可以使用此方法返回所選顏色的顏色空間。為給定條目獲取顏色空間的另一種方法是應用 Arrays.to.String。這是一個更複雜的策略,如下例所示: 示例

public class Main {
  public static void main(String[] args) {

    Color myColor = Color.RED;          

    System.out.println(Arrays.toString(myColor.getComponents(ColorSpace.getInstance(ColorSpace.CS_CIEXYZ),null)));

getHSBColor(浮動 h,浮動 s,浮動 b)

Java 開發人員應用此方法根據 HSB 模型的值創建新的顏色對象。 示例

 private Color colorAt(int y)

 {
   return Color.getHSBColor(1 - (float) y / (height - 1), 1, 1);
 }
}

getGreen()	returns the green component in the range 0-255 in the default sRGB space.

得到綠色()

此 Java 方法返回您創建的顏色的綠色分量的值。所有值都在 RGB 配色方案中對應於綠色的範圍內。 示例

Color clickBoxColor = new Color(color.getRed(), color.getGreen(), color.getBlue(), 20);

獲取紅色()

與 類似getGreen()getRed返回給定顏色的紅色分量的值。您已經在上面的示例中看到瞭如何應用該方法。

getBlue()

此方法返回 RGB 配色方案值範圍內的藍色值。同樣,使用 的例子getBlue(),參見 的描述getGreen()

獲取阿爾法()

當開發人員想要找到給定顏色的 alpha 值時,在 Java 中使用 getAlpha() 方法。與 RBG 類似,所有顏色的 alpha 都在 0-255 範圍內。 示例:這裡是如何getAlpha()用作循環的一部分。

int alpha = color.getAlpha();
	if (alpha != 255)
	{
		setStrokeAlpha(alpha);
		strokeAlphaSet = true;

獲取透明度()

此方法返回您或其他開發人員在創建顏色時為顏色指定的透明度值。 示例

public int getTransparency() {

return myColor.getTransparency();

布爾等於(對像對象)

如果您將兩種顏色相互比較,此方法非常有用。它讓 Java 開發人員知道兩個顏色對象的值是否相等。 示例

import java.awt.Color;
public class Main {
  public static void main(String[] a) {
    Color myBlack = new Color(0, 0, 0); // Color black
    Color myWhite = new Color(255, 255, 255); // Color white
    System.out.println(myBlack.equals(myWhite));
  }
}

等於(對像對象)

與 類似boolean equals(Object obj),這是一種比較方法。我們用它來確定顏色對像是否彼此相等。 示例

Object a = new Object(); Object b = new Object(); return(a.equals(b));

Java 中使用的主要顏色指南

現在您已經了解了在 Java 中用於操作顏色的方法,讓我們來看看您將使用的字段類型。這些是 Java 開發人員可以定義的實際靜態顏色。您可以通過輸入名稱來定義顏色(確保您輸入的名稱與官方文檔中所寫的完全一致)或指定其 RGB 值。讓我們來看看開發人員使用的調色板:
字段名稱 描述
靜態顏色黑色(BLACK) 定義黑色
靜態顏色白色(WHITE) 定義白色
靜態顏色藍色(BLUE) 用於定義藍色
靜態顏色灰色(GREY) 定義灰色
靜態顏色深灰色 (DARK_GRAY) 定義較深的灰色陰影
靜態顏色淺灰色 (LIGHT_GRAY) 定義較淺的灰色陰影
靜態顏色綠色(GREEN) 用於定義綠色
靜態顏色洋紅色 (MAGENTA) 定義洋紅色陰影
靜態顏色粉紅色(PINK) 在 Java 中定義粉色
靜態顏色橙色 (ORANGE) 在 Java 中創建橙色
靜態顏色黃色 (YELLOW) 用於定義黃色
靜態顏色紅色 (RED) 在 Java 中定義紅色

在 Java 中使用 AWT.Color 的練習題

您覺得您在 Java 中的 AWT Color 基礎紮實嗎?讓我們通過解決一些實際問題來測試這些技能——在這裡,您必須應用構造函數和常用方法,以及其他與顏色無關的 Java 工具。 練習問題#1。創建一個自定義組件,讓程序用戶可以調整顏色的 RGB 級別(類似於RGBColorChooser)。確保將 getColor() 包含到您的組件中。使組件成為 Panel 子類,而不是小程序。 回答:這是一個相當複雜的問題 - 讓我們將其分解為可管理的步驟:
  1. 將 an 轉換RGBChooser為組件。
  2. 向組件添加新例程 - getColor()
  3. 添加setColor()以設置顏色。
這是您在一天結束時應該獲得的示例代碼:

import java.awt.*;
    import java.awt.event.*;
    
    public class RGBChooserComponent extends Panel implements AdjustmentListener {
       
       private Scrollbar redScroll, greenScroll, blueScroll;   // Scroll bars.
       
       private Label redLabel, greenLabel, blueLabel;  // For displaying RGB values.
                     
                     
       private Canvas colorCanvas;  // Color patch for displaying the color.
                     
       public RGBChooserComponent() {  // Constructor.
       
           /*Now let’s add scrollbars with values from 0 to 255. */
           
           redScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 265);
           greenScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 265);
           blueScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 265);
           
           /* Create Labels showing current RGB and HSB values. */
           
           redLabel = new Label(" R = 0");
           greenLabel = new Label(" G = 0");
           blueLabel = new Label(" B = 0");
           
           /* We are setting backgrounds for Scrollbars and Labels, so they get the default
              gray background of the applet. */
           
           redScroll.setBackground(Color.lightGray);
           greenScroll.setBackground(Color.lightGray);
           blueScroll.setBackground(Color.lightGray);
           
           redLabel.setBackground(Color.white);
           greenLabel.setBackground(Color.white);
           blueLabel.setBackground(Color.white);
           
           /* Establish a panel that would listen for changes to the Scrollbars' values */
           
           redScroll.addAdjustmentListener(this);
           greenScroll.addAdjustmentListener(this);
           blueScroll.addAdjustmentListener(this);
           
           /* Add a canva, the background color of which will always match the currently selected color. */
           
           colorCanvas = new Canvas();
           colorCanvas.setBackground(Color.black);
           
           /* Create the applet layout, which consists of a row of
              three equal-sized regions holding the Scrollbars,
              the Labels, and the color patch.  The background color
              of the applet is gray, which will show around the edges
              and between components. */
           
           setLayout(new GridLayout(1,3,3,3));
           setBackground(Color.gray);
           Panel scrolls = new Panel();
           Panel labels = new Panel();
           
           add(scrolls);
           add(labels);
           add(colorCanvas);
           
           /* Add the Scrollbars and the Labels to their respective panels. */
           
           scrolls.setLayout(new GridLayout(3,1,2,2));
           scrolls.add(redScroll);
           scrolls.add(greenScroll);
           scrolls.add(blueScroll);
           
           labels.setLayout(new GridLayout(3,1,2,2));
           labels.add(redLabel);
           labels.add(greenLabel);
           labels.add(blueLabel);
           
       } // end init();
       
       
       public Color getColor() {
              // Get the color currently displayed by the component.
           int r = redScroll.getValue();
           int g = greenScroll.getValue();
           int b = blueScroll.getValue();
           return new Color(r, g, b);
       }
       
       
       public void setColor(Color c) {
             // Set the component to display the given color.
             // (Ignore this if c is null.)
          if (c != null) {
             int r = c.getRed();      // Get the color levels from the color.
             int g = c.getGreen();
             int b = c.getBlue();
             redLabel.setText(" R = " + r);   // Set the labels.
             greenLabel.setText(" G = " + g);
             blueLabel.setText(" B = " + b);
             redScroll.setValue(r);        // Set the scrollbars.
             greenScroll.setValue(g);
             blueScroll.setValue(b);
             colorCanvas.setBackground(new Color(r,g,b));  // Set the canvas.
             colorCanvas.repaint();
          }
       }
       
       
       public Dimension getMinimumSize() {
              // Specify the minimum reasonable size of this component.
          return new Dimension(150,40);
       }
       
       
       public Dimension getPreferredSize() {
              // Specify the preferred size of this component.
          return new Dimension(280,80);
       }
       
    
       public void adjustmentValueChanged(AdjustmentEvent evt) {
               // This is called when the user has changed the values on
               // one of the scrollbars.  All the scrollbars are checked,
               // the labels are set to display the correct values,
               // and the color patch is reset to correspond to the new color.
           int r = redScroll.getValue();
           int g = greenScroll.getValue();
           int b = blueScroll.getValue();
           redLabel.setText(" R = " + r);
           greenLabel.setText(" G = " + g);
           blueLabel.setText(" B = " + b);
           colorCanvas.setBackground(new Color(r,g,b));
           colorCanvas.repaint();  // Redraw the canvas in its new color.
       } // end adjustmentValueChanged
    
       
       public Insets getInsets() {
              // The system calls this method to find out how much space to
              // leave between the edges of the applet and the components that
              // it contains.  I want a 2-pixel border at each edge.
          return new Insets(2,2,2,2);
       }
       
    }  // end class RGBColorChooser

結論

恭喜,您已經閱讀了這份關於 Java 中的 AWT.Color 的詳盡指南。現在,處理接口會容易得多。不要忘記通過解決練習題和 CodeGym 測驗來應用您的知識。熟能生巧,所以請盡量嘗試示例問題!
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION