Trying to use a JScrollPane to display an array of strings but i keep getting an error - user-interface

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class SavingAccountFrame extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_LENGTH = 500;
private static final double INITIAL_BALANCE = 0.0;
private static final double ANNUAL_RATE = 0.0;
private static final int YEARS = 0;
String[] result;
private JLabel initialLabel;
private JLabel rate;
private JLabel years;
private JTextField initialBal;
private JTextField annualRate;
private JTextField numOfYears;
private JButton calculate;
private JPanel panel;
private JList box;
private JScrollPane scroll;
SavingAccountFrame(){
createTextField();
createButton();
createScrollPane();
createPanel();
setSize(FRAME_WIDTH, FRAME_LENGTH);
}
private void createTextField(){
final int FIELD_WIDTH = 10;
initialLabel = new JLabel("Initial Balance");
initialBal = new JTextField(FIELD_WIDTH);
rate = new JLabel("Annual Rate");
annualRate = new JTextField(FIELD_WIDTH);
years = new JLabel("Number of Years");
numOfYears = new JTextField(FIELD_WIDTH);
}
private void createButton(){
calculate = new JButton("Calculate");
class CalcListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double iB = Double.parseDouble(initialBal.getText());
double r = Double.parseDouble(rate.getText());
int y = Integer.parseInt(years.getText());
r = r / 100;
for (int i = 0; i < y; i++) {
double newbalance = iB * r;
iB += newbalance;
String test = String.valueOf(iB);
result[i] = test;
}
box = new JList(result);
scroll = new JScrollPane(box);
getContentPane().add(scroll);
}
}
ActionListener d = new CalcListener();
calculate.addActionListener(d);
}
private void createScrollPane(){
scroll = new JScrollPane();
}
private void createPanel()
{
panel = new JPanel();
panel = new JPanel();
panel.add(initialLabel);
panel.add(initialBal);
panel.add(rate);
panel.add(annualRate);
panel.add(years);
panel.add(numOfYears);
panel.add(calculate);
panel.add(scroll);
add(panel);
}
}
import javax.swing.JFrame;
public class SavingAccount {
public static void main(String[] args) {
JFrame frame = new SavingAccountFrame();
frame.setTitle("Savings Account");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
i am having a bit of homework trouble and my code keeps spitting out this error when i press the calculate button.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Annual Rate"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1242)
at java.lang.Double.parseDouble(Double.java:527)
at SavingAccountFrame$1CalcListener.actionPerformed(SavingAccountFrame.java:54)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2012)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2335)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:404)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6268)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6033)
at java.awt.Container.processEvent(Container.java:2045)
at java.awt.Component.dispatchEventImpl(Component.java:4629)
at java.awt.Container.dispatchEventImpl(Container.java:2103)
at java.awt.Component.dispatchEvent(Component.java:4455)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4633)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4297)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4227)
at java.awt.Container.dispatchEventImpl(Container.java:2089)
at java.awt.Window.dispatchEventImpl(Window.java:2517)
at java.awt.Component.dispatchEvent(Component.java:4455)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:649)
at java.awt.EventQueue.access$000(EventQueue.java:96)
at java.awt.EventQueue$1.run(EventQueue.java:608)
at java.awt.EventQueue$1.run(EventQueue.java:606)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:116)
at java.awt.EventQueue$2.run(EventQueue.java:622)
at java.awt.EventQueue$2.run(EventQueue.java:620)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:619)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
Can someone please clarify for me what this exception is and how to fix it. I can't pinpoint where the seems to point null or where the format is incorrect. Please and thank you

The error is here
double r = Double.parseDouble(rate.getText());
in createButton.
instead you should use annualRate.parseDouble.
because rate is a JLabel but not the textfield.
rate = new JLabel("Annual Rate");
When you try to parse the "Annual Rate" into a number, it will give you java.lang.NumberFormatException

Related

JavaFX: Animation based on time function

