Java如何在框架中顯示顏色?

2019-10-16 22:27:02

在Java的GUI程式設計中,如何在框架(Frame)中顯示顏色?

以下範例顯示如何使用Image類的setRGB()方法顯示框架(Frame)中的所有顏色。

package com.yiibai;

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 DisplayFrameColor 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 DisplayFrameColor());
        f.setSize(300, 300);
        f.setLocation(100, 100);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        f.setVisible(true);
    }
}

上述程式碼範例將產生以下結果。

範例-2

以下是在框架中顯示顏色的另一個範例。

package com.yiibai;

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class DisplayFrameColor2 { 
   public static void main(String[] args) { 
      SwingUtilities.invokeLater(new Runnable() { 
         public void run() { 
            displayJFrame();
         } 
      }); 
   } 
   static void displayJFrame() { 
      JFrame frame = new JFrame("Tw511.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setBackground(Color.red);
      frame.setPreferredSize(new Dimension(400, 400));
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}