How to formulate multiple JLabels that all will follow same procedure? - java

I am working with 100 JLabels aligned in a grid format. 10 x 10.
Each JLabel has a number associated with it. Depending on the value of the number, the JLabel's background will be set. Therefore, an intensity map. The value number are in the same class file, on a different tab (a 10x10 table with numbers).
My concern is that it would take forever to do something like this:
Private JLabel first one....last 100th one
first one = new JLabel("")
if(first one value is value is 5) {setBackground color Red} else if {blue} else if {green}
And so one till the last 100th one.

You're going to want to use an array and a loop to initialize them.
JLabel[][] labels = new JLabel[10][10];
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
labels[i][j] = new JLabel("");
//Do whatever with it here
}
}

Related

How can I set a grid with the value of my 2D array?(Java, Android Studio)

I have a school project, I have to build a Tetris Game.
So I began with the creation of my menu with the different level, when I click on one level i go to my second activity (the game area) and I have also created my custom block.
My problem is a visual issue, indeed I don't know what type of layout I have to use for my surface game (gridlayout, linearlayout, grid etc. ...).
And then how to affect my blocks custom in this surface game, in this layout?
See the result expected.
enter image description here
I'm not sure I understand what you want entirely but ill give it a shot from what i think you mean.
You should use a nested for loop to do it, if your array was int[10,20](not right syntax but i cant be bothered to count the actual size of your array).
you should go:
(pseudocode)
also assume your resolution is 100, 200
For(int i = 1 To 10){
For(int k = 1 To 20){
DrawSquare(i*10, k*10, "block type")
k = k + 1
}
i = i + 1
}
Then it will fill your 100, 200 area with the block type specified. Now if you want to load what block type you want freom the array you can just call the array in the block type.
DrawSquare(i*10, k*10, Array[i,k])
Obviously bear in mind that its all pseudocode to display the logic.
Hope this helps
Building on Valhalla's answer with a Java-specific example, it's still a bit unclear what you're asking, but assuming you want to initialise the grid to begin with you can use this code:
private final int columns = 10;
private final int rows = columns * 2;
private int[][] grid;
private void initialise() {
grid = new int[columns][rows];
for (int i = 0; i < columns; i++) {
for(int j = 0; j < rows; j++) {
grid[i][j] = 0;
}
}
}
And assuming that you have a block that starts at the top, and falls one square with each iteration provided there's nothing underneath, you can try this:
private void blockFall() {
// Start from 1 row above the bottom and parse upwards
// so a block won't drop right to the bottom on a single iteration
for (int i = 0; i < columns; i++) {
for(int j = rows - 2; j >= 0; j--) {
if (grid[i][j] > 0 && grid[i][j+1] == 0) {
grid[i][j+1] = grid[i][j];
grid[i][j] = 0;
}
}
}
}

Creating multiple objects "x" distance away from each other

