CodeGym /Java Blog /무작위의 /Java.Awt.Color 클래스
John Squirrels
레벨 41
San Francisco

Java.Awt.Color 클래스

무작위의 그룹에 게시되었습니다
Java Abstract Toolkit을 마스터하고 있다면 Java AWT Color Class의 응용 프로그램을 배워야 합니다. 관련된 생성자와 메서드가 많기 때문에 처음에는 두렵게 느껴질 수 있습니다. 하지만 걱정하지 마세요. 저희가 도와드리겠습니다. :) Java AWT Color에 대한 전체 설명을 통해 새로운 색상 유형을 생성하고 즉시 관리하는 방법을 배울 수 있습니다. 또한 기술을 연마하는 데 도움이 되는 몇 가지 연습 테스트도 제공합니다.

Java의 AWT 색상 클래스는 무엇입니까?

AWT Color의 주요 목적은 개발자가 RGB(빨강, 녹색, 파랑), RGBA(빨강, 녹색, 파랑, 알파) 또는 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에서 색상을 정의합니다. 개발자는 정의된 알파의 float 배열에서 색상 구성 요소의 범위를 지정합니다.
  • 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 색상을 생성하는 데 사용됩니다. 값의 범위는 알파의 경우 24-31, 빨간색의 경우 16-23, 녹색의 경우 8-15, 파란색의 경우 0-7입니다.
그 외에 class.awt.color는 다음에서 상속된 필드와 함께 작동합니다 Java.awt.Transparency.
  • TRANSLUCENT색상에 알파 값이 포함되어 있고 0과 1의 두 값이 있는지 여부를 나타냅니다.
  • OPAQUE완전한 불투명도를 보장하는 개체에 알파 값 1을 할당합니다.
  • BITMASK절대 불투명도 또는 투명도 값을 나타내며 (0;1) 범위 내에 있습니다. 여기서 0은 완전한 투명도이고 1은 극도의 불투명도입니다.

Java AWT 색상 클래스와 함께 사용하는 상위 15가지 방법

색상을 조작하고 어둡거나 밝기를 조정하기 위해 Java 개발자는 다양한 방법을 사용합니다. 수십 가지가 있으므로 모두 암기할 필요가 없습니다. 그러나 가장 널리 사용되는 Java AWT Color 메서드의 경우 목록을 15개로 좁혔습니다. 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 get알파()

색상의 알파 구성 요소를 반환하려면 이 방법을 사용하십시오. 알파 값은 0-255 범위 내에 있음을 명심하십시오. 다음은 메서드의 적용 및 반환에 대한 예입니다. :

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

정적 색상 getColor(문자열 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 힌트)

이 방법은 복잡해 보이지만 생각보다 조작하기 쉽습니다. 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 메서드입니다. 이 방법은 cspace에 의해 정의된 주어진 것에 적용됩니다 ColorSpace. :

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(float h, float s, float 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.

getGreen()

이 Java 메서드는 생성한 색상의 녹색 구성 요소 값을 반환합니다. 모든 값은 RGB 색 구성표에서 녹색에 해당하는 범위에 맞습니다. :

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

getRed()

와 유사하게 는 getGreen()주어진 getRed색상의 빨간색 구성 요소에 대한 값을 반환합니다. 위의 예에서 메서드가 어떻게 적용되었는지 이미 확인했습니다.

getBlue()

이 메서드는 RGB 색 구성표의 값 범위 내에서 파란색 값을 반환합니다. 마찬가지로 를 사용하는 예는 의 getBlue()설명을 참조하십시오 getGreen().

get알파()

getAlpha() 메서드는 개발자가 주어진 색상의 알파 값을 찾으려고 할 때 Java에서 사용됩니다. RBG와 유사하게 모든 색상의 알파는 0-255 범위 내에 있습니다. getAlpha() : 루프의 일부로 사용된 방법은 다음과 같습니다 .

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

getTransparency()

이 메서드는 사용자 또는 다른 개발자가 색상을 만들 때 색상에 대해 지정한 투명도 값을 반환합니다. :

public int getTransparency() {

return myColor.getTransparency();

부울 같음(객체 obj)

이 방법은 두 가지 색상을 서로 비교할 때 매우 유용합니다. 이를 통해 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) 파란색을 정의하는 데 사용됨
정적 색상 회색(GRAY) 회색 색상을 정의합니다.
정적 색상 짙은 회색(DARK_GRAY) 더 어두운 회색 음영을 정의합니다.
정적 색상 lightGray(LIGHT_GRAY) 더 밝은 회색 음영을 정의합니다.
정적 색상 녹색(GREEN) 녹색을 정의하는 데 사용됨
정적 색상 마젠타(MAGENTA) 자홍색 음영을 정의합니다.
정적 컬러 핑크(PINK) Java에서 분홍색을 정의합니다.
정적 색상 주황색(ORANGE) Java에서 주황색을 만듭니다.
정적 색상 노란색(YELLOW) 노란색을 정의하는 데 사용
정적 색상 빨간색(RED) Java에서 빨간색을 정의합니다.

Java에서 AWT.Color를 사용하기 위한 연습 문제

Java에서 AWT Color의 견고한 기반을 가지고 있다고 느끼십니까? 몇 가지 실제적인 문제를 해결하여 이러한 기술을 테스트해 보겠습니다. 여기서 생성자와 일반적인 메서드는 물론 색상과 관련되지 않은 다른 Java 도구를 적용해야 합니다. 연습 문제 #1 . 프로그램 사용자가 색상의 RGB 수준을 조정할 수 있는 사용자 정의 구성 요소를 만듭니다( 와 유사 RGBColorChooser). 구성 요소에 getColor()를 포함해야 합니다. 구성 요소를 애플릿이 아닌 패널 하위 클래스로 만듭니다. 대답 : 이것은 상당히 복잡한 문제입니다. 관리 가능한 단계로 나누어 보겠습니다.
  1. 구성 요소로 변환합니다 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