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)
}
}
}
Related
Say I have created a custom object, Tile, like so
public class Tile {
String name;
int color;
public Tile(String n, int c){
name = n;
color = c;
}
}
and I create an array of these Tile objects
Tile[][] board = new Tile[8][8];
how would I be able to give each Tile a name and color? What syntax would I use in order to give the Tile at board[0][0] the name "A1" and the color 255? Thank you.
While Tile[][] board = new Tile[8][8]; creates a 2D array of tiles, it does not create the tiles themselves.
You can add tiles individually like:
Tile[][] board = new Tile[8][8];
board[0][0] = new Tile("A1", 255);
If you want to fill the board with tiles, try using a nested loop:
Tile[][] board = new Tile[8][8];
int counter = 0;
for( int row = 0; row < board.length; row++ ) {
for( int column = 0; column < board[row].length; column++ ) {
board[row][column] = new Tile("A" + counter++, 255);
}
}
The code above would fill in the board giving the tiles unique names ("A0", "A1", etc...).
If you want to change the name of a tile in the board after it has been added, you can access it like board[0][0].name = "A1"; (Same for the color value). Another way you could change the values is by adding a setter method in the Tile class.
I posted this question a bit earlier and was told to make it SSCCE so here goes (if I can make any improvements feel free to let me know):
I'm wondering why when my button "confirm" is clicked the old squares disappear and the redrawn squares do not appear on my GUI (made with swing). The Squares class draws 200 spaced out squares with an ID (0, 1, 2, or 3 as String) inside obtained from a different class (for the purpose of this question, let's assume it is always 0 and not include that class). For clarification: Squares draws everything perfectly the first time (also retrieves the correct IDs), but I want it to redraw everything once the button is clicked with new IDs.
Code for Squares:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
public class Squares extends JPanel{
private ArrayList<Rectangle> squares = new ArrayList<Rectangle>();
private String stringID = "0";
public void addSquare(int x, int y, int width, int height, int ID) {
Rectangle rect = new Rectangle(x, y, width, height);
squares.add(rect);
stringID = Integer.toString(ID);
if(ID == 0){
stringID = "";
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
FontMetrics fm = g2.getFontMetrics();
int fontAscent = fm.getAscent();
g2.setClip(new Rectangle(0,0,Integer.MAX_VALUE,Integer.MAX_VALUE));
for (Rectangle rect : squares) {
g2.drawString(stringID, rect.x + 7, rect.y + 2 + fontAscent);
g2.draw(rect);
}
}
}
Code for GUI:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIReserver extends JFrame implements Runnable{
private int myID;
private JButton confirm = new JButton("Check Availability and Confirm Reservation");
private JFrame GUI = new JFrame();
private Squares square;
public GUIReserver(int i) {
this.myID = i;
}
#Override
public void run() {
int rows = 50;
int seatsInRow = 4;
confirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
GUI.getContentPane().remove(square);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this does not show up at all (could be that it wasn't drawn, could be that it is out of view etc...)
GUI.repaint(); //the line in question
}
});
GUI.setLayout(new FlowLayout());
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setLocation(0,0);
GUI.setExtendedState(JFrame.MAXIMIZED_BOTH);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this shows up the way I wish
GUI.add(confirm);
GUI.pack();
GUI.setVisible(true);
}
}
Code for main:
public class AircraftSeatReservation {
static AircraftSeatReservation me = new AircraftSeatReservation();
private final int rows = 50;
private final int seatsInRow = 4;
private int seatsAvailable = rows * seatsInRow;
private Thread t3;
public static void main(String[] args) {
GUIReserver GR1 = new GUIReserver(3);
me.t3 = new Thread(GR1);
me.t3.start();
}
}
One major problem: Your Squares JPanels preferred size is only 20 by 20, and will likely actually be that size since it seems to be added to a FlowLayout-using container. Next you seem to be drawing at locations that are well beyond the bounds of this component, and so the drawings likely will never be seen. Consider allowing your Squares objects to be larger, and make sure to only draw within the bounds of this component.
Note also there is code that doesn't make sense, including:
private int myID;
private JTextField row, column, instru draft saved // ???
package question2;ction1, instruction2, seatLabel, rowLabel; // ???
I'm guessing that it's
private int myID;
private JTextField row, column, instruction1, instruction2, seatLabel, rowLabel;
And this won't compile for us:
int rows = AircraftSeatReservation.getRows();
int seatsInRow = AircraftSeatReservation.getSeatsInRow(); // and shouldn't this take an int row parameter?
since we don't have your AircraftSeatReservation class (hopefully you don't really have static methods in that class).
And we can't compile or run your current code. We don't want to see your whole program, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem. So as Andrew Thompson recommends, for better help, please create and post your Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
I would try to OOP-ify your problem as much as possible, to allow you to divide and conquer. This could involve:
Creating a SeatClass enum, one with possibly two elements, FIRST and COACH.
Creating a non-GUI Seat class, one with several fields including possibly: int row, char seat ( such as A, B, C, D, E, F), a SeatClass field to see if it is a first class seat or coach, and a boolean reserved field that is only true if the seat is reserved.
This class would also have a getId() method that returns a String concatenation of the row number and the seat char.
Creating a non-GUI Airplane class, one that holds two arrays of Seats, one for SeatClass.FIRST or first-class seats, and one for SeatClass.COACH.
It would also have a row count field and a seat count (column count) field.
After creating all these, then work on your GUI classes.
I'd create a GUI class for Seats, perhaps GuiSeat, have it contain a Seat object, perhaps have it extend JPanel, allow it to display its own id String that it gets from its contained Seat object, have it override getBackground(...) so that it's color will depend on whether the seat is reserved or not.
etc.....
This code is the relevant portion of my program, and it produces an array out of bounds error, and I can't figure out why.
My error is 'java.lang.ArrayIndexOutOfBoundsException: 6', with 6 being a random value, at the if statement in randomShot();
public class Ai
{
private int WIDTH;
private int HEIGHT;
public Ai(){
WIDTH=10;
HEIGHT=10;
}
int[][] board=new int[WIDTH][HEIGHT];
Random rand = new Random();
public void randomShot(){
x=rand.nextInt(WIDTH/2);
y=rand.nextInt(HEIGHT);
x=x*2;
if(y%2==0)
{
y+=1;
}
if(board[x][y]!=0) //java.lang.ArrayIndexOutOfBoundsException: 6
{
randomShot();
}
}
I have noticed that if I use the code
int[][] board=new int[10][10];
it works perfectly fine. I can't see why this is happening, it's doing exactly the same thing?
WIDTH and HEIGHT are 0 when you are defining board.
Constructor is called after class level variables. For int, the default value is 0.
Move your board initialization into the constructor. The order of field initializations means the array is declared (and initialized) before the constructor is entered (and thus, the WIDTH and HEIGHT are zero).
private int WIDTH;
private int HEIGHT;
public Ai(){
WIDTH=10;
HEIGHT=10;
board=new int[WIDTH][HEIGHT]; // <-- here.
}
int[][] board; // =new int[WIDTH][HEIGHT];
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.
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.