I am trying to finish my code for an assignment I have, but I'm stuck on the last component. I need to create "stars" (small yellow square objects) in the "sky"... a grid of 5 rows of 10 stars. I am in a beginner java class, and I am supposed to being using methods such as star.moveHorizontal() or star.moveVertical(). All of the relevant posts I've searched for have been too complex or out of my comprehension.
I think that I would need to create an array? We haven't even covered that in class... And then have each "star" be x distance (the first star) + 30 units to the right. Then t continue that trend until there are 10 stars in a row. And then get four more rows of 10 stars.
Here is the code I've create for just one star (in the upper left of my window):
Square s1 = new Square();
s1.makeVisible();
s1.changeColor("yellow");
s1.changeSize(5);
s1.moveVertical(-100);
s1.moveHorizontal(-270);
Then I tried to create an array for a square class... I honestly have no idea if that's even legal.
Square[] starArray = new Square[10];
for ( int i=0; i<starArray.length; i++) {
starArray[i] = new Square();
But then I don't understand how I can call each star and make them appear... Please help. I feel so out of my depth. I've tried to research this and try new things for over 2.5 hours now. I will answer any questions you have to the best of my ability. Thank you
If you can make a single star appear and haven't learned about arrays yet, I don't think that is the answer your teacher is looking for. The point of an array is to be a container so you can reference the objects again. If you don't need to go back to the stars in the future, just create them and set their values in a loop.
// Set defaults for spacing and start positions
int horizontalStartPosition = 10;
int horizontalSpacing = 30;
int verticalStartPosition = 10;
int verticalSpacing = 30;
// Outer loop creates the 4 rows
for (int i = 0; i < 4; i++) {
// Inner loop creates each row
for (int j = 0; j < 10; j++) {
// Create the next star in the row
Square s = new Square();
s.makeVisible();
s.changeColor("yellow");
s.changeSize(5);
// Move the star to the correct vertical position for the current row
s.moveVertical(verticalStartPosition + i * verticalSpacing);
// Move the star to the correct horizontal spacing for the next star
s.moveHorizontal(horizontalStartPosition + j * horizontalSpacing);
}
}
You're on the right track. You can use a 2D array with 5 rows and 10 columns. Try something like this:
int numColumns = 10; //the number of columns in the array
int numRows = 5; // the number of rows in the array
Square[][] starArray = new Square[numRows][numColumns]; // the array itself
final int DIST_X = 10; //the distance between columns (use final because this value should not change)
final int DIST_Y = 10; // the distance between rows (use final because this value should not change)
int y = 0; // the initial row's vertical displacement
for ( int i=0; i<numRows; i++) {
int x = 0; // the initial columns horizontal displacement
for ( int j=0; j<numColumns; j++) {
starArray[i][j] = new Square(); //define the square
starArray[i][j].moveHorizontal(x); // move it x units horizontally
starArray[i][j].moveVertical(y); // move it y units vertically
starArray[i][j].makeVisible(); //show the square
x += DIST_X; //update your horizontal displacement so the next column shows up in the correct position
}
y += DIST_Y; //update your vertical displacement so the next row shows up in the correct position
}
Based on what I understand, you would want to call a method which would basically place a star in the grid for you.
I am not fully sure of what you mean, but here is what I can offer you:
You'll want to create a method for placing a star.
private static int X_SPACING = 30;
private static int Y_SPACING = 20;
public Square placeStar(int x, int y){
// This is the same code that you had before.
Square sq = new Square();
sq.changeColor("yellow");
sq.changeSize(5);
sq.moveVertical(-y); // Where Y is the distance from the TOP LEFT.
sq.moveHorizontal(-x);
return sq;
}
public ArrayList<Square> makeRow(int columnsAmount, int y, int startX){
ArrayList<Square> squares = new ArrayList<>();
for(int i = 0; i < columnsAmount; i++)
squares.add(placeStar(startX + (X_SPACING * i), y));
return squares;
}
public ArrayList<Square> makeGrid(int rowsAmount, int columnsAmount){
ArrayList<Square> rslt = new ArrayList<>();
for(int i = 0; i < rowsAmount; i++)
rslt.addAll(makeRow(columnsAmount, (i * Y_SPACING), 0);
return rslt;
}
Basically, calling "makeRow" should create a row of [rowsAmount] stars, which are all separated by [X_SPACING] pixels.
Then, makeGrid will call makeRow multiple times adjusting [y], and this will make you a grid. Feel free to adjust any value in the code.
EDIT: I've added a makeGrid function, and changed a few variables in the makeRow as I mistyped them. I made the functions return an ArrayList, but you shouldn't need them, only if your teachers later ask to modify them later, or something.
I hope this helps, don't hesitate to ask more questions.
Sneling.

How can I remove a given number of elements from an array?

I have a JLabel array that starts with an integer number of elements. How can I remove an certain number of elements from the array? For example, every time the int is updated:
int i = 21;
i = i - removedElements
How can I update the array to contain that many elements, instead of creating an entirely new array with the desired number of elements?
As others have already mentioned, List is the way to go here since it is specifically designed for adding and or deleting elements.
However if you would prefer to use the JLabel Array you already have in established then you will need to realize that the only way to delete an element from that array is to actually create another array with the desired element to delete excluded from it then return it into the original array. Below I have supplied a simple method named deleteJLabelFromArray() that can do this for you:
public static JLabel[] deleteJLabelFromArray(JLabel[] srcArray, int... indexesToDelete) {
int counter = 0;
JLabel[] newArray = new JLabel[srcArray.length - indexesToDelete.length];
for (int i = 0; i < srcArray.length; i++) {
boolean noGo = false;
for (int j = 0; j < indexesToDelete.length; j++) {
if (i == indexesToDelete[j]) { noGo = true; break; }
}
if (noGo == false) { newArray[counter] = srcArray[i]; counter++; }
}
return newArray;
}
With this method you can delete whatever indexes you supply within the indexesToDelete argument (delimited with a comma). Copy/Paste the code into your project then you can use it something like this:
JLabel[] jla = {jLabel2,jLabel3,jLabel4,jLabel5};
jla = deleteJLabelFromArray(jla, 2);
for (int i = 0; i < jla.length; i++) {
System.out.println(jla[i]);
}
In this example we are going to delete the element number 2 (remember that arrays are 0 based) and therefore jLabel4 would be removed from the Array.
Keep in mind that this would be scary stuff with really big arrays.
Hope this helps.

Formula to draw pyramid of circles

I'm trying to create a pyramid of circles to my game, looking similar to this :
alt text http://img266.imageshack.us/img266/3094/lab1213c.jpg
But I can't make it print properly. Constantly I'm getting really strange spirals but nothing close to this. Can anyone give me some tip on proper formula ? My window is 600x600, base of pyramid is 8 .
fields = new Field[BASE*(BASE/2)+4];
int line_count = BASE;
int line_tmp = line_count;
for(int i=0; i< fields.length; i++){
for( int j=line_tmp; j <= line_count; j++){
fields[i] = new Field(0, (150+(line_tmp*5)),(600+line_tmp*5));
}
line_count--;
line_tmp = line_count;
}
The mistakes I see are:
Incorrect array size formula.
Including line_tmp (which seems to be your column counter) in your y expression.
Having two variables, line_count and line_temp that are always equal.
Having your outer loop count by node rather than counting by row.
Having generally meaningless variable names and magic numbers strewn about.
// I use java.util.ArrayList because using its add(..) method is convenient here.
// The proper forumula for anticipated number of nodes is: base×(base+1)÷2
final List<Field> fields = new ArrayList<Field>(BASE*(BASE+1)/2);
// I use a java.awt.Point to store the (x,y) value of the first node of the row.
// This clarifies the meaning, rather than using ints or long inline expressions.
final Point rowStart = new Point(PANEL_WIDTH/2, DIAMETER);
// The number of rows equals the number of nodes on the final row.
for (int row = 1; row <= BASE; row++) {
// The nth row has n nodes.
for (int circle = 0; circle < row; circle++) {
// Each row starts at rowStart and each subsequent circle is offset to
// the right by two times the circle diameter.
fields.add(new Field(0, rowStart.x + circle*DIAMETER*2, rowStart.y));
}
// Each subsequent row starts a little down and to the left of the previous.
rowStart.x -= DIAMETER;
rowStart.y += DIAMETER;
}
Remember to only use this as reference for fixing your own code if this is homework.

java nested for() loop throws ArrayIndexOutOfBoundsException

I'm working through a JPanel exercise in a Java book. I'm tasked with creating a 5x4 grid using GridLayout.
When I loop through the container to add panels and buttons, the first add() throws the OOB exception. What am I doing wrong?
package mineField;
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class MineField extends JFrame {
private final int WIDTH = 250;
private final int HEIGHT = 120;
private final int MAX_ROWS = 5;
private final int MAX_COLUMNS = 4;
public MineField() {
super("Minefield");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container mineFieldGrid = getContentPane();
mineFieldGrid.setLayout(new GridLayout(MAX_ROWS, MAX_COLUMNS));
// loop through arrays, add panels, then add buttons to panels.
for (int i = 0; i < MAX_ROWS; i++) {
JPanel[] rows = new JPanel[i];
mineFieldGrid.add(rows[i], rows[i].getName());
rows[i].setBackground(Color.blue);
for (int j = 0; j < MAX_COLUMNS; j++) {
JButton[] buttons = new JButton[i];
rows[i].add(buttons[j], buttons[j].getName());
}
}
mineFieldGrid.setSize(WIDTH, HEIGHT);
mineFieldGrid.setVisible(true);
}
public int setRandomBomb(Container con)
{
int bombID;
bombID = (int) (Math.random() * con.getComponentCount());
return bombID;
}
/**
* #param args
*/
public static void main(String[] args) {
//int randomBomb;
//JButton bombLocation;
MineField minePanel = new MineField();
//minePanel[randomBomb] = minePanel.setRandomBomb(minePanel);
}
}
I'm sure I'm over-engineering a simple nested for loop. Since I'm new to Java, please be kind. I'm sure I'll return the favor some day.
JPanel[] rows = new JPanel[i];
i is 0 in the first iteration, which isn't what you want. Make that:
JPanel[] rows = new JPanel[MAX_ROWS];
Also, I think you want to take that completely outside the for loop, since you seem to be using its elements, which would be uninitialised...
This is also wrong:
JButton[] buttons = new JButton[i];
i can be 0 when j is 2 for example, in which case there's no such thing as a buttons[j]. Make them all MAX_* and I think you want to take them out of the loop, since I don't see the point in recreating them at every iteration. Also, you need to instantiate the individual array elements as well.
This part doesn't really make sense:
for (int j = 0; j < MAX_COLUMNS; j++) {
JButton[] buttons = new JButton[i];
rows[i].add(buttons[j], buttons[j].getName());
}
You're creating an array of i JButtons, and trying to add the jth to rows, which makes little sense and won't work if j >= i. You probably meant to do:
JButton[] buttons = new JButton[MAX_COLUMNS];
for (int j = 0; j < MAX_COLUMNS; j++) {
rows[i].add(buttons[j], buttons[j].getName());
}
But the array still doesn't contain any buttons, all you did is initialize it. There's really no reason for the array at all; this actually works:
for (int j = 0; j < MAX_COLUMNS; j++) {
JButton button = new JButton("foo");
rows[i].add(button, button.getName());
}
JPanel[] rows = new JPanel[i];
When i is 0, you create an array with 0 elements. You then try to access that array, but it has no elements in it.
The problem is that your button array is of size i, but j can be larger than i. For instance, the first time through, you are making an empty array here:
JButton[] buttons = new JButton[i];
because i is equal to 0. You then attempt to access it at index 0, which doesn't exist (since the array has no size) and you get your exception. Should you instead be doing something like:
JButton[] buttons = new JButton[MAX_COLUMNS];
That way you will have a button for each array location. Also, you will probably need to initialize the individual buttons - i.e. something like this:
for (int k = 0; k < MAX_COLUMNS; k++) {
buttons[k] = new JButton();
}
(disclaimer: code not tested, but pulled out of you-know-where for example purposes only. There could be typos or unseen bugs.)
Good luck.
It looks like you're creating way too many arrays. You're creating your arrays INSIDE the loops, so instead of creating 5 rows, you're creating 5 rows 5 times, or 25 rows.
The other problem is that you aren't actually creating any objects, only the array to hold the objects. For each object in your array, you need another "button[j] = new JButton()" line.

Categories

Resources