位置:首页 > Java技术 > java实例在线教程 > Java在框架中显示颜色

Java在框架中显示颜色

如何在框架中显示的颜色?

解决方法

下面的示例显示了如何使用Image类的一个setRGB方法显示一帧中所有的颜色。

import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Main extends JComponent {
   BufferedImage image;
   public void initialize() {
      int width = getSize().width;
      int height = getSize().height;
      int[] data = new int[width * height];
      int index = 0;
      for (int i = 0; i < height; i++) {
         int red = (i * 255) / (height - 1);
         for (int j = 0; j < width; j++) {
            int green = (j * 255) / (width - 1);
            int blue = 128;
            data[index++] = (red < < 16) | (green < < 8) | blue;
         }
      }
      image = new BufferedImage
      (width, height, BufferedImage.TYPE_INT_RGB);
      image.setRGB(0, 0, width, height, data, 0, width);
   }
   public void paint(Graphics g) {
      if (image == null)
      initialize();
      g.drawImage(image, 0, 0, this);
   }
   public static void main(String[] args) {
      JFrame f = new JFrame("Display Colours");
      f.getContentPane().add(new Main());
      f.setSize(300, 300);
      f.setLocation(100, 100);
      f.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
      f.setVisible(true);
   }
}

结果

上面的代码示例将产生以下结果。

Displays all the colours in a frame.