Reputation: 60
I am new to Java and I am wanting to make a basic 3D engine.
I want to take an array of colors and display it on the screen. Is there a simple and fast way to do this?
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.
Upvotes: 2
Views: 489
Reputation: 20914
Here is a proof of concept (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.
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.
Upvotes: 2