I am working on an exercise that is asking me to do the following;
Create a GridPane
Set the pane’s horizontal and vertical gap to zero
Set the pane’s grid line visibility to true
Use nested FOR loops to create and add buttons to the pane (loops
starts from 0 to 10)
Each button must be labeled with any number between 0 to 99
Color the buttons based on the following rules:
a. If the color’s label is divisible by 2, then change the color to Blue
b. If the color’s label is divisible by 3, then change the color to
Yellow
c. If the color’s label is divisible by 6, then change the color to Green
Add the pane to a scene
Add the scene to a stage, then display the Stage
I have everything set up, just not sure how to read the value generated by Math.random and do assign a specific color to that button.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.GridPane;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
public class Exercise8GridPane extends Application {
#Override
public void start(Stage primary) {
primary.setTitle("Exercise 8");
GridPane gp = new GridPane();
gp.setHgap(0);
gp.setVgap(0);
gp.setGridLinesVisible(true);
for (int k = 0; k < 10; k++) {
for (int l = 0; l < 10; l++) {
Button btn = new Button(String.valueOf((int)(Math.random() * 100)));
// if / 3 == 0){
btn.setStyle("-fx-base:red;-fx-text-fill:yellow");
gp.add(btn, l, k);
}
}
Scene s = new Scene(gp);
primary.setScene(s);
primary.show();
}
public static void main(String[] args) {
launch(args);
}
}
The java.lang.Math.random() returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.
There are countless ways to read it.
I would recommend doing something like
int RED = (int) (Math.random() * 256);
// Note that Math.random() returns a value less than 1.0
int BLUE = ...
It's difficult to get three values from one number, so I think this will work well.
Related
I am new in processing and java, I have some exercise to display 100 ellipses but the screen size is (900, 600), and I want break 100 in 10 lines of 10, but I don't know how to break line in processing , I already use translate(https://processing.org/reference/translate_.html),but it doesn't work.
//function
void draw(){
smooth();
noStroke();
fill(23,43,208,200);// cor azul
ellipse(posX,posY,12,10);
noStroke();
fill(242,76,39);//cor vermelho
ellipse(posX,posY,12,10);
}
for (int i=1; i<ellipses.length; i++)
{
for (int j=i; j<ellipses.length; j++)
{
if(j%10==0)
ellipses[i].draw();//calling function
}
}
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;
public class T15DrawEllipses extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
Group group = new Group();
Scene scene = new Scene(group, 900, 600);
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
Ellipse e = new Ellipse();
e.setCenterX(44 + col * 90);
e.setCenterY(29 + row * 60);
e.setRadiusX(45);
e.setRadiusY(30);
group.getChildren().add(e);
}
}
primaryStage.setScene(scene);
primaryStage.show();
}
}
A complete example of 10 rows/columns with ellipses.
The best thing you can do when you have questions like this is to get out a piece of graph paper, and draw out a bunch of examples until you notice a pattern. What is the X,Y position of every cirlce you want to draw? What is the X value of the first row, the second row, the third row? What is the Y value of the first column, the second column, the third column?
You should also get into the habit of breaking your problem down into smaller pieces and taking those pieces on one at a time. For example, instead of trying to draw 100 circles in a grid, why don't you just try to draw 10 circles in a single row? Create a function that draws a row of circles. Then try calling that function multiple times to create your grid of circles.
If you get stuck on a specific step, you can ask a more specific question along with a MCVE. Good luck.
I am currently trying to make an 8x8 board and cannot seem to figure out why my rectangle objects are not showing. I am trying to figure out the logic behind one row before I do it multiple times to get the whole board. Below is my current code:
import javafx.application.*;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.TilePane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Board extends Application {
public static void main(String[] args) {
launch();
}
public void start(Stage ps) {
TilePane tp = new TilePane();
Pane p = new Pane();
for (int column = 0; column > 8; column++) {
// This loop is used to determine the center of the rectangle
for (int x = 10; x < 160; x += 20) {
Rectangle r = new Rectangle();
r.setWidth(20);
r.setHeight(20);
r.setX(x);
r.setY(10);
if (column == 0 || column % 2 == 0) {
r.setFill(Color.BLACK);
}
else {
r.setFill(Color.GREY);
}
tp.getChildren().add(r);
}
}
p.getChildren().add(tp);
Scene s = new Scene(p, 160, 160);
ps.setScene(s);
ps.setTitle("PP2 Halma Project");
ps.show();
}
}
for (int column = 0; column > 8; column++) - This will never happen because 0 can never be more than 8.
r.setX(x) - I don't think you would need this. You should let TilePane layout the rectangles for you; you just need to define a size for it.
Pane p = new Pane() - Personally, I think this is redundant. Using just TilePane without it will work just fine. This will not cause your program to bug, though.
I am trying to recursively add ellipses to a pane for homework. I have written what code I believe should work, and while it both compiles and runs, it shows nothing on my pane.For a little background, the ellipses should all be centered in the pane, each should be 10px away from the next ellipse edge, and the outer ellipse should be 10px away from the edge of the pane.
Here is my code
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.*;
import javafx.scene.shape.*;
import java.util.Random;
import javafx.scene.paint.Color;
public class DisplayCircles extends Application {
private static Pane mainPane = new Pane();
public void start(Stage primaryStage) {
double horRadius = (mainPane.getWidth() / 2) - 10;
double vertRadius = (mainPane.getHeight() / 2) - 10;
addCircles(horRadius, vertRadius);
Scene scene = new Scene(mainPane, 500, 500);
primaryStage.setTitle("Circle Display");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* Recursively adds circles to the pane from largest to smallest.
*
* #param horizontal - The starting horizontal radius.
* #param vertical - The starting vertical radius.
*/
public static void addCircles(double horizontal, double vertical) {
if (horizontal <= 10 || vertical <= 10) {
createEllipse(horizontal, vertical);
} else {
createEllipse(horizontal, vertical);
addCircles(horizontal - 10, vertical - 10);
}
}
/**
* Creates an ellipse with the given horizontal and vertical radii.
*
* #param horizontal - The x based radius.
* #param vertical - the y based radius.
*/
private static void createEllipse(double horizontal, double vertical) {
Random rand = new Random();
Ellipse ellipse = new Ellipse(horizontal, vertical);
ellipse.centerXProperty().bind(
mainPane.widthProperty().divide(2.0));
ellipse.centerYProperty().bind(
mainPane.heightProperty().divide(2.0));
double r = rand.nextDouble();
double g = rand.nextDouble();
double b = rand.nextDouble();
double o = rand.nextDouble();
ellipse.setFill(Color.color(r, g, b, o));
mainPane.getChildren().add(ellipse);
}
}
The width and height of the Pane will be 0 until it has been added to a Scene and that Scene has undergone layout. Of course, in this case you know what the initial size of the pane is going to be, so you can do
double width = 500 ;
double height = 500 ;
double horRadius = (width / 2) - 10;
double vertRadius = (height / 2) - 10;
addCircles(horRadius, vertRadius);
Scene scene = new Scene(mainPane, width, height);
Another solution would be to re-compute the graphics when the size of the pane changes. In this solution, the circles are drawn when the pane is first placed in the scene, and then redrawn to fill the pane any time the window resizes. This probably isn't what you want for this application, but might be a useful idea in other cases:
mainPane.boundsInLocalProperty().addListener((obs, oldBounds, newBounds) -> {
mainPane.getChildren().clear();
double horRadius = (mainPane.getWidth() / 2) - 10;
double vertRadius = (mainPane.getHeight() / 2) - 10;
addCircles(horRadius, vertRadius);
});
Scene scene = new Scene(mainPane, 500, 500);
As an aside, why did you make everything static? It doesn't matter too much as only one instance of an Application subclass is ever created, but in general it's bad practice to use static when there's no good design reason to do so.
This is my first program written in JavaFX (as opposed to Swing). I'm starting small by simply displaying data sets in a matrix of buttons (I do not wish to use a Table just yet).
package matrixjavafx;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.util.Random; // required for random number generation
/**
*
* #author Matt
*/
public class MatrixJavaFX extends Application {
Button[][] matrix; //names the grid of buttons
#Override
public void start(Stage primaryStage) {
int SIZE = 10;
int length = SIZE;
int width = SIZE;
StackPane root = new StackPane();
matrix = new Button[width][length]; // allocates the size of the matrix
// runs a for loop and an embedded for loop to create buttons to fill the size of the matrix
// these buttons are then added to the matrix
for(int y = 0; y < length; y++)
{
for(int x = 0; x < width; x++)
{
Random rand = new Random(); // Creates new Random object for generating random numbers
// The following variables are generated using Random object rand.
// rand.nextInt(2) generates a double ranging from 0.000 to 0.999.
// setting the target variable to be an integer truncates the range to 0 - 1.
int rand1 = rand.nextInt(2); // Declare and initialize random integer (0 - 1) + 1
matrix[x][y] = new Button(/*"(" + rand1 + ")"*/); //creates new random binary button
matrix[x][y].setText("(" + rand1 + ")"); // Sets the text inside the matrix
matrix[x][y].setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Random Binary Matrix (JavaFX)");
}
});
root.getChildren().add(matrix[x][y]);
}
}
Scene scene = new Scene(root, 500, 500);
primaryStage.setTitle("Random Binary Matrix (JavaFX)");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
greeting(); // Greets the User and explains the purpose of the program
launch(args); // Opens the window that generates and displays the matrix
//new MatrixSwingGUI(width, length); // makes new MatrixSwing with 2 parameters
thanks(); // Thanks User and indicates that the program is about to close
}
public static void greeting()
{
// Greets the User and displays the program's purpose
System.out.println("Welcome to the Random Matrix Generator\n");
System.out.println("The purpose of this program is to generate and display "
+ "\na 10 x 10 matrix of random 0's, and 1's.");
}
public static void thanks() // Thanks User and indicates that the program is about to close
{
System.out.println("\nGoodbye and Thank You for using the Random Matrix Generator\n\n");
} // End thanks method
}
The heart of the problem seems to be the following line, since by default all of the buttons are stacking on top of each other in the center of the pane.
StackPane root = new StackPane();
That said, I would like the buttons to align side by side for all of length and width, resulting in an n x m matrix. What should be done to accomplish this? What additional javafx.scene.* files need to be imported?
The basic problem is the Layout that you have chosen for the project. You can get an in-depth knowledge about layouts, that javafx support over here
StackPane stacks all the Nodes that you pass it. I would suggest you to use GridPane inplace of StackPane.
GridPane root = new GridPane();
To add the nodes, use
root.add(matrix[x][y], y, x);
P.S. I would also advice you to rename your buttons, to give you more clarity on button representing row's and column's of the matrix. You can use something as, though its totally optional ! :)
matrix[x][y].setText(x + "," + y);
I am having a problem with my java code. I'm trying to make it so the top left quadrant produces a set number of lines input by a user through JOption Pane which are in random colors and in random positions. The programs builds successfully but it does not produce the number of lines the user input, nor does it set a random color (This it at the very bottom of my code). Can someone please explain how to fix this problem? Thanks very much.
Edit: fixed the curve braces but still will not work.
Edit: Everything works now except the random colors
import javax.swing.*; //for JFrame
import java.awt.*; //for Graphics and Container
import java.util.Random;
import javax.swing.JOptionPane;
// other import statements here
public class RandomGraphics
{
// constants are used to draw the grid, and for you to put shapes in the grid
public static final int MIDX = 400;
public static final int MIDY = 300;
public static final int MAXX = 799;
public static final int MAXY = 599;
public static final int COLOR = (int) (Math.random() * 256);
// make another constant for the color value that will
// be used to generate a random color
public static void main( String[] args )throws InterruptedException
{
//*** This next section sets up the graphics window.
//*** You are not required to understand it
Container contentPane;
Graphics g;
JFrame win = new JFrame("Random Graphics");
win.setSize(825,650);
win.setLocation(0,0);
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = win.getContentPane();
contentPane.setBackground(Color.white);
g = contentPane.getGraphics();
Thread.sleep(50);
//*** done setting up graphics window
// Draws Grid - DO NOT CHANGE
// After you use JOptionPane to get the number of lines, you can move this
// section of code to just after that, so the lines will not disappear
g.drawRect(0,0,MAXX+1,MAXY+1);
g.drawLine(0,MIDY,MAXX,MIDY); // horizontal line
g.drawLine(MIDX,0,MIDX,MAXY); // vertical line
// Create Random object
Random r = new Random();
// Top left quadrant:
// Use a JOptionPane to ask the user to enter the number of lines 1 to 100.
int count = 0;
do
{
String morelines = JOptionPane.showInputDialog("Enter a number of lines between 1 to 100");
count = Integer.parseInt(morelines);
}
while(count > 100 || count < 1);
for(int i = 1; i >= count; i++)
{
g.setColor(new Color (r.nextInt(COLOR), r.nextInt(COLOR), r.nextInt(COLOR)));
g.drawLine(r.nextInt(MIDX), r.nextInt(MIDY), r.nextInt(MIDX), r.nextInt(MIDY));
}
g = contentPane.getGraphics();
Graphics objects are not persistent, the programmer needs to draw the GUI to them when asked to do so. For tips, see the Performing Custom Painting Lesson of the tutorial.
Beside the 'always include curly braces around loops advice', note..
for(int i = 1; i >= count; i++)
Should be..
for(int i = 1; i <= count; i++)
But don't ignore the advice about custom painting. The app. will not render reliably until that is fixed.
for(int i = 1; i >= count; i++)
g.setColor(new Color (r.nextInt(COLOR), r.nextInt(COLOR), r.nextInt(COLOR)));
g.drawLine(r.nextInt(MIDX), r.nextInt(MIDY), r.nextInt(MIDX), r.nextInt(MIDY));
Looking at your indenting, it looks like you want g.setColor(...) and g.drawLine(...) to be inside your for loop. You need to enclose them in curly braces {}, otherwise only the statement immediately following your for loop will be inside the loop.