Set red 2d array values using for loop - java

I am trying to create a method that will get all of the red values in an image and display only the red values. I am having trouble with my getRedImage() method. I am new to this and any help would be much appreciated!
public class SimpleRGB
{
private int width, height;
private int[][] red = new int[1000][1000];
This part gets the red value and sets it to the specified position of my 2D red array:
public void setRed(int x, int y, int aRed)
{
red[x][y] = aRed;
}
This part gets the red value at coordinate (x,y) and returns it:
public int getRed(int x, int y)
{
int thisr = red[x][y];
return thisr;
}
I am unsure of how to phrase this part. I know I need to create a new SimpleRGB object to return, and then use nested for-loops to set the red 2D array of my new simple RGB oject to the red 2D array of this simpleRGB object, and then use a nested for loop to set both the green and blue 2D array values to all zero. I am just unsure of how to do this.
public SimpleRGB getRedImage()
{
// This is where I am confused.
}
}

Looping in 2d array is easy
But i don't think this is the right way.
private int[][] red = new int[1000][1000];
for (int i = 0; i < 1000; i++) {
for(int j = 0; j < 1000; j++) {
System.out.println(red[i][j]);
}
}

I did not understand very well your question, but, if you have 3 2D arrays, one for each RGB:
int[][] red = new int[1000][1000];
int[][] green = new int[1000][1000];
int[][] blue = new int[1000][1000];
and you only want the red color in the image, just set to zero all other colors:
public class SimpleRGB
{
private int width;
private int height;
private int[][] red = new int[1000][1000];
private int[][] green = new int[1000][1000];
private int[][] blue = new int[1000][1000];
public SimpleRGB(int[][] red, int[][] green, int[][] blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
// some methods
public int[][] getRed() {
return red;
}
public int[][] getGreen() {
return green;
}
public int[][] getBlue() {
return blue;
}
// the method that interests you
public SimpleRGB getRedImage() {
return new SimpleRGB(red, new int[1000][1000], new int[1000][1000]);
}
}
Creating a new array, all its elements are initialized by default to 0.

I finally figured it out:
public SimpleRGB getRedImage()
{
SimpleRGB redImage = new SimpleRGB(width, height);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
redImage.setRed(i, j, getRed(i, j));
redImage.setGreen(i, j, getGreen(i, j, 0);
redImage.setBlue(i, j, getBlue(i, j, 0));
}
}
return redImage;
}
I had the basic structure correct but I was altering THIS red/green/blue instead of adding redImage.setRed to modify the NEW object.

Related

JLabel set Color from an int array

I'm trying to set a bunch of JLabels to colors from an int Array, but i'm not sure what would be the best way to do it.
This is what i got:
private JLabel[][] board = new JLabel[7][7];
private int[][] charA = {{Color.BLUE,Color.BLUE,Color.BLUE,Color.WHITE,Color.BLUE,Color.BLUE,Color.BLUE},
{Color.BLUE,Color.BLUE,Color.WHITE,Color.BLUE,Color.WHITE,Color.BLUE,Color.BLUE},
{Color.BLUE,Color.BLUE,Color.WHITE,Color.BLUE,Color.WHITE,Color.BLUE,Color.BLUE},
{Color.BLUE,Color.BLUE,Color.WHITE,Color.WHITE,Color.WHITE,Color.BLUE,Color.BLUE},
{Color.BLUE,Color.WHITE,Color.BLUE,Color.BLUE,Color.BLUE,Color.WHITE,Color.BLUE},
{Color.BLUE,Color.WHITE,Color.BLUE,Color.BLUE,Color.BLUE,Color.WHITE,Color.BLUE},
{Color.BLUE,Color.WHITE,Color.BLUE,Color.BLUE,Color.BLUE,Color.WHITE,Color.BLUE}};
public void setArray(){
for(int row=0; row<board.length;row++){
for(int col=0; col<board[row].length;col++){
board[row][col].setForeground(charA[row][col]);
//setForeground gives error: The method setForeground(Color) in
//the type JComponent is not applicable for the arguments (int)
}
}
}

Rotating a String or char clockwise by 90 degrees

