In my Java class we are working in chapter 4 of the Fundamentals of Java book. I'm doing project 4-11 which is a black and red checkerboard however I'm getting random colors, I'm trying to complete this the way the book teaches us to use ColorPanels and JFrames. Here is my code:
package guiwindow3;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class GUIWindow3 {
public static void main(String[] args) {
//Objects
JFrame theGUI = new JFrame();
//Format GUI
theGUI.setTitle("GUI Example");
theGUI.setSize(500, 500);
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = theGUI.getContentPane();
pane.setLayout(new GridLayout(8, 8));
//Loop for grid
Color lastColor = Color.BLACK;
for(int i = 1; i < 8; i++) {
for(int j = 0; j < 8; j++) {
if((j % 2 == 1 && i %2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
lastColor = Color.RED;
}
else {
lastColor = Color.BLACK;
}
ColorPanel panel = new ColorPanel(lastColor);
pane.add(panel);
}
}
theGUI.setVisible(true);
}
}
Then for the ColorPanel class I have:
import javax.swing.*;
import java.awt.*;
class ColorPanel extends JPanel {
public ColorPanel(Color lastColor) {
setBackground(lastColor);
}
}
The reason you're getting random numbers is because you're creating a random number for each RGB parameter. Instead you could change this:
for (int i = 1; i <= rows * cols; i++) {
int red = gen.nextInt(256); //A random Red
int green = gen.nextInt(256); //A random Green
int blue = gen.nextInt(256); //A random Blue
Color backColor = new Color(red, green, blue); //Join them and you get a random color
ColorPanel panel = new ColorPanel(backColor); //Paint the panel
pane.add(panel);
}
To this:
Color lastColor = Color.BLACK;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if ((j % 2 == 1 && i % 2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
lastColor = Color.RED; //Set the color to RED
} else {
lastColor = Color.BLACK; //Set the color to BLACK
}
ColorPanel panel = new ColorPanel(lastColor); //Paint the panel with RED or BLACK color
pane.add(panel); //Add the painted Panel
}
}
And the output is something like:
Edit
Another way to get the same output and make the if
condition easier to read, is as @dimo414 said in his comment :
if((j % 2 == 1 && i %2 == 1) || (j % 2 == 0 && i % 2 == 0))
is the same asif (j % 2 == i % 2)
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (i % 2 == j % 2) {
lastColor = Color.RED;
} else {
lastColor = Color.BLACK;
}
ColorPanel panel = new ColorPanel(lastColor);
pane.add(panel);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.