How to center a LabelField with large font - java

I need to horizontally center a LabelField using a vertical field manager. I also need to increase the size of the font of this LabelField. I find that, once I center it using FIELD_HCENTER, if I change the size of the font, it changes the position of the field.
This is the code
VerticalFieldManager vfm = new VerticalFieldManager(Field.FIELD_VCENTER | Manager.USE_ALL_WIDTH);
LabelField title = new LabelField("My Title",Field.FIELD_HCENTER) ;
title.setFont(Font.getDefault().derive(Font.BOLD, 18, Ui.UNITS_pt);
vfm.add(title);
(If I remove the third line, title.setFont, then the title is centered, otherwise, it's not). I need some help to get a solution for this.
Any help is appreciated?
Thanks

You can create a Custom FieldManger by overriding sublayout method of VerticalFieldManager, which will place it's child in center. Following one is such an implementaion.
class CustomVerticalFieldManger extends VerticalFieldManager {
private final int VERTICAL_GAP = 30;
protected void sublayout(int maxWidth, int maxHeight) {
int nFields = getFieldCount(), height = 0, xPosition, yPosition = 0;
Field f;
for (int i = 0; i < nFields; i++) {
f = getField(i);
layoutChild(f, maxWidth, maxHeight);
height += f.getHeight();
if (i != 0) {
height += VERTICAL_GAP;
}
}
for (int i = 0; i < nFields; i++) {
f = getField(i);
xPosition = (maxWidth - f.getWidth()) / 2;
setPositionChild(f, xPosition, yPosition);
yPosition += f.getHeight();
if (i != nFields - 1) {
yPosition += VERTICAL_GAP;
}
}
setExtent(maxWidth, height);
}
}
Usage
class MyScreen extends MainScreen {
private LabelField lblOne, lblTwo, lblThree;
public MyScreen() {
CustomVerticalFieldManger cvfm = new CustomVerticalFieldManger();
cvfm.setBackground(BackgroundFactory.createSolidBackground(Color.AQUA));
lblOne = new LabelField("The quick brown fox jumps over the lazy dog");
lblTwo = new LabelField("The quick brown fox jumps over the lazy dog");
lblThree = new LabelField("The quick brown fox jumps over the lazy dog");
cvfm.add(lblOne);
cvfm.add(lblTwo);
cvfm.add(lblThree);
add(cvfm);
changeFont();
}
private int fontSize = 5;
private void changeFont() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
if (fontSize == 50) {
fontSize = 5;
}
lblOne.setFont(Font.getDefault().derive(Font.PLAIN,
fontSize));
lblTwo.setFont(Font.getDefault().derive(Font.PLAIN,
fontSize + 2));
lblThree.setFont(Font.getDefault().derive(Font.PLAIN,
fontSize + 4));
fontSize += 6;
updateLayout();
invalidate();
}
});
}
};
timer.schedule(task, 500, 1000);
}
}

Related

Making scenes in a game without javafx

I am currently trying to make something that when the first scene is done, it moves onto the next scene. I don't use javafx, and I do not plan to use it because I am too lazy to try and download anything else or learn a completely new programming language. I want to know a way to make my character go onto the next scene without using javafx, simply because I am lazy. I may learn it another time but for now I am trying to learn the basics of coding in java, especially when it comes to video games, as I do plan on making games as I become more experienced. I am also too lazy to modify my code unless if it is something minor or something that will actually make things work.
My Code:
Player player;
public ArrayList<Wall> walls = new ArrayList<>();
public ArrayList<Spike> spikes = new ArrayList<>();
public ArrayList<SpawnPoint> spawnpoints = new ArrayList<>();
public ArrayList<BackgroundWall> backgroundwalls = new ArrayList<>();
public ArrayList<TextThing> textthings = new ArrayList<>();
Timer gameTimer;
public int x = 600;
public int y = 500;
public int textx = 200;
public int texty = 300;
public boolean Stage1 = true;
public boolean Stage2 = false;
public GamePanel() {
player = new Player(x, y, this);
makeObjects1();
gameTimer = new Timer();
gameTimer.schedule(new TimerTask() {
public void run() {
player.set();
repaint();
}
}, 0, 17);
}
public void makeObjects1() {
for(int i = 100; i < 1900; i += 100) {
walls.add(new Wall(i, 700));
}
for(int i = 200; i < 700 ; i += 100) {
walls.add(new Wall(100, i));
}
for(int i = 200; i < 500 ; i += 100) {
walls.add(new Wall(1100, i));
}
for(int i = 100; i < 1200; i += 100) {
walls.add(new Wall(i, 100));
}
for(int i = 100; i < 1200; i += 100) {
backgroundwalls.add(new BackgroundWall(i, 700));
}
for(int i = 100; i < 1200; i += 100) {
backgroundwalls.add(new BackgroundWall(i, 600));
}
for(int i = 100; i < 1200; i += 100) {
backgroundwalls.add(new BackgroundWall(i, 500));
}
for(int i = 100; i < 1200; i += 100) {
backgroundwalls.add(new BackgroundWall(i, 400));
}
for(int i = 100; i < 1200; i += 100) {
backgroundwalls.add(new BackgroundWall(i, 300));
}
for(int i = 100; i < 1200; i += 100) {
backgroundwalls.add(new BackgroundWall(i, 200));
}
spikes.add(new Spike(1100, 500));
spawnpoints.add(new SpawnPoint(x, y));
textthings.add(new TextThing(textx, texty));
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D gtd = (Graphics2D) g;
if(player.keyDown) {
player.height = 100;
}
if(player.keyReleasedDown) {
player.height = 200;
}
}
My coding works btw, it's just that all my attempts in trying to code scenes without javafx failed miserably. Thank you!

Brick breaker brick color