I don't have an MWE because I'm not sure how to start. I guess my question is mostly about which are the best tools for the job.
I have an object that amounts to a Function<Double, VectorXYZ>, which outputs the position of an object given a time. It handles its own interpolation. I'm wondering if there's a way to handle the functionality of a Timeline without having to use KeyFrames. I would like to be able to both play it forward, and to use a Slider.
I thought of having a DoubleProperty that is somehow linked to the Timeline, associated with a Listener that updates the translation property of the Group containing the object. But I don't know how to go about doing that.
Thanks for your help!
So yeah, it was a very vague question, but as #James_D said, AnimationTimer is the tool I was looking for. Basically I was looking for low-level access to the animation loop, and this seemed to be it. Here's an MWE of an object following some path across the Scene. It separates system time from scene time (stored as a DoubleProperty) so that it can be paused and restarted, and the time can be set via a Slider as well.
import com.google.common.base.Function;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.SubScene;
import javafx.scene.control.Slider;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class AnimationTestApp extends Application {
private static final double durationSeconds = 5;
private static final double screenWidthMeters = 10;
private static final double screenHeightMeters = 10;
private static final double pixelsPerMeter = 50;
private static final double squareSizeMeters = 0.5;
private static final double screenWidthPixels = pixelsPerMeter * screenWidthMeters;
private static final double screenHeightPixels = pixelsPerMeter * screenHeightMeters;
private static final double squareSizePixels = pixelsPerMeter * squareSizeMeters;
private static final double originXPixels = screenWidthPixels/2;
private static final double originYPixels = screenHeightPixels/2;
private final Rectangle square = new Rectangle(squareSizePixels, squareSizePixels, Color.RED);
private long lastTime = -1;
private boolean isStopped = true;
private double t = 0;
private DoubleProperty timeProperty;
private DoubleProperty timeProperty() {
if (timeProperty == null) {
timeProperty = new SimpleDoubleProperty();
timeProperty.addListener((obs, ov, nv) -> {updateScene();});
}
return timeProperty;
}
#Override
public void start(Stage primaryStage) throws Exception {
final SubScene subscene = new SubScene(new Group(square), screenWidthPixels, screenHeightPixels);
Slider timeSlider = new Slider(0, 5, 1);
timeSlider.valueProperty().bindBidirectional(timeProperty());
VBox root = new VBox(timeSlider, subscene);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
AnimationTimer animationTimer = buildTimer();
handleKeyboard(scene, animationTimer);
}
private AnimationTimer buildTimer() {
AnimationTimer animationTimer = new AnimationTimer() {
#Override
public void handle(long now) {
double elapsedNS = now - lastTime;
double dt = elapsedNS * 1E-9;
if (timeProperty().get() + dt > durationSeconds) {
stop();
}
timeProperty().set(timeProperty().get() + dt);
updateScene();//timeProperty.get());
lastTime = now;
}
#Override
public void start() {
lastTime = System.nanoTime();
isStopped = false;
if (timeProperty().get() > durationSeconds) {
timeProperty().set(0);
}
super.start();
}
#Override
public void stop() {
isStopped = true;
super.stop();
}
};
return animationTimer;
}
private void updateScene() {
double t = timeProperty().get();
Point2D point = positionFunction().apply(t);
double xPixels = originXPixels + point.getX() * pixelsPerMeter;
double yPixels = originYPixels + point.getY() * pixelsPerMeter;
square.setTranslateX(xPixels);
square.setTranslateY(yPixels);
}
private Function<Double, Point2D> positionFunction() {
double radius = 3;
double period = 2;
return (t) -> new Point2D(radius * Math.sin(2*Math.PI*t/period), radius * Math.cos(2*Math.PI*t/period));
}
private void handleKeyboard(Scene scene, AnimationTimer timer) {
scene.setOnKeyPressed((ke) -> {
if (ke.getCode().equals(KeyCode.SPACE)) {
if (isStopped) {timer.start();}
else {timer.stop();}
}
});
}
}

(JFX) Troubles when loading images using a static method and inherited classes

I'm trying to load 2 images using a static method loadImage(String) that I made.
This method is stored in my Entity (abstract) class and my classes Projectile and Player are inheriting from this entity.
However when I'm using this method (2 times since i'm loading "Projectile.loadImage("image1");" and "Player.loadImage("image2");") only the second image is stored.
I'm thinking that it's cause by the inheritance since the loadImage() method is written in the Entity class so it might be changing the static sprite from the Entity and not Player or Projectile, but i don't know how to fix this without recreating a loadImage() method for all subclasses and having the subclasses not inheriting the sprite property but instead having their own ones
Here is an example of the code :
//Main class
package application;
import Entities.*;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
public class Main extends Application
{
final int WIDTH = 800;
final int HEIGHT = 800;
public int frameCount = 0;
Player p;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
Player.loadImage("/images/isaac.png");
Projectile.loadImage("/images/tear.png");
stage.setTitle("My first JFX / Java project");
Group root = new Group();
Scene scene = new Scene(root, WIDTH, HEIGHT);
p = new Player(WIDTH/2,HEIGHT/2,root);
stage.setScene(scene);
stage.setResizable(false);
stage.sizeToScene();
stage.show();
}
}
//Entity Class and load Image
package Entities;
import application.Vector2;
import javafx.scene.Group;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public abstract class Entity {
protected double x;
protected double y;
private Group root;
protected Vector2 dir;
protected double speed;
private static Image sprite;
private ImageView iv;
private int size;
private double hp;
public Entity(float px, float py,Group r, Image s) {
root = r;
x = px;
y = py;
size = 100;
iv = new ImageView(s);
dir = new Vector2(0,0);
speed = 0.2;
hp = 3;
root.getChildren().add(iv);
iv.setX(x);
iv.setY(y);
iv.setFitWidth(100);
iv.setFitHeight(100);
}
public static void loadImage(String input) {
sprite = new Image(input);
}
//Player class constructor
package Entities;
import application.Vector2;
import javafx.scene.Group;
public class Player extends Entity{
private boolean north, west, south, east;
private boolean shootN, shootW, shootS, shootE;
private Vector2 pInput;
public Player(float px, float py,Group r) {
super(px,py,r,getSprite());
north = false;
west = false;
south = false;
east = false;
pInput = new Vector2(0,0);
setHp(10);
}
}
//Projectile Constructor
package Entities;
import java.util.ArrayList;
import application.Vector2;
import javafx.scene.Group;
public class Projectile extends Entity{
private double speed;
Entity parent;
int lifespan;
public Projectile(float px, float py,Group r,Entity p,Vector2 d){
super(px,py,r,getSprite());
speed = 5;
dir = new Vector2(d.x,d.y);
dir.x += p.dir.x/30;
dir.y += p.dir.y/30;
lifespan = 100;
parent = p;
}
}

How to fill a shape with an image JavaFX

I am currently trying to create a game with falling "asteroids" that a ship has to dodge. I have currently created a pane that is a large circle stacked with multiple smaller circles. Unfortunately, the pane's "hitbox" is a square/rectangle, rather than a circle, which is frustrating. The other alternate way of fixing this would be to create a circle and fill it with an image of an asteroid, but I couldn't find this anywhere. I know of:
circle.setFill(Color.WHATEVER);
but i would like for it to look like an asteroid, not just a simple grey circle falling. To sum it up, how can I set an image to a shape? Or, if there is a way to change the hitbox of a stackpane, a way to do that would also help fix my issue!
Any help is greatly appreciated! Thanks!
EDIT:
Below are the 4 files that will make a simplified version of my game work with the same problem:
DodgerRemake:
package javafxapplication6;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class DodgerRemake extends Application
{
private Spaceship thisSpaceShip = new Spaceship();
private BoxPane gamePane = new BoxPane(thisSpaceShip);
BorderPane pane = new BorderPane();
private BooleanProperty upPressed = new SimpleBooleanProperty();
private BooleanProperty rightPressed = new SimpleBooleanProperty();
private BooleanProperty downPressed = new SimpleBooleanProperty();
private BooleanProperty leftPressed = new SimpleBooleanProperty();
private BooleanBinding anyPressed = upPressed.or(rightPressed).or(downPressed).or(leftPressed);
protected BorderPane getPane()
{
StackPane centerPane = new StackPane();
centerPane.getChildren().add(gamePane);
pane.setCenter(centerPane);
Button thisButton = new Button("Start");
thisButton.setAlignment(Pos.CENTER);
thisButton.setFocusTraversable(false);
thisButton.setOnAction(new startGame());
pane.setLeft(thisButton);
return pane;
}
#Override
public void start(Stage primaryStage) {
// Create a scene and place it in the stage
Scene scene = new Scene(getPane(), 960, 800);
primaryStage.setTitle("Dodger"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.setResizable(false);
primaryStage.show(); // Display the stage
scene.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.UP) {
upPressed.set(true);
}
if (e.getCode() == KeyCode.DOWN) {
downPressed.set(true);
}
if (e.getCode() == KeyCode.RIGHT) {
rightPressed.set(true);
}
if (e.getCode() == KeyCode.LEFT) {
leftPressed.set(true);
}
});
scene.setOnKeyReleased(e -> {
if (e.getCode() == KeyCode.UP) {
upPressed.set(false);
}
if (e.getCode() == KeyCode.DOWN) {
downPressed.set(false);
}
if (e.getCode() == KeyCode.RIGHT) {
rightPressed.set(false);
}
if (e.getCode() == KeyCode.LEFT) {
leftPressed.set(false);
}
});
AnimationTimer timer = new AnimationTimer()
{
#Override
public void handle(long timestamp) {
if (upPressed.get()){
gamePane.moveShipUp();
}
if (downPressed.get()){
gamePane.moveShipDown();
}
if (rightPressed.get()) {
gamePane.moveShipRight();
}
if (leftPressed.get()) {
gamePane.moveShipLeft();
}
}
};
anyPressed.addListener((obs, wasPressed, isNowPressed) ->
{
if (isNowPressed) {
timer.start();
} else {
timer.stop();
}
});
}
class startGame implements EventHandler<ActionEvent>
{
#Override
public void handle(ActionEvent e)
{
gamePane.addSpaceship();
gamePane.startGame();
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
BoxPane:
package javafxapplication6;
import java.util.Random;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.layout.Pane;
import javafx.util.Duration;
class BoxPane extends Pane
{
private Spaceship spaceShip;
private Timeline asteroids;
private double x;
private double y;
BoxPane(Spaceship thisSpaceShip)
{
spaceShip = thisSpaceShip;
spaceShip.setRotate(180);
}
public void addSpaceship()
{
getChildren().add(spaceShip);
x = 400 - spaceShip.getWidth()/2;
y = 740;
spaceShip.setTranslateX(x);
spaceShip.setTranslateY(y);
}
public void moveShipLeft()
{
if(x > 0)
{
spaceShip.setTranslateX(x-5);
x = x-5;
}
else
{
spaceShip.setTranslateX(0);
x = 0;
}
}
public void moveShipRight()
{
if(x+spaceShip.getWidth() < getWidth())
{
spaceShip.setTranslateX(x+5);
x = x+5;
}
else
{
spaceShip.setTranslateX(getWidth() - spaceShip.getWidth());
x = getWidth() - spaceShip.getWidth();
}
}
public void moveShipUp()
{
if(y > 0)
{
spaceShip.setTranslateY(y-5);
y = y-5;
}
else
{
spaceShip.setTranslateY(0);
y = 0;
}
}
public void moveShipDown()
{
if(y+spaceShip.getHeight() < getHeight())
{
spaceShip.setTranslateY(y+5);
y = y+5;
}
else
{
spaceShip.setTranslateY(getHeight() - spaceShip.getHeight());
y = getHeight() - spaceShip.getHeight();
}
}
public void startGame()
{
//addSpaceship();
asteroids = new Timeline(new KeyFrame(Duration.seconds(.5), e -> displayAsteroid()));
asteroids.setCycleCount(Timeline.INDEFINITE);
asteroids.play();
}
public void displayAsteroid()
{
Asteroid asteroid = new Asteroid();
getChildren().add(asteroid);
Random rand = new Random();
int randomNum = rand.nextInt((int) (getWidth() - asteroid.getWidth()));
asteroid.setY(-200);
asteroid.setX(randomNum);
asteroid.setTranslateY(asteroid.getY());
asteroid.setTranslateX(asteroid.getX());
Timeline timeline = new Timeline();
KeyFrame keyFrame = new KeyFrame(Duration.millis(50), event -> {
if(asteroid.getY() > getHeight()|| asteroid.getBoundsInParent().intersects(spaceShip.getBoundsInParent()))
{
timeline.stop();
getChildren().remove(asteroid);
}
else
{
asteroid.setY(asteroid.getY()+5);
asteroid.setTranslateY(asteroid.getY());
}
});
timeline.setCycleCount(Animation.INDEFINITE);
timeline.getKeyFrames().add(keyFrame);
timeline.play();
}
}
asteroid class:
package javafxapplication6;
import javafx.geometry.Pos;
import java.util.Random;
import java.util.Vector;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
public class Asteroid extends StackPane
{
private Ellipse asteroid = new Ellipse();
private Ellipse hole1 = new Ellipse();
private Ellipse hole2 = new Ellipse();
private Ellipse hole3 = new Ellipse();
private int speed;
private double y = 0;
private double x = 0;
Asteroid()
{
Random rand = new Random();
int asteroidNum = rand.nextInt(10);
if(asteroidNum < 6)
{
asteroidNum = 0;
}
else if(asteroidNum < 8)
{
asteroidNum = 1;
}
else
{
asteroidNum = 2;
}
StackPane thisAsteroid = new StackPane();
VBox vbox = new VBox();
HBox hbox = new HBox();
vbox.setAlignment(Pos.CENTER);
hbox.setAlignment(Pos.CENTER);
asteroid.setFill(Color.GREY);
asteroid.setStroke(Color.DIMGREY);
hole1.setFill(Color.DIMGREY);
hole1.setStroke(Color.BLACK);
hole2.setFill(Color.DIMGREY);
hole2.setStroke(Color.BLACK);
hole3.setFill(Color.DIMGREY);
hole3.setStroke(Color.BLACK);
switch(asteroidNum)
{
case 0: asteroid1();
vbox.setSpacing(10);
hbox.setSpacing(10);
break;
case 1: asteroid2();
vbox.setSpacing(15);
hbox.setSpacing(15);
break;
case 2: asteroid3();
vbox.setSpacing(25);
hbox.setSpacing(25);
break;
}
int holeLayout = rand.nextInt(3);
switch(holeLayout)
{
case 0: hbox.getChildren().addAll(hole1, hole2);
vbox.getChildren().addAll(hole3, hbox);
thisAsteroid.getChildren().addAll(asteroid, vbox);
break;
case 1: vbox.getChildren().addAll(hole2, hole3);
hbox.getChildren().addAll(vbox, hole1);
thisAsteroid.getChildren().addAll(asteroid, hbox);
break;
case 2: vbox.getChildren().addAll(hole1, hole3);
hbox.getChildren().addAll(hole2, vbox);
thisAsteroid.getChildren().addAll(asteroid, hbox);
break;
case 3: hbox.getChildren().addAll(hole1, hole2);
vbox.getChildren().addAll(hbox, hole3);
thisAsteroid.getChildren().addAll(asteroid, vbox);
break;
}
this.getChildren().add(thisAsteroid);
}
public void asteroid1()
{
speed = 10;
asteroid.setRadiusX(40);
asteroid.setRadiusY(35);
asteroid.setStrokeWidth(3);
hole1.setRadiusX(7);
hole1.setRadiusY(8);
hole2.setRadiusX(9);
hole2.setRadiusY(6);
hole3.setRadiusX(6);
hole3.setRadiusY(5);
}
public void asteroid2()
{
speed = 6;
asteroid.setRadiusX(60);
asteroid.setRadiusY(50);
asteroid.setStrokeWidth(5);
hole1.setRadiusX(10);
hole1.setRadiusY(12);
hole2.setRadiusX(12);
hole2.setRadiusY(10);
hole3.setRadiusX(14);
hole3.setRadiusY(13);
}
public void asteroid3()
{
speed = 4;
asteroid.setRadiusX(100);
asteroid.setRadiusY(90);
asteroid.setStrokeWidth(8);
hole1.setRadiusX(20);
hole1.setRadiusY(18);
hole2.setRadiusX(18);
hole2.setRadiusY(22);
hole3.setRadiusX(23);
hole3.setRadiusY(19);
}
public void setY(double nY)
{
y = nY;
}
public void setX(double nX)
{
x = nX;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public int getSpeed()
{
return speed;
}
}
spaceship class:
package javafxapplication6;
import javafx.geometry.Pos;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;
public class Spaceship extends StackPane
{
private Rectangle leftWingBottom = new Rectangle();
private Rectangle leftWingGun = new Rectangle();
private Rectangle leftWingDesign = new Rectangle();
private Rectangle leftWingAttachment = new Rectangle();
private Rectangle leftTransparent = new Rectangle();
private Rectangle rightWingBottom = new Rectangle();
private Rectangle rightWingGun = new Rectangle();
private Rectangle rightWingDesign = new Rectangle();
private Rectangle rightWingAttachment = new Rectangle();
private Rectangle rightTransparent = new Rectangle();
private Rectangle centerCompartmentBottom = new Rectangle();
private Rectangle centerCompartmentDesign = new Rectangle();
private Ellipse centerCompartmentTop = new Ellipse();
Spaceship()
{
HBox ship = new HBox();
VBox leftWing = new VBox();
VBox rightWing = new VBox();
VBox leftAttachment = new VBox();
VBox rightAttachment = new VBox();
StackPane leftWingStack = new StackPane();
StackPane rightWingStack = new StackPane();
StackPane centerCompartmentShip = new StackPane();
leftTransparent.setFill(Color.TRANSPARENT);
rightTransparent.setFill(Color.TRANSPARENT);
// creates the right wing
rightWingBottom.setHeight(30);
rightWingBottom.setWidth(8);
rightWingBottom.setStrokeWidth(1);
rightWingDesign.setHeight(25);
rightWingDesign.setWidth(3);
rightWingStack.setAlignment(Pos.CENTER);
rightWingStack.getChildren().addAll(rightWingBottom, rightWingDesign);
rightWingGun.setHeight(5);
rightWingGun.setWidth(2);
rightWing.setAlignment(Pos.TOP_CENTER);
rightWing.getChildren().addAll(rightWingStack, rightWingGun);
// creates the left wing and gun
leftWingBottom.setHeight(30);
leftWingBottom.setWidth(8);
leftWingBottom.setStrokeWidth(1);
leftWingDesign.setHeight(25);
leftWingDesign.setWidth(3);
leftWingStack.setAlignment(Pos.CENTER);
leftWingStack.getChildren().addAll(leftWingBottom, leftWingDesign);
leftWingGun.setHeight(5);
leftWingGun.setWidth(2);
leftWing.setAlignment(Pos.TOP_CENTER);
leftWing.getChildren().addAll(leftWingStack, leftWingGun);
// attaches the cockpit and right wing together
rightTransparent.setHeight(5);
rightTransparent.setWidth(5);
rightWingAttachment.setHeight(3);
rightWingAttachment.setWidth(5);
rightAttachment.setAlignment(Pos.TOP_CENTER);
rightAttachment.getChildren().addAll(rightTransparent, rightWingAttachment);
// attaches the cockpit and left wing together
leftTransparent.setHeight(5);
leftTransparent.setWidth(5);
leftWingAttachment.setHeight(3);
leftWingAttachment.setWidth(5);
leftAttachment.setAlignment(Pos.TOP_CENTER);
leftAttachment.getChildren().addAll(leftTransparent, leftWingAttachment);
// creates the cockpit
centerCompartmentBottom.setHeight(25);
centerCompartmentBottom.setWidth(20);
centerCompartmentBottom.setStrokeWidth(2);
centerCompartmentTop.setRadiusX(10);
centerCompartmentTop.setRadiusY(25);
centerCompartmentTop.setStrokeWidth(2);
centerCompartmentDesign.setHeight(25);
centerCompartmentDesign.setWidth(5);
centerCompartmentShip.setAlignment(Pos.TOP_CENTER);
centerCompartmentShip.getChildren().addAll(centerCompartmentTop, centerCompartmentBottom, centerCompartmentDesign);
rightWingBottom.setFill(Color.WHITE);
rightWingBottom.setStroke(Color.GREY);
leftWingBottom.setFill(Color.WHITE);
leftWingBottom.setStroke(Color.GREY);
rightWingGun.setFill(Color.WHITE);
leftWingGun.setFill(Color.WHITE);
rightWingDesign.setFill(Color.TRANSPARENT);
leftWingDesign.setFill(Color.TRANSPARENT);
rightWingAttachment.setFill(Color.WHITE);
rightWingAttachment.setStroke(Color.GREY);
leftWingAttachment.setFill(Color.WHITE);
leftWingAttachment.setStroke(Color.GREY);
centerCompartmentBottom.setFill(Color.WHITE);
centerCompartmentBottom.setStroke(Color.GREY);
centerCompartmentTop.setFill(Color.WHITE);
centerCompartmentTop.setStroke(Color.GREY);
centerCompartmentDesign.setFill(Color.TRANSPARENT);
// adds everything to final hbox
ship.getChildren().addAll(rightWing,
rightAttachment,
centerCompartmentShip,
leftAttachment,
leftWing);
// adds it to the SpaceShip object
this.getChildren().add(ship);
}
}
Hope this helps, thanks!

How to retrieve data from mysql database from what is the input on my textfield

For example I have entered my pin to 123 in my text field I want that program to Show the balance, card number and account number of that certain pin
i used setters and getters to get the pin from the previous frame (login)
Here is my code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.table.*;
public class Test extends JFrame
{
private static final Test sh1 = new Test();
public static Test getInstance()
{
return sh1;
}
Container c;
Connection con;
Statement st;
ResultSet rs;
ResultSetMetaData rm;
JTable tb;
JButton btnback = new JButton("Back");
JTextField pin = new JTextField("");
public void setUser(String user) {this.pin.setText(user);}
public String getUser() {return this.pin.getText();}
public Test(){
this.setTitle("Data");
this.setSize(500,500);
this.setLocation(800, 80);
this.setBackground(Color.black);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=this.getContentPane();
c.setLayout(new FlowLayout());
c.add(btnback);
c.add(pin);
stud();
}
public void stud()
{
Vector ColName = new Vector();
Vector Data = new Vector();
try{
String driver="com.mysql.jdbc.Driver";
String db="jdbc:mysql://localhost:3306/atm";
String user="root";
String pass="";
Class.forName(driver);
con=DriverManager.getConnection(db,user,pass);
st=con.createStatement();
String pincodee = pin.getText().trim();
String sqltb = "Select balance,cardnumber , accountnumber from accounts WHERE "
+ "pincode = '"+pincodee+"' ";
rs = st.executeQuery(sqltb);
rm = rs.getMetaData();
int col = rm.getColumnCount();
for(int i = 1; i <= col; i++)
{
ColName.addElement(rm.getColumnName(i));
}
while(rs.next())
{
Vector row = new Vector(col);
for(int i = 1; i <= col; i++)
{
row.addElement(rs.getObject(i));
String s = rs.getString(2);
pin.setText(s);
}
Data.addElement(row);
}
}
catch (Exception ex)
{
}
tb = new JTable( Data, ColName);
tb.repaint();
JScrollPane sc = new JScrollPane(tb);
sc.validate();
c.add(sc);
}
public static void main(String[] args)
{
Test s = new Test();
s.setVisible(true);
}
}
You need to create a button which says 'Go!' or something like that and add an action listener to it that calls your stud() method.
look here for example..
http://www.javaprogrammingforums.com/java-swing-tutorials/278-how-add-actionlistener-jbutton-swing.html
Your code is not going to work either way, you need to rewrite a great deal of it but the ActionListener class is your friend if you want actions on the user interface to call logic code.

JavaFX : Canvas to Image in non GUI Thread

I have to visualize lot of data (real-time) and I am using JavaFX 2.2. So I have decided to "pre-visualize" data before they are inserted into GUI thread.
In my opinion the fastest way to do it (with antialliasing etc.) is let some NON GUI thread to generate image/bitmap and then put in GUI thread (so the UI is still responsive for user).
But I can't find way how to conver Canvas to Image and then use:
Image imageToDraw = convert_tmpCanvasToImage(tmpCanvas);
Platform.runLater(new Runnable() {
#Override
public void run() {
canvas.getGraphicsContext2D().drawImage(imageToDraw, data.offsetX, data.offsetY);
}
});
Thx for some usable answers. :-)
btw: I have made test app to show my problem.
package canvasandthreads02;
import java.util.Random;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class CanvasAndThreads02 extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Paint");
final AnchorPane root = new AnchorPane();
final Canvas canvas = new Canvas(900, 800);
canvas.setLayoutX(50);
canvas.setLayoutY(50);
root.getChildren().add(canvas);
root.getChildren().add(btn);
Scene scene = new Scene(root, 900, 800);
primaryStage.setTitle("Painting in JavaFX");
primaryStage.setScene(scene);
primaryStage.show();
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Start painting");
/**
* Start Thread where some data will be visualized
*/
new Thread(new PainterThread(canvas, new DataToPaint())).start();
}
});
}
private class PainterThread implements Runnable{
private final DataToPaint data;
private final Canvas canvas;
public PainterThread(Canvas canvas, DataToPaint data){
this.canvas = canvas;
this.data = data;
}
#Override
public void run() {
long currentTimeMillis = System.currentTimeMillis();
Canvas tmpCanvas = new Canvas(data.width, data.height);
GraphicsContext graphicsContext2D = tmpCanvas.getGraphicsContext2D();
graphicsContext2D.setFill(data.color;);
for (int i = 0; i < data.height; i++) {
for (int j = 0; j < data.width; j++) {
graphicsContext2D.fillRect(j, i, 1, 1); //draw 1x1 rectangle
}
}
/**
* And now I need still in this Thread convert tmpCanvas to Image,
* or use some other method to put result to Main GIU Thread using Platform.runLater(...);
*/
final Image imageToDraw = convert_tmpCanvasToImage(tmpCanvas);
System.out.println("Canvas painting: " + (System.currentTimeMillis()-currentTimeMillis));
Platform.runLater(new Runnable() {
#Override
public void run() {
//Start painting\n Canvas painting: 430 \n Time to convert:62
//long currentTimeMillis1 = System.currentTimeMillis();
//Image imageToDraw = tmpCanvas.snapshot(null, null);
//System.out.println("Time to convert:" + (System.currentTimeMillis()-currentTimeMillis1));
canvas.getGraphicsContext2D().drawImage(imageToDraw, data.offsetX, data.offsetY);
}
});
}
}
private class DataToPaint{
double offsetX = 0;
double offsetY = 0;
Color color;
int width = 500;
int height = 250;
public DataToPaint(){
Random rand = new Random();
color = new Color(rand.nextDouble(), rand.nextDouble(), rand.nextDouble(), rand.nextDouble());
offsetX = rand.nextDouble() * 20;
offsetY = rand.nextDouble() * 20;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
use Canvas' snapshot(...) method to create a WritableImage from the Canvas' content. ^^
Works fine for me.
I know this is a really old question, but just for anyone who cares:
There is now a second version of canvas.snapshot that takes a callback and works asynchronously!
public void snapshot(Callback<SnapshotResult,Void> callback,
SnapshotParameters params,
WritableImage image)

Resources