Folks, I'm having a really hard time with rotating a Shape clockwise by 90 degrees. I'm having troubles with completing it. If there is a shape:
.t.
ttt
The method rotateBy90() rotates the above shape by 90 degrees clockwise, so it'll be the following output:
t.
tt
t.
THe shapes are of a String type.
Here what I have and Im pretty sure Im completely doing it wrong. The method can be done by using either char[][], or char[], or String[], or String[][]. Another issue is that rotateBy90() is a void method. COuld smb please help me with this rotation algorithm? Thanks in advance!
import java.util.*;
public class CreateShape {
private int height;
private int width;
private char dc;
private Rotation initialPos;
private Rotation nextPos;
private char[][] shape = new char[height][width];
String[] shapeLayout = new String[height];
String[] rotatedArray;
public CreateShape(int height, int width, char dc)
{
this.height = height;
this.width = width;
this.dc = dc;
initialPos = Rotation.CW0;
}
public void rotateBy90()
{
nextPos = initialPos.next();
String newLayout = "";
int count = 0;
String[] newMatrixColumns= shape.split("\n");
while (count < shape.split("\n")[0].length()) {
for (int i = newMatrixColumns.length - 1; i > -1; i--) {
newLayout += newMatrixColumns[i].charAt(count);
}
newLayout = newLayout + "\n";
count++;
}
}
I don't quite get your approach and where your difficulties lie. I also don't get why you have so many unused fields. You may want to set your width and height fields final, as they shouldn't really change in this case.
Personally I think by far the easiest is to use a char[][]. All you have to do then is iterate your initial char[][] and place the element at the appropriate place in your new char[][]. So in your method you'd have something like
public void rotateBy90()
{
// bla bla
char[][] tempShape = new char[width][height];
for(int j = 0; j < width; j++) {
for(int i = 0; i < height; i++) {
tempShape[...][...] = myShape[i][j]; //I'll leave this as exercise
}
}
myShape = tempShape;
}
Word of caution: be careful with strings. Many string operations involve creating other strings (split, substring, concatenation etc). If you do them in a long loop, you may run out of memory fairly quickly.

Slow map in java

I'm making a game in java, is a rpg, however, only with the map the game is slow.
The map is made ​​in TiledMap Editor, therefore, an XML that is read and loaded into an ArrayList. My PC is a dual-core 3.0, 4GB RAM, 1GB Video.
The do the rendering is done as follows:
//method of tileset class
public void loadTileset(){
positions = new int[1 + tilesX * tilesY][2];
int yy = 0;
int xx = 0;
int index = 0;
// save the initial x and y point of each tile in an array named positions
// positions[tileNumber] [0] - X position
// positions[tileNumber] [1] - Y position
for(int i = 1 ; i < positions.length; i++){
if(index == tilesX ){
yy += tileHeight;
xx = 0;
index = 0;
}
positions[i][0] = xx;
positions[i][1] = yy;
xx += tileWidth;
index++;
}
}
//method of map class
public void draw(Graphics2D screen){
//x and y position of each tile on the screen
int x = 0; int y = 0;
for(int j = 0; j < 20 ; j++){
for(int i = initialTile ; i < initialTile + quantTiles ; i++){
int tile = map[j][i];
if(tile != 0){
screen.drawImage(tileSet.getTileImage().getSubimage(tileSet.getTileX(tile), tileSet.getTileY(tile),tileSet.getTileWidth(), tileSet.getTileHeight()),x,y,null);
}
x += tileSet.getTileWidth();
}
x = 0;
y += tileSet.getTileHeight();
}
}
Am I doing something wrong?
Note: I'm new to the forum and to make matters worse I do not understand very much English, so excuse any mistake.
First of all, you should not create the subimages for the tiles during each call. Strictly speaking, you should not call getSubimage at all for images that you want to paint: It will make the image "unmanaged", and this can degrade rendering performance by an order of magnitude. You should only call getSubimage for images that you do not want to render - for example, when you are initially creating individual images for the tiles.
You obviously already have a TileSet class. You could add a bit of functionality to this class so that you can directly access images for the tiles.
Your current code looks like this:
screen.drawImage(
tileSet.getTileImage().getSubimage(
tileSet.getTileX(tile),
tileSet.getTileY(tile),
tileSet.getTileWidth(),
tileSet.getTileHeight()),
x,y,null);
You could change it to look like this:
screen.drawImage(tileSet.getTileImage(tile), x,y,null);
The getTileImage(int tile) method suggested here could then obtain tiles that have been stored internally.
I'll sketch a few lines of code from the tip of my head, you'll probably be able to transfer this into your TileSet class:
class TileSet
{
private Map<Integer, BufferedImage> tileImages;
TileSet()
{
....
prepareTileImages();
}
private void prepareTileImages()
{
tileImages = new HashMap<Integer, BufferedImage>();
for (int tile : allPossibleTileValuesThatMayBeInTheMap)
{
// These are the tiles that you originally rendered
// in your "draw"-Method
BufferedImage image =
getTileImage().getSubimage(
getTileX(tile),
getTileY(tile),
getTileWidth(),
getTileHeight());
// Create a new, managed copy of the image,
// and store it in the map
BufferedImage managedImage = convertToARGB(image);
tileImages.put(tile, managedImage);
}
}
private static BufferedImage convertToARGB(BufferedImage image)
{
BufferedImage newImage = new BufferedImage(
image.getWidth(), image.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return newImage;
}
// This is the new method: For a given "tile" value
// that you found at map[x][y], this returns the
// appropriate tile:
public BufferedImage getTileImage(int tile)
{
return tileImages.get(tile);
}
}

Java GUI program to convert 2D array value into graphic [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am a beginner in Java & i have to make a java program that takes the input from a 2d array with dimensions 347*697 (array's value range from 2200 to 4200 ). I have to do such that for every 100 increase in range there is a set of specific color(for e.g 2200-2300 color(214,217,223) & so on). I have never done anything .. & this is the program i found little bit similar ... Can anyone give me idea how to convert it
I know its too much to ask for , but tomorrow i have to give a ppt. & when every option is closed i came here. Please guys, I need help badly
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Map extends JPanel {
public static final Color CITY = new Color(214,217,223);
public static final Color DESERT = new Color(255,204,102);
public static final Color DIRT_ROAD = new Color(153,102,0);
public static final Color FOREST = new Color(0,102,0);
public static final Color HILLS = new Color(51,153,0);
public static final Color LAKE = new Color(0,153,153);
public static final Color MOUNTAINS = new Color(102,102,255);
public static final Color OCEAN = new Color(0,0,153);
public static final Color PAVED_ROAD = new Color(51,51,0);
public static final Color PLAINS = new Color(102,153,0);
public static final Color[] TERRAIN = {
CITY,
DESERT,
DIRT_ROAD,
FOREST,
HILLS,
LAKE,
MOUNTAINS,
OCEAN,
PAVED_ROAD,
PLAINS
};
public static final int NUM_ROWS = 215;
public static final int NUM_COLS = 300;
public static final int PREFERRED_GRID_SIZE_PIXELS = 10;
// In reality you will probably want a class here to represent a map tile,
// which will include things like dimensions, color, properties in the
// game world. Keeping simple just to illustrate.
private final Color[][] terrainGrid;
public Map(){
this.terrainGrid = new Color[NUM_ROWS][NUM_COLS];
Random r = new Random();
// Randomize the terrain
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
int randomTerrainIndex = r.nextInt(TERRAIN.length);
Color randomColor = TERRAIN[randomTerrainIndex];
this.terrainGrid[i][j] = randomColor;
}
}
int preferredWidth = NUM_COLS * PREFERRED_GRID_SIZE_PIXELS;
int preferredHeight = NUM_ROWS * PREFERRED_GRID_SIZE_PIXELS;
setPreferredSize(new Dimension(preferredWidth, preferredHeight));
}
#Override
public void paintComponent(Graphics g) {
// Important to call super class method
super.paintComponent(g);
// Clear the board
g.clearRect(0, 0, getWidth(), getHeight());
// Draw the grid
int rectWidth = getWidth() / NUM_COLS;
int rectHeight = getHeight() / NUM_ROWS;
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
// Upper left corner of this terrain rect
int x = i * rectWidth;
int y = j * rectHeight;
Color terrainColor = terrainGrid[i][j];
g.setColor(terrainColor);
g.fillRect(x, y, rectWidth, rectHeight);
}
}
}
public static void main(String[] args) {
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Game");
Map map = new Map();
frame.add(map);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
Create a byte[] with the rgb values for each pixel of the image you want. The byte[] length will be width * height * 3 (3 values for each pixel). Look at this for an example of how create a BufferedImage from the byte[].
Another alternative is to create a BufferedImage and set the rgb value for each pixel directly. In this case, you have to bit twiddle all 3 rgb values into a single int value.

Creating a color array with distinct colors

I'm trying to create an array which includes separate distinct colors. Color array will created automatically when the range 'n' given. It's something as following:
variable n = 2;
colourarrray = [red,green];
variable n = 4;
colourarrray = [red,green,blue,yellow];
What is the easiest method to generate such a color array?
An enum. Because it is scalable.
public enum Colors
{
BLACK(255, 255, 255),
WHITE(0, 0, 0);
private int red;
private int green;
private int blue;
private Colors(final int red, final int green, final int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
}
public int red()
{
return red;
}
public int green()
{
return green;
}
public int blue()
{
return blue;
}
}
Then dinamically add them to a List<Colors> as you need them.
Since you didn't put any specification, additional infos or anything to your question and I have nothing better to do right now:
private java.util.Random rnd = new java.util.Random();
public java.awt.Color[] getColors(int num) {
java.util.List<java.awt.Color> colors = new java.util.ArrayList<>(num);
int i = 0;
while (i++ < num) {
colors.add(new java.awt.Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255), 100));
}
java.awt.Color[] array = colors.toArray(new java.awt.Color[num]);
return array;
}

Categories