I am trying to have each brick in my game have a random color, however when I try to do this the whole set of bricks become the same color. How do I make each individual brick a random color? Any help is appreciated.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Game extends JoeApplet implements KeyListener
{
String status;
int ballx = 294; // ball spawn x coordinate
int bally = 640; // ball spawn y coordinate
int batx = 294;
int baty = 654;
int brickx = 32;
int bricky = 50;
double movex = -16; // x speed of ball
double movey = -16; //y speed of ball
int count = 0;
int currentLevel=0;
int score=0; //starts score at 0
int lives=3; //lives start at 3
static boolean right = false;
static boolean left = false;
boolean ballFallDown = false;
boolean bricksOver = false;
Rectangle Ball = new Rectangle(ballx, bally, 14, 14); //creates ball
Rectangle Bat = new Rectangle(batx, baty, 100, 12); //creates bat(paddle)
Rectangle[] Brick = new Rectangle[49]; //creates desired number of bricks
public void paint(Graphics art)
{
switch(currentLevel)
{
case 0:
menuScreen(art);
break;
case 1:
game(art);
break;
}
}
public void menuScreen(Graphics art)
{
setSize(700, 700);
art.setColor(Color.BLACK);
art.fillRect(0, 0, 698, 698);
Color ballcolor=new Color(0,0,66);
art.setColor(ballcolor);
art.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
Color batcolor=new Color(0,0,66);
art.setColor(batcolor);
art.fill3DRect(Bat.x, Bat.y, Bat.width, Bat.height, true);
art.setColor(Color.green);
art.drawRect(0, 0, 698, 698);
art.setColor(Color.yellow);
Font menu = new Font("Arial", Font.BOLD, 20);
art.setFont(menu);
art.drawString("Brick Breaker", 100,400);
art.drawString("Press P to Play", 100,425);
art.drawString("Press Q to Quit game", 100,450);
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
Color mycolor=new Color(100,0,0);
art.setColor(mycolor);
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
art.setColor(Color.YELLOW);
if (ballFallDown || bricksOver)
{
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.drawString(status, 294, 349);
ballFallDown = false;
bricksOver = false;
}
}
public void game(Graphics art)
{
setSize(700, 700);
art.setColor(Color.BLACK);
art.fillRect(0, 0, 698, 698);
Color ballcolor=new Color(0,0,225);
art.setColor(ballcolor);
art.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
Color batcolor=new Color(0,0,139);
art.setColor(batcolor);
art.fill3DRect(Bat.x, Bat.y, Bat.width, Bat.height, true);
art.setColor(Color.green);
art.drawRect(0, 0, 698, 698);
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
Color mycolor=new Color(200,0,0);
art.setColor(mycolor);
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
if (ballFallDown || bricksOver)
{
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.drawString(status, 100,425);
ballFallDown = false;
bricksOver = false;
}
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
if (Brick[i].intersects(Ball))
{
score=score+10;
Brick[i] = null;
movey = -movey;
count++;
}
}
}
if (count == Brick.length)
{
bricksOver = true;
movex=0;
movey=0;
art.setColor(Color.green);
status = "YOU BEAT THE LEVEL!!";
art.drawString("Press E to Exit", 100,450);
art.drawString("Press N for Next Level", 100,475);
repaint();
}
repaint();
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.setColor(Color.white);
art.drawString("Score:"+score, 600, 684);
Ball.x += movex;
Ball.y += movey;
if (left == true)
{
Bat.x -= 18;
right = false;
}
if (right == true)
{
Bat.x += 18;
left = false;
}
if (Bat.x <= 4)
{
Bat.x = 4;
}
else if (Bat.x >= 586)
{
Bat.x = 596;
}
if (Ball.intersects(Bat))
{
movey = -movey-.1;
}
if (Ball.x <= 0 || Ball.x + Ball.height >= 698)
{
movex = -movex;
}
if (Ball.y <= 0)
{
movey = -movey;
}
Font f1 = new Font("Arial", Font.BOLD, 20);
art.setFont(f1);
art.setColor(Color.white);
art.drawString("Lives:"+ lives, 5, 684);
if (Ball.y >= 698 && (bricksOver==false) && lives>0)
{
ballFallDown = true;
art.setColor(Color.red);
status = "";
art.drawString("", 100,450);
lives=lives-1;
ballx = 294;
bally = 640;
Ball = new Rectangle(ballx, bally, 14, 14);
movex = -16;
movey = -16;
repaint();
}
if(lives==0 && Ball.y >= 698)
{
art.setColor(Color.red);
art.drawString("You lost!!", 100,425);
art.drawString("Press E to Exit", 100,450);
}
}
public void init()
{
addKeyListener(this);
for (int i = 0; i < Brick.length; i++) //creates bricks
{
Brick[i] = new Rectangle(brickx, bricky, 40, 20);
if (i == 12) //1st row of bricks
{
brickx = 32;
bricky = 84;
}
if (i == 23) //2nd row of bricks
{
brickx = 82;
bricky = 118;
}
if (i == 32) //3rd row of bricks
{
brickx = 132;
bricky = 152;
}
if (i == 39) //4th row of bricks
{
brickx = 182;
bricky = 186;
}
if (i == 44) //5th row of bricks
{
brickx = 232;
bricky = 220;
}
if (i == 47) //6th row of bricks
{
brickx = 282;
bricky = 254;
}
if (i == 48) //7th row of bricks
{
brickx = 144;
bricky = 132;
}
brickx += 50; //spacing between each brick
}
}
public void restart()
{
ballx = 294;
bally = 640;
batx = 294;
baty = 654;
brickx = 32;
bricky = 50;
Ball = new Rectangle(ballx, bally, 14, 14);
Bat = new Rectangle(batx, baty, 100, 12);
movex = -16;
movey = -16;
ballFallDown = false;
bricksOver = false;
count = 0;
status = null;
for (int i = 0; i < Brick.length; i++) //recreates bricks
{
Brick[i] = new Rectangle(brickx, bricky, 40, 20);
if (i == 12)
{
brickx = 32;
bricky = 84;
}
if (i == 23)
{
brickx = 82;
bricky = 118;
}
if (i == 32)
{
brickx = 132;
bricky = 152;
}
if (i == 39)
{
brickx = 182;
bricky = 186;
}
if (i == 44)
{
brickx = 232;
bricky = 220;
}
if (i == 47)
{
brickx = 282;
bricky = 254;
}
if (i == 48)
{
brickx = 144;
bricky = 132;
}
brickx += 50;
}
repaint();
}
#Override
public void keyPressed(KeyEvent e) //allows each key to do desired action
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT)
{
left = true;
}
if (keyCode == KeyEvent.VK_RIGHT)
{
right = true;
}
if (keyCode == e.VK_P && currentLevel == 0)
{
currentLevel = 1;
}
else if (keyCode == e.VK_E && currentLevel == 1)
{
currentLevel = 0;
score=0;
lives=3;
restart();
}
else if(keyCode == e.VK_Q)
{
System.exit(0);
}
}
#Override
public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT)
{
left = false;
}
if (keyCode == KeyEvent.VK_RIGHT)
{
right = false;
}
}
#Override
public void keyTyped(KeyEvent e)
{
}
public static void main(String[] args)
{
Game prog = new Game();
prog.init();
}
}
I'd throw that code out and start over as you've got both program logic and repaints within your painting methods, neither of which will help you, and your code appears to be one big huge "God" class, all of which will leave you with code that's a horrific nightmare to debug. Recommendations:
Create at least two separate JPanels to display your program with, a GamePanel and a MenuPanel.
Swap these JPanels using a CardLayout.
Do all graphics within a JPanel's paintComponent method and not within a JFrame's or JApplet's paint method.
Don't forget to call the super's painting method, the same method as your override within your override. This is to clean up any dirty pixels.
Separate your program logic from your GUI
This means that you should have a logical non-GUI representation of a single Brick class as well as a collection of these non-GUI bricks.
You can always give your Brick class a Color field, one that the view or gui uses to paint it with.
Create a game-loop, one that you can control, one that doesn't involve calling repaint() within a painting method, since this leads to a completely uncontrollable loop.
Favor use of Key Bindings over KeyListeners.
Try to avoid use of "magic" numbers, such as hard-coding your brick width and spacing in the class itself. Better to use constants as this too makes debugging and enhancing much easier.
For example, some code that's just to demonstrate showing random colors:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class BrickBreak {
private static void createAndShowGui() {
GamePanel gamePanel = new GamePanel();
JFrame frame = new JFrame("Brick Break");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(gamePanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
// JPanel that draws the game
class GamePanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final Color BACK_GRND = Color.BLACK;
private int prefW;
private int prefH;
private Bricks bricks = new Bricks();
public GamePanel() {
// wide enough to hold the complete top-row of Bricks
// using constants, so GUI automatically resizes if any sizes change
prefW = (Brick.WIDTH + Bricks.X_SPACING) * Bricks.ROW_COUNTS[0] + Bricks.X_SPACING;
prefH = prefW;
setBackground(BACK_GRND);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(prefW, prefH);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Brick brick : bricks) {
brick.draw(g2);
}
}
}
// non-GUI class that represents a logical Brick
class Brick {
public static final int WIDTH = 40;
public static final int HEIGHT = 20;
private int x;
private int y;
private Color color;
private Rectangle boundingRectangle;
public Brick(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
boundingRectangle = new Rectangle(x, y, WIDTH, HEIGHT);
}
// yeah, I'm mixing some view with model here.
public void draw(Graphics2D g2) {
g2.setColor(color);
g2.fill3DRect(x, y, WIDTH, HEIGHT, true);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Color getColor() {
return color;
}
// use this to test for collisions
public boolean contains(Point p) {
return boundingRectangle.contains(p);
}
#Override
public String toString() {
return "Brick [x=" + x + ", y=" + y + ", color=" + color + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Brick other = (Brick) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
// logical class that holds all Bricks
// Have class implement Iterable<Brick> so we can easily iterate through its containing
// Brick objects in a for-each loop
class Bricks implements Iterable<Brick> {
public static final int X_SPACING = 10;
public static final int Y_SPACING = X_SPACING;
public static final int[] ROW_COUNTS = {13, 11, 9, 7, 5, 3, 1};
private static final float MIN_SAT = 0.8f;
private List<Brick> brickList;
private Random random = new Random();
public Bricks() {
init(); // safe to call since it's final
}
public final void init() {
// recreate the brickList ArrayList
brickList = new ArrayList<>();
int y = Y_SPACING;
// for each row of bricks
for (int row = 0; row < ROW_COUNTS.length; row++) {
int x = X_SPACING + ((ROW_COUNTS[0] - ROW_COUNTS[row]) / 2) * (X_SPACING + Brick.WIDTH);
// for each column
for (int j = 0; j < ROW_COUNTS[row]; j++) {
// create a random color
float hue = random.nextFloat();
float saturation = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
float brightness = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
Color color = Color.getHSBColor(hue, saturation, brightness);
Brick brick = new Brick(x, y, color); // create a new Brick with this Color
brickList.add(brick);
x += X_SPACING + Brick.WIDTH;
}
y += Y_SPACING + Brick.HEIGHT;
}
}
// returns null if no collision
public Brick collision(Point p) {
for (Brick brick : brickList) {
if (brick.contains(p)) {
return brick;
}
}
return null;
}
#Override
public Iterator<Brick> iterator() {
return brickList.iterator();
}
public boolean remove(Brick brick) {
// because Brick implements equals and hashCode, we can do this
return brickList.remove(brick);
}
}
Note that I like using Color's static getHSBColor(float h, float s, float b) method for creating random Colors as this helps me to avoid creating dull Colors, since I can guarantee that the saturation and brightness are above minimum values. All three parameters must be float values between 0f and 1.0f
float hue = random.nextFloat();
float saturation = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
float brightness = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
Color color = Color.getHSBColor(hue, saturation, brightness);
Your code has quite a lot of issues, which #HovercaftFullOfEels answer already points out.
As for why your code doesn't work:
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
Color mycolor=new Color(100,0,0);
art.setColor(mycolor);
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
This is the part that renders the bricks. You never create a random-number, but use the same Color for each brick (new Color(100, 0, 0);). Instead introduce a new variable into Brick that specifies the color of each brick and is initialized once with a random color.
The Brick-class would afterwards look like this:
public class Brick{
public int x;
public int y;
...
public Color color;
...
}
The ... are just placeholders for other code that may be content of the class. Regarding public access of Class-variables: Encapsulation is a fundamental concept of OOP and should be used (on encapsulation). E.g. instead of giving direct access to Brick.x consider introducing a method Brick#getX().

javafx Glow shatter the animation

Im just starting to code and learn javafx and doing an easy project and my problem is after i add a Glow effect on my graphic context the animation slows down dramaticly.
/**
* JavaFX rocks ;)
*/
public class CDLMatrix extends Application {
Stage matrixStage;
private final String characters = "Effect glow = new Glow(1.0); gc.setEffect(glow); WHY SHATTERS ?!";
private final Random random = new Random();
protected final Font font = Font.font("MS PGothic", FontWeight.BOLD, 15);
char[] data = new char[2000 * 2000];
int[] path = new int[2000 * 2000];
private long lastTime = 0;
int getNumberOfCharsPerRow() {
return (int) matrixStage.getWidth() / 12;
}
int getNumberOfCharsPerColumn() {
return (int) matrixStage.getHeight() / 12;
}
// takes random for now
private char getChar() {
return characters.charAt(Math.abs(random.nextInt()
% characters.length()));
}
void update(long now) {
if (lastTime == 0) {
lastTime = now;
}
// fadeTime = how fast trail will fade out
// flipRate = how fast trail chars will change
final int fadeTime = 3;
final float flipRate = 0.01f;
final int fillStart = 100;
final float fillRate = 0.01f;
int numberOfCharsPerRow = getNumberOfCharsPerRow();
int numberOfCharsPerColumn = getNumberOfCharsPerColumn();
int numberOfChars = numberOfCharsPerRow * numberOfCharsPerColumn;
for (int i = numberOfChars - 1; i >= 0; --i) {
if (i + numberOfCharsPerRow < numberOfChars) {
if (path[i] == 255) {
// This means char was just set
// Initialize the next row at this X
// position
path[i + numberOfCharsPerRow] = 255;
data[i + numberOfCharsPerRow] = getChar();
}
}
// path[i] > 64 means if this char Green component > 25%
if (path[i] > 64 && random.nextFloat() < flipRate) {
data[i] = getChar();
}
// Decrement the char Green component
if (path[i] > fadeTime) {
path[i] -= fadeTime;
} else {
path[i] = 0;
}
// First row
// Start doing stuff only if the Green component > 40%
if (i < numberOfCharsPerRow && path[i] <= fillStart) {
if (random.nextFloat() < fillRate) {
path[i] = 255;
data[i] = getChar();
}
}
}
lastTime = now;
}
#Override
public void start(Stage stage) throws Exception {
this.matrixStage = stage;
matrixStage.setTitle("CDL Matrix");
Group root = new Group();
Scene scene = new Scene(root, 1024, 768);
scene.addEventHandler(KeyEvent.KEY_PRESSED,
new EventHandler<KeyEvent>() {
#Override
// F key for full screen ;)
public void handle(KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.F) {
matrixStage.setFullScreen(!matrixStage
.isFullScreen());
}
// ctrl + Q = exit
if (keyEvent.isControlDown()
&& keyEvent.getCode() == KeyCode.Q) {
matrixStage.close();
}
}
});
Canvas canvas = new Canvas();
canvas.widthProperty().bind(matrixStage.widthProperty());
canvas.heightProperty().bind(matrixStage.heightProperty());
final GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFont(font);
// Effect glow = new Glow(1.0); <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// gc.setEffect(glow); <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
new AnimationTimer() {
#Override
public void handle(long now) {
update(now);
gc.clearRect(0, 0, matrixStage.getWidth(),
matrixStage.getHeight());
gc.setFill(Color.rgb(0, 1, 0));
gc.fillRect(0, 0, matrixStage.getWidth(),
matrixStage.getHeight());
int y = 0;
int numberOfCharsPerRow = getNumberOfCharsPerRow();
int numberOfCharsPerColumn = getNumberOfCharsPerColumn();
// Colors
for (int i = 0; i < numberOfCharsPerRow
* numberOfCharsPerColumn; ++i) {
gc.setFill(Color.rgb(0, path[i], 0));
String text = String.valueOf(data[i]);
gc.fillText(text, (i % numberOfCharsPerRow) * 12 + 1,
y + 13);
if (i % numberOfCharsPerRow == numberOfCharsPerRow - 1) {
y += 12;
}
}
}
}.start();
root.getChildren().add(canvas);
matrixStage.setScene(scene);
matrixStage.show();
}
}
Apply the glow to the Canvas node rather than to the GraphicsContext.
Animation will then occur at normal speed rather than slideshow speed.
Change:
gc.setEffect(glow);
To:
canvas.setEffect(glow);
There must be something in the internal implementation of JavaFX which causes applying effects such as Glow to a GraphicsContext rather than a Node to be orders of magnitude less efficient. You might want to file an issue in the JavaFX issue tracker to have a developer look into it.
Test environment: Java 8u40, OS X 10.9

How can i put delay in displaying the final result of my maze

i am creating a maze generation application. what i want to happen is that, when i run my program, it will show the animation on how the maze was created (it will show how it knocks the wall to create a path).
i tried to put delay on some of its parts but it won't run.thank you for the HUGE HELP!
here's the code:
public class Maze extends JPanel {
private Room[][] rooms;// m x n matrix of rooms
private ArrayList<Wall> walls; // List of walls
private Random rand;// for random wall
private int height;// height of matrix
private int width;// width of matrix
private int num;// incrementor
private JoinRoom ds;// union paths
// paint methods //
private int x_cord; // x-axis rep
private int y_cord;// y-axis rep
private int roomSize;
private int randomWall;
private int create;
int mazectr;
public static int m;// these are variables for the size of maze (m x n)
public static int n;
public Maze(int m, int n) {
JPanel j = new JPanel();
final JFrame f = new JFrame();
this.height = m;
this.width = n;
rooms = new Room[m][n];
walls = new ArrayList<Wall>((m - 1) * (n - 1));
long startTime = System.currentTimeMillis();
generateRandomMaze();
long endTime = System.currentTimeMillis();
final JLabel jl = new JLabel("Time Taken: " + (endTime-startTime) + "ms");
final JButton y = new JButton("OK");
j.add(jl);
j.add(y);
f.add(j);
y.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e)
{
f.setVisible(false);
}
});
f.setVisible(true);
f.setSize(100, 100);
//jl.setLocation(1000, 1500);
//jl.setBounds(0, 0, 110, 130);
setPreferredSize(new Dimension(800, 700));
}
private void generateRandomMaze() {
generateInitialRooms();// see next method
ds = new JoinRoom(width * height);
rand = new Random(); // here is the random room generator
num = width * height;
while (num > 1) {
// when we pick a random wall we want to avoid the borders getting eliminated
randomWall = rand.nextInt(walls.size());
Wall temp = walls.get(randomWall);
// we will pick two rooms randomly
int roomA = temp.currentRoom.y + temp.currentRoom.x * width;
int roomB = temp.nextRoom.y + temp.nextRoom.x * width;
// check roomA and roomB to see if they are already members
if (ds.find(roomA) != ds.find(roomB)) {
walls.remove(randomWall);
ds.unionRooms(ds.find(roomA), ds.find(roomB));
temp.isGone = true;
temp.currentRoom.adj.add(temp.nextRoom);
temp.nextRoom.adj.add(temp.currentRoom);
num--;
}// end of if
}// end of while
}
// name the room to display
private int roomNumber = 0;
private static Label input;
private static Label input2;
/**
* Sets the grid of rooms to be initially boxes
* This is self explanitory, we are only creating an reverse L for all
* The rooms and there is an L for the border
*/
private void generateInitialRooms() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
// create north walls
rooms[i][j] = new Room(i, j);
if (i == 0) {
rooms[i][j].north = new Wall(rooms[i][j]);
} else {
rooms[i][j].north = new Wall(rooms[i - 1][j], rooms[i][j]);
walls.add(rooms[i][j].north);
}
if (i == height - 1) {
rooms[i][j].south = new Wall(rooms[i][j]);
}
if (j == 0) {
rooms[i][j].west = new Wall(rooms[i][j]);
} else {
rooms[i][j].west = new Wall(rooms[i][j - 1], rooms[i][j]);
walls.add(rooms[i][j].west);
}
if (j == width - 1) {
rooms[i][j].east = new Wall(rooms[i][j]);
}
rooms[i][j].roomName = roomNumber++;// we will name the rooms
}
}
// initalize entrance and exit
rooms[0][0].west.isGone = true;// you can replace .west.isGone with .north.isGone
// this is just saying the roomName for top left is 0
rooms[0][0].roomName = 0;
// we will remove the south wall of the last room
rooms[height - 1][width - 1].south.isGone = true;
// this is just saying the roomName for bottom right is the last element in the mxn room matrix
rooms[height - 1][width - 1].roomName = (height * width);
}
public void paintComponent(Graphics g) {
x_cord = 40;
y_cord = 40;
Thread t = new Thread();
// could have taken height as well as width
// just need something to base the roomsize
roomSize = (width - x_cord) / width + 20;
// temp variables used for painting
int x = x_cord;
int y = y_cord;
for (int i = 0; i <= height - 1; i++) {
for (int j = 0; j <= width - 1; j++) {
if (!(rooms[i][j].north.isGone)) {
g.drawLine(x, y, x + roomSize, y);
}//end of north if
// west wall not there draw the line
if (rooms[i][j].west.isGone == false) {
g.drawLine(x, y, x, y + roomSize);
}// end of west if
if ((i == height - 1) && rooms[i][j].south.isGone == false) {
g.drawLine(x, y + roomSize, x + roomSize,
y + roomSize);
}// end of south if
if ((j == width - 1) && rooms[i][j].east.isGone == false) {
g.drawLine(x + roomSize, y, x + roomSize,
y + roomSize);
}// end of east if
x += roomSize;// change the horizontal
try
{
Thread.sleep(50);
} catch (Exception e) {};
t.start();
}// end of inner for loop
x = x_cord;
y += roomSize;
}// end of outer for loop
}
public static void main(String[] args) throws IOException {
// use JFrame to put the created panel on
String path = "E:\\Iskul\\trys\\tryy\\bin\\GUI.jpg";
File file = new File("E:\\Iskul\\trys\\tryy\\bin\\GUI.jpg");
BufferedImage image = ImageIO.read(file);
File fileRec = new File("E:\\Iskul\\trys\\tryy\\bin\\re.jpg");
BufferedImage imageRec = ImageIO.read(fileRec);
File fileHex = new File("E:\\Iskul\\trys\\tryy\\bin\\hexx.jpg");
BufferedImage imageHex = ImageIO.read(fileHex);
final JFrame frame = new JFrame("Prim's Algorithm");
final JPanel jp = new JPanel();
final JTextField input = new JTextField(10);
final JTextField input2 = new JTextField(10);
final JButton jb = new JButton(new ImageIcon(imageRec));
jb.setBorder(BorderFactory.createEmptyBorder());
final JButton jb1 = new JButton(new ImageIcon(imageHex));
jb1.setBorder(BorderFactory.createEmptyBorder());
final JLabel label = new JLabel(new ImageIcon(image));
jb.setLocation(100, 10);
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(795, 501));
jp.add(input);
jp.add(input2);
frame.add(jp);
jp.add(jb);
jp.add(jb1);
//jb.setImage(image);
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//int mazectr = 1;
int m = Integer.valueOf(input.getText());
int n = Integer.valueOf(input2.getText());
frame.remove(label);
frame.remove(jp);
//frame.add(new Maze(m,n));
frame.getContentPane().add(new Maze(m, n));
frame.pack();
}});
jb1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//int m = Integer.valueOf(input.getText());
//int n = Integer.valueOf(input2.getText());
Hexa1 hexa = new Hexa1();
hexa.main();
//hexa.run();
}
});
}}// end of main
Your code wont work, you cant do an sleep in the Paint method, because if you do so, he wont draw, he just waits and at the end he'll draw your whole image.
If you want to do a nice effect, you should draw one step after the other but you should be aware that this is a lot of work to realize...

Sprites are drawing at the wrong, but right location

public void render() {
if (TimeUtils.nanoTime() - lastSpawn > 2100000000)
chooseLane();
}
private void spawnCar() {
Rectangle car2 = new Rectangle();
float Pos123 = MathUtils.random(0, 2);
if (Pos123 == 0) {
car2.x = 60;
}
if (Pos123 == 1) {
car2.x = 180;
}
if (Pos123 == 2) {
car2.x = 300;
}
car = new Rectangle();
car.width = 100;
car.height = 172;
car2.y = 1000;
car2.setWidth(100);
car2.setHeight(172);
carb.add(car2);
lastSpawn = TimeUtils.nanoTime();
}
The sprites are drawing at one of these three locations every time but when I do a System.out.println(Pos123) the Sprite doesn't correlate to the actually lane that it has spawned in. This is also throwing the collision detector out of whack because it's triggering in the wrong lanes

Categories