简体   繁体   English

如何在 JPanel 上显示 RGB 值的二维数组?

[英]How do you display a 2d array of RGB values on a JPanel?

I am new to Java and I am wanting to make a basic 3D engine.我是 Java 的新手,我想做一个基本的 3D 引擎。
I want to take an array of colors and display it on the screen.我想获取一组 colors 并将其显示在屏幕上。 Is there a simple and fast way to do this?有没有一种简单快捷的方法来做到这一点?

EDIT编辑

For example, if the array was例如,如果数组是

{{{255, 0, 0}, {255, 0, 0}}, {{255, 0, 0}, {255, 0, 0}}}

It would output a red square 2x2 pixels.它将 output 一个红色正方形 2x2 像素。

Here is a proof of concept (POC).这是概念证明(POC)。

As described in Performing Custom Painting tutorial, you can perform custom painting by writing a class that extends javax.swing.JPanel and overriding its paintComponent method.执行自定义绘画教程中所述,您可以通过编写扩展javax.swing.JPanel并覆盖其paintComponent方法的 class 来执行自定义绘画。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class ColorArr extends JPanel implements Runnable {
    private int[][][] arr = {
                             {
                              {255, 0, 0},
                              {255, 0, 0}
                             },
                             {
                              {255, 0, 0},
                              {255, 0, 0}
                             }
                            };

    public ColorArr() {
        setPreferredSize(new Dimension(50, 50));
    }

    @Override // java.lang.Runnable
    public void run() {
        showGui();
    }

    @Override // javax.swing.JComponent
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int row = 0; row < arr.length; row++) {
            for (int col = 0; col < arr[row].length; col++) {
                Color color = new Color(arr[row][col][0], arr[row][col][1], arr[row][col][2]);
                g.setColor(color);
                g.drawRect(row, col, 1, 1);
            }
        }
    }

    private void showGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(this);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new ColorArr());
    }
}

Here is a screen capture.这是一个屏幕截图。 A two-pixel by two-pixel, red square appears in the top, left corner.一个两像素乘两像素的红色正方形出现在左上角。

正在运行的 Swing 应用程序的屏幕截图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM