Draw circle in border of rectangle in JavaFX - java

I want add some circles in border of a rectangle in event onMouseMoved.
Need to develop a graph using JavaFX and these circles will serve to connect the edges to the graph nodes.
See the image below:
I'm using JavaFX.
See you the code:
public class SampleDragAndDrop extends Application {
public static void main(String[] args) throws Exception {
launch(args);
}
#Override
public void start(final Stage stage) throws Exception {
DoubleProperty entity1X = new SimpleDoubleProperty(100);
DoubleProperty entity1Y = new SimpleDoubleProperty(100);
Entity entity1 = new Entity(Color.STEELBLUE, entity1X, entity1Y);
Screen screen = Screen.getPrimary();
Rectangle2D bounds = screen.getVisualBounds();
stage.setX(bounds.getMinX());
stage.setY(bounds.getMinY());
stage.setWidth(bounds.getWidth());
stage.setHeight(bounds.getHeight());
stage.setTitle("Draw circle in rectangle");
stage.setScene(new Scene(new Group(entity1), 400, 400, Color.ALICEBLUE));
stage.show();
}
class Anchor extends Circle {
Anchor(Color color, DoubleProperty x, DoubleProperty y) {
super(x.get(), y.get(), 20);
setFill(color.deriveColor(1, 1, 1, 0.5));
setStroke(color);
setStrokeWidth(2);
setStrokeType(StrokeType.OUTSIDE);
x.bind(centerXProperty());
y.bind(centerYProperty());
}
class Entity extends Rectangle {
Entity(Color color, DoubleProperty x, DoubleProperty y) {
setX(x.get());
setY(y.get());
setWidth(120);
setHeight(50);
setFill(color.deriveColor(1, 1, 1, 0.5));
setStroke(color);
setStrokeWidth(2);
setStrokeType(StrokeType.OUTSIDE);
setArcWidth(20);
setArcHeight(20);
x.bind(xProperty());
y.bind(yProperty());
enableDrag();
}
private void enableDrag() {
final Entity.Delta dragDelta = new Entity.Delta();
setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
dragDelta.x = getX() - mouseEvent.getX();
dragDelta.y = getY() - mouseEvent.getY();
getScene().setCursor(Cursor.MOVE);
}
});
setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
getScene().setCursor(Cursor.HAND);
}
});
setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
double newX = mouseEvent.getX() + dragDelta.x;
if (newX > 0 && newX < getScene().getWidth()) {
setX(newX);
}
double newY = mouseEvent.getY() + dragDelta.y;
if (newY > 0 && newY < getScene().getHeight()) {
setY(newY);
}
}
});
setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
getScene().setCursor(Cursor.HAND);
}
}
});
setOnMouseExited(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
getScene().setCursor(Cursor.DEFAULT);
}
}
});
setOnMouseMoved(new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent mouseEvent) {
// Create circles in rectangle here
}
});
}
private class Delta {
double x, y;
}
}
}
How can I do?
Thank you!

This works:
// Create circles in rectangle here
// Not sure you really need these?
DoubleProperty leftX = new SimpleDoubleProperty();
DoubleProperty leftY = new SimpleDoubleProperty();
Anchor leftAnchor = new Anchor(Color.STEELBLUE, leftX, leftY);
leftAnchor.centerXProperty().bind(xProperty());
leftAnchor.centerYProperty().bind(yProperty().add(heightProperty().divide(2)));
((Group)getParent()).getChildren().add(leftAnchor);

Related

Anchor Points Do Not Follow Polygon - JavaFX

Currently I have a polygon which can be resized and shaped as required. The problem is when I move the polygon the anchor points remain fixed to their position and do not move with the polygon, I am really confused and was hoping someone could help or guide me.
public Polygon createStartingFloorPlan(ActionEvent event) throws IOException {
Polygon fp = new Polygon();
ObjectProperty<Point2D> mousePosition = new SimpleObjectProperty<>();
fp.getPoints().setAll(
150d, 50d,
450d, 50d,
750d, 50d,
750d, 350d,
750d, 650d,
450d, 650d,
150d, 650d,
150d, 350d
);
fp.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
}
});
fp.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
double deltaX = event.getSceneX() - mousePosition.get().getX();
double deltaY = event.getSceneY() - mousePosition.get().getY();
fp.setLayoutX(fp.getLayoutX()+deltaX);
fp.setLayoutY(fp.getLayoutY()+deltaY);
mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
createControlAnchorsFor(fp.getPoints());
}
});
fp.setStroke(Color.FORESTGREEN);
fp.setStrokeWidth(4);
fp.setStrokeLineCap(StrokeLineCap.ROUND);
fp.setFill(Color.CORNSILK.deriveColor(0, 1.2, 1, 0.6));
container.getChildren().add(fp);
container.getChildren().addAll(createControlAnchorsFor(fp.getPoints()));
return fp;
}
private ObservableList<Anchor> createControlAnchorsFor(final ObservableList<Double> points) {
ObservableList<Anchor> anchors = FXCollections.observableArrayList();
for (int i = 0; i < points.size(); i += 2) {
final int idx = i;
DoubleProperty xProperty = new SimpleDoubleProperty(points.get(i));
DoubleProperty yProperty = new SimpleDoubleProperty(points.get(i + 1));
xProperty.addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> ov, Number oldX, Number x) {
points.set(idx, (double) x);
}
});
yProperty.addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> ov, Number oldY, Number y) {
points.set(idx + 1, (double) y);
}
});
anchors.add(new Anchor(Color.GOLD, xProperty, yProperty));
}
return anchors;
}
// a draggable anchor displayed around a point.
class Anchor extends Circle {
private final DoubleProperty x, y;
Anchor(Color color, DoubleProperty x, DoubleProperty y) {
super(x.get(), y.get(), 10);
setFill(color.deriveColor(1, 1, 1, 0.5));
setStroke(color);
setStrokeWidth(2);
setStrokeType(StrokeType.OUTSIDE);
this.x = x;
this.y = y;
x.bind(centerXProperty());
y.bind(centerYProperty());
enableDrag();
}
// make a node movable by dragging it around with the mouse.
private void enableDrag() {
final Delta dragDelta = new Delta();
setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
dragDelta.x = getCenterX() - mouseEvent.getX();
dragDelta.y = getCenterY() - mouseEvent.getY();
getScene().setCursor(Cursor.MOVE);
}
});
setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
getScene().setCursor(Cursor.HAND);
}
});
setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
double newX = mouseEvent.getX() + dragDelta.x;
if (newX > 0 && newX < getScene().getWidth()) {
setCenterX(newX);
}
double newY = mouseEvent.getY() + dragDelta.y;
if (newY > 0 && newY < getScene().getHeight()) {
setCenterY(newY);
}
}
});
setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
getScene().setCursor(Cursor.HAND);
}
}
});
setOnMouseExited(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
getScene().setCursor(Cursor.DEFAULT);
}
}
});
}
// records relative x and y co-ordinates.
private class Delta {
double x, y;
}
}
Problem
The coordinates where the points of the Polygon are drawn are (layoutX + pointX, layoutY + pointY) assuming there are no transforms applied to the node.
You never adjust the layoutX and layoutY properties of the Anchors though. To fix this you can bind them to the properties of the Polygon:
private ObservableList<Anchor> createControlAnchorsFor(Polygon polygon, final ObservableList<Double> points) {
...
Anchor anchor = new Anchor(Color.GOLD, xProperty, yProperty);
anchor.layoutXProperty().bind(polygon.layoutXProperty());
anchor.layoutYProperty().bind(polygon.layoutYProperty());
anchors.add(anchor);
...
}
Furthermore I recommend using a custom DoubleProperty class instead of using SimpleDoublePropertys with listeners, since by this you make the code a bit more readable and also reduce the number of objects by one per coordinate:
private static class ListWriteDoubleProperty extends SimpleDoubleProperty {
private final ObservableList<Double> list;
private final int index;
public ListWriteDoubleProperty(ObservableList<Double> list, int index) {
super(list.get(index));
this.list = list;
this.index = index;
}
#Override
protected void invalidated() {
list.set(index, get());
}
}
DoubleProperty xProperty = new ListWriteDoubleProperty(points, i);
DoubleProperty yProperty = new ListWriteDoubleProperty(points, i + 1);
// no more listeners/final index copy required...

libgdx click area above target

I'm trying to make a simple main menu with clickable play and exit labels, but clickable area is always above labels. To click "play" label I need to click about 20 pixels above it.
How can I align clickable area with labels?
There is my MainMenuButton class
public class MainMenuButtons {
private MainGame game;
private Stage stage;
private Viewport gameViewport;
private Label mainGameLabel, playLabel, exitLabel;
public MainMenuButtons(MainGame game) {
this.game = game;
gameViewport = new FillViewport(GameInfo.WIDTH, GameInfo.HEIGHT, new OrthographicCamera());
stage = new Stage(gameViewport, game.getBatch());
Gdx.input.setInputProcessor(stage);
createLabelsAndButtons();
addAllListeners();
Table menuTable = new Table();
menuTable.center().center();
menuTable.setFillParent(true);
menuTable.add(playLabel);
menuTable.row();
menuTable.add(exitLabel).padTop(40);
Table gameTitle = new Table();
gameTitle.center().top();
gameTitle.setFillParent(true);
gameTitle.add(mainGameLabel).padTop(40);
menuTable.debug();
stage.addActor(menuTable);
stage.addActor(gameTitle);
}
void createLabelsAndButtons() {
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("Fonts/PressStart2P.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 45;
BitmapFont font = generator.generateFont(parameter);
mainGameLabel = new Label("Road Racer", new Label.LabelStyle(font, Color.WHITE));
parameter.size = 25;
font = generator.generateFont(parameter);
playLabel = new Label("Play", new Label.LabelStyle(font, Color.WHITE));
exitLabel = new Label("Exit", new Label.LabelStyle(font, Color.WHITE));
}
void addAllListeners() {
playLabel.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
System.out.println("Play label clicked " + y);
// game.setScreen(new GamePlay(game));
}
});
exitLabel.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
System.out.println("Exit label clicked " + y);
// Gdx.app.exit();
}
});
}
public Stage getStage() {
return this.stage;
}
}
And I call it in the MainMenu class
/**
* Created by vladk on 24/09/16.
*/
public class MainMenu implements Screen {
private MainGame game;
private OrthographicCamera mainCamera;
private Viewport gameViewport;
private MainMenuButtons btns;
public MainMenu(MainGame game) {
this.game = game;
mainCamera = new OrthographicCamera();
mainCamera.setToOrtho(false, GameInfo.WIDTH, GameInfo.HEIGHT);
mainCamera.position.set(GameInfo.WIDTH / 2f, GameInfo.HEIGHT / 2f, 0);
gameViewport = new StretchViewport(GameInfo.WIDTH, GameInfo.HEIGHT, mainCamera);
// background ??
// buttons
btns = new MainMenuButtons(game);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// game.getBatch().begin();
// game.getBatch().end();
game.getBatch().setProjectionMatrix(btns.getStage().getCamera().combined);
btns.getStage().draw();
btns.getStage().act();
}
#Override
public void resize(int width, int height) {
gameViewport.update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
// bg
// buttons
btns.getStage().dispose();
}
}
I found a solution. I needed to update view port for the MainMenuButtons, so I created a new method
// in the MainMenuButtons class
public void viewportUpdate(int width, int height) {
gameViewport.update(width, height);
}
and call if from the MainMenu class
#Override
public void resize(int width, int height) {
gameViewport.update(width, height);
btns.viewportUpdate(width, height);
}

Extend content of a Scrollpane if smaller than viewport

I want to make a ScrollPane with a custom Pane inside, that has two Children. One that holds my objects and one just for the background. I want to make it so if I zoom out, and the content is smaller than the viewport, then the size of the content would expand, filling in the new place in the viewport. And if I zoom back then it would remain the same, and I have now a larger content in area. The new width of the content would be: originalWidth + viewportWidth - scaledWidth.
I have made the grid, and the zooming works, but I can't make it so that it resizes the content. I have tried to set the content size when zooming to the current viewport size, but it does not work.
Question:
What am I doing wrong?
The layout is defined in fxml. Another than ScrollPane content set to fill height and width nothing out of ordinary there.
CustomPane class:
public class CustomPane extends StackPane implements Initializable {
#FXML
StackPane view;
#FXML
AnchorPane objectPane;
#FXML
GriddedPane background;
private DoubleProperty zoomFactor = new SimpleDoubleProperty(1.5);
private BooleanProperty altStatus = new SimpleBooleanProperty(false);
public CustomPane() {
super();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getClassLoader().getResource("CustomCanvas.fxml"));
loader.setController(this);
loader.setRoot(this);
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
objectPane.setStyle("-fx-background-color: transparent");
objectPane.prefWidthProperty().bind(prefWidthProperty());
objectPane.prefHeightProperty().bind(prefHeightProperty());
objectPane.getChildren().add(new Circle(512, 378, 20, Color.RED));
}
public void zoom(ScrollPane parent, Node node, double factor, double x, double y) {
Timeline timeline = new Timeline(60);
// determine scale
double oldScale = node.getScaleX();
double scale = oldScale * factor;
double f = (scale / oldScale) - 1;
// determine offset that we will have to move the node
Bounds bounds = node.localToScene(node.getBoundsInLocal());
double dx = (x - (bounds.getWidth() / 2 + bounds.getMinX()));
double dy = (y - (bounds.getHeight() / 2 + bounds.getMinY()));
// timeline that scales and moves the node
timeline.getKeyFrames().clear();
timeline.getKeyFrames().addAll(
new KeyFrame(Duration.millis(100), new KeyValue(node.translateXProperty(), node.getTranslateX() - f * dx)),
new KeyFrame(Duration.millis(100), new KeyValue(node.translateYProperty(), node.getTranslateY() - f * dy)),
new KeyFrame(Duration.millis(100), new KeyValue(node.scaleXProperty(), scale)),
new KeyFrame(Duration.millis(100), new KeyValue(node.scaleYProperty(), scale))
);
timeline.play();
Bounds viewportBounds = parent.getViewportBounds();
if (bounds.getWidth() < viewportBounds.getWidth()) {
setMinWidth(viewportBounds.getWidth());
requestLayout();
}
if (getMinHeight() < viewportBounds.getHeight()) {
setMinHeight(viewportBounds.getHeight());
requestLayout();
}
}
public final Double getZoomFactor() {
return zoomFactor.get();
}
public final void setZoomFactor(Double zoomFactor) {
this.zoomFactor.set(zoomFactor);
}
public final DoubleProperty zoomFactorProperty() {
return zoomFactor;
}
public boolean getAltStatus() {
return altStatus.get();
}
public BooleanProperty altStatusProperty() {
return altStatus;
}
public void setAltStatus(boolean altStatus) {
this.altStatus.set(altStatus);
}
}
Controller class:
public class Controller implements Initializable {
public ScrollPane scrollPane;
public CustomPane customPane;
public AnchorPane anchorPane;
public Tab tab1;
#Override
public void initialize(URL location, ResourceBundle resources) {
scrollPane.viewportBoundsProperty().addListener((observable, oldValue, newValue) -> {
customPane.setMinSize(newValue.getWidth(), newValue.getHeight());
});
scrollPane.requestLayout();
tab1.getTabPane().addEventFilter(KeyEvent.KEY_PRESSED, event1 -> {
if (event1.getCode() == KeyCode.ALT)
customPane.setAltStatus(true);
});
tab1.getTabPane().addEventFilter(KeyEvent.KEY_RELEASED, event1 -> {
if (event1.getCode() == KeyCode.ALT)
customPane.setAltStatus(false);
});
scrollPane.setOnScroll(event -> {
double zoomFactor = 1.5;
if (event.getDeltaY() <= 0)
zoomFactor = 1 / zoomFactor;
customPane.setZoomFactor(zoomFactor);
if (customPane.getAltStatus())
customPane.zoom(scrollPane, customPane, customPane.getZoomFactor(), event.getSceneX(), event.getSceneY());
});
}
}
GriddedPane class:
public class GriddedPane extends Pane implements Initializable {
DoubleProperty gridWidth = new SimpleDoubleProperty(this, "gridWidth", 10);
DoubleProperty gridHeight = new SimpleDoubleProperty(this, "gridHeight", 10);
public GriddedPane() {
super();
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#Override
protected void layoutChildren() {
getChildren().clear();
setMouseTransparent(true);
toBack();
for (int i = 0; i < getHeight(); i += getGridWidth())
getChildren().add(makeLine(0, i, getWidth(), i, "x"));
for (int i = 0; i < getWidth(); i += getGridHeight())
getChildren().add(makeLine(i, 0, i, getHeight(), "y"));
}
public void redrawLines() {
for (Node n : getChildren()) {
Line l = (Line) n;
if (l.getUserData().equals("x")) {
l.setEndX(getWidth());
} else if (l.getUserData().equals("y")) {
l.setEndY(getHeight());
}
}
}
private Line makeLine(double sx, double sy, double ex, double ey, String data) {
final Line line = new Line(sx, sy, ex, ey);
if (ex % (getGridWidth() * 10) == 0.0) {
line.setStroke(Color.BLACK);
line.setStrokeWidth(0.3);
} else if (ey % (getGridHeight() * 10) == 0.0) {
line.setStroke(Color.BLACK);
line.setStrokeWidth(0.3);
} else {
line.setStroke(Color.GRAY);
line.setStrokeWidth(0.1);
}
line.setUserData(data);
return line;
}
public double getGridWidth() {
return gridWidth.get();
}
public DoubleProperty gridWidthProperty() {
return gridWidth;
}
public void setGridWidth(double gridWidth) {
this.gridWidth.set(gridWidth);
}
public double getGridHeight() {
return gridHeight.get();
}
public DoubleProperty gridHeightProperty() {
return gridHeight;
}
public void setGridHeight(double gridHeight) {
this.gridHeight.set(gridHeight);
}
}
Not really sure if I unterstood what you want to achieve. But if your goal is to make the content of the scrollPane never get smaller than the scrollPane's width, this does the job for me:
public class Zoom extends Application {
#Override
public void start(Stage primaryStage) {
ImageView imageView = new ImageView(new Image(someImage));
ScrollPane scrollPane = new ScrollPane(imageView);
StackPane root = new StackPane(scrollPane);
imageView.fitWidthProperty().bind(scrollPane.widthProperty());
imageView.fitHeightProperty().bind(scrollPane.heightProperty());
scrollPane.setOnScroll(evt -> {
boolean zoomOut = evt.getDeltaY() < 0;
double zoomFactor = zoomOut ? -0.2 : 0.2;
imageView.setScaleX(imageView.getScaleX() + zoomFactor);
imageView.setScaleY(imageView.getScaleY() + zoomFactor);
if (zoomOut) {
Bounds bounds = imageView.getBoundsInParent();
if (bounds.getWidth() < scrollPane.getWidth()) {
imageView.setScaleX(1);
imageView.setScaleY(1);
}
}
});
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Javafx drag and drop shapes on canvas

I am quite beginner in Java and need some help with my application.
I am would like to use drag and drop on custom made shapes with javafx canvas i.e multiple polygons that make up a bow tie.
I have created a method that draws a bow tie that looks like this:
public void joonistaBowTie(GraphicsContext gc) {
// Bowtie left side
gc.setFill(Color.RED);
double xpoints[] = { 242, 242, 200 };
double ypoints[] = { 245, 290, 270 };
int num = 3;
gc.fillPolygon(xpoints, ypoints, num);
// Bowtie right side
gc.setFill(Color.RED);
double xpoints1[] = { 160, 160, 200 };
double ypoints1[] = { 245, 290, 270 };
int num1 = 3;
gc.fillPolygon(xpoints1, ypoints1, num1);
// Bowtie middle part
gc.setFill(Color.RED);
gc.fillOval(190, 255, 20, 30);
}
I have moved that method into a separate class called BowTie.
I also have a main class that looks like this:
public class GraafikaNaide extends Application {
Bowtie bowtie;
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX-iga joonistatud kloun");
Group root = new Group();
Canvas canvas = new Canvas(1000, 1000);
GraphicsContext gc = canvas.getGraphicsContext2D();
joonista(gc);
root.getChildren().add(canvas);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
private void joonista(GraphicsContext gc) {
Bowtie bowtie = new Bowtie();
bowtie.joonistaBowTie(gc);
}
I also found somewhat example on how to do drag and drop, but i just lack knowledge on how to implement this code to mine.
Could someone please help me with this?
Thanks
Using the link you provided, here is how you would incorporate it with your work:
public class GraafikaNaide extends Application
{
joonistaBowTie bowtie;
double orgSceneX, orgSceneY;
double orgTranslateX, orgTranslateY;
#Override
public void start(Stage primaryStage)
{
Canvas canvas = new Canvas(1000, 1000);
GraphicsContext gc = canvas.getGraphicsContext2D();
joonista(gc);
canvas.setOnMousePressed(canvasOnMousePressedEventHandler);
canvas.setOnMouseDragged(canvasOnMouseDraggedEventHandler);
Group root = new Group();
root.getChildren().add(canvas);
primaryStage.setTitle("JavaFX-iga joonistatud kloun");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
private void joonista(GraphicsContext gc)
{
joonistaBowTie bowtie = new joonistaBowTie();
bowtie.joinBowTie(gc);
}
EventHandler<MouseEvent> canvasOnMousePressedEventHandler = new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent mouseEvent)
{
orgSceneX = mouseEvent.getSceneX();
orgSceneY = mouseEvent.getSceneY();
orgTranslateX = ((Canvas)(mouseEvent.getSource())).getTranslateX();
orgTranslateY = ((Canvas) (mouseEvent.getSource())).getTranslateY();
}
};
EventHandler<MouseEvent> canvasOnMouseDraggedEventHandler = new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent mouseEvent)
{
double offsetX = mouseEvent.getSceneX() - orgSceneX;
double offsetY = mouseEvent.getSceneY() - orgSceneY;
double newTranslateX = orgTranslateX + offsetX;
double newTranslateY = orgTranslateY + offsetY;
((Canvas) (mouseEvent.getSource())).setTranslateX(newTranslateX); //transform the object
((Canvas) (mouseEvent.getSource())).setTranslateY(newTranslateY);
}
};
}
Hope this helps.

Deleting Buffers LibGdx

I have created multiple Screens for my Libgdx game.
Whenever I exit the game (Desktop Version), I am getting a red sentence in eclipse console, showing Deleting Buffers(1).
The number is changing according to the Screen, which is active when I quit the game.
What is this "Deleting Buffers"?
Do I have to worry about that?
Also the android version of my game crashes at the second Screen, while the desktop version is running perfectly.
Thanks in advance.
Screen1
public class Splash implements Screen {
private SpriteBatch batch;
private Sprite titleSprite;
private Input input;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
batch.begin();
titleSprite.draw(batch);
batch.end();
Gdx.input.setInputProcessor(input);
}
#Override
public void show() {
batch = new SpriteBatch();
titleSprite = new Sprite(new Texture("img/Title.jpg"));
titleSprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
titleSprite.setOrigin(titleSprite.getWidth() / 2f,
titleSprite.getHeight() / 2f);
titleSprite.setPosition(
Gdx.graphics.getWidth() / 2f - titleSprite.getWidth() / 2f,
Gdx.graphics.getHeight() / 2f - titleSprite.getHeight() / 2f);
input = new Input() {
public boolean keyDown(int keycode) {
if (keycode == Keys.ENTER) {
((Game) Gdx.app.getApplicationListener())
.setScreen(new MainMenu());
Gdx.audio.newMusic(Gdx.files.internal("sounds/button.mp3"))
.play();
dispose();
}
if (keycode == Keys.ESCAPE) {
Gdx.app.exit();
}
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer,
int button) {
((Game) Gdx.app.getApplicationListener())
.setScreen(new MainMenu());
dispose();
return super.touchDown(screenX, screenY, pointer, button);
}
};
}
#Override
public void dispose() {
batch.dispose();
titleSprite.getTexture().dispose();
}
}
Screen2
public class MainMenu implements Screen {
private Stage stage;
private Table table;
private TextButton playButton, exitButton;
private Skin skin;
private BitmapFont white, black;
private TextureAtlas atlas;
private TextButtonStyle textButtonStyle;
private SpriteBatch batch;
private Sprite sprite;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
batch.begin();
sprite.draw(batch);
batch.end();
stage.act(delta);
stage.draw();
Gdx.input.setInputProcessor(stage);
if (Gdx.input.isKeyPressed(Keys.ESCAPE)) {
Gdx.app.exit();
}
}
#Override
public void show() {
batch = new SpriteBatch();
sprite = new Sprite(new Texture("img/Title.jpg"));
sprite.setOrigin(sprite.getWidth() / 2f, sprite.getHeight() / 2f);
sprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
sprite.setPosition(Gdx.graphics.getWidth() / 2f - sprite.getWidth()
/ 2f, Gdx.graphics.getHeight() / 2f - sprite.getHeight() / 2f);
sprite.setRotation(0);
white = new BitmapFont(Gdx.files.internal("fonts/White.fnt"), false);
black = new BitmapFont(Gdx.files.internal("fonts/Black.fnt"), false);
black.setScale(Gdx.graphics.getWidth() / 1440f,
Gdx.graphics.getHeight() / 900f);
stage = new Stage();
atlas = new TextureAtlas("ui/Button.pack");
skin = new Skin(atlas);
table = new Table(skin);
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
textButtonStyle = new TextButtonStyle();
textButtonStyle.up = skin.getDrawable("ButtonUp9");
textButtonStyle.down = skin.getDrawable("ButtonDown9");
textButtonStyle.pressedOffsetX = 1;
textButtonStyle.pressedOffsetY = -1;
textButtonStyle.font = black;
exitButton = new TextButton("Exit", textButtonStyle);
exitButton.pad(10);
playButton = new TextButton("Play", textButtonStyle);
playButton.pad(10);
playButton.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
((Game) Gdx.app.getApplicationListener())
.setScreen(new Scenarios());
Gdx.audio.newSound(Gdx.files.internal("sounds/button.mp3"))
.play(1);
Gdx.input.vibrate(50);
dispose();
}
});
exitButton.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
dispose();
}
});
table.add(playButton);
table.row();
table.add(exitButton);
table.getCell(exitButton).spaceTop(50f);
stage.addActor(table);
}
#Override
public void dispose() {
stage.dispose();
black.dispose();
white.dispose();
skin.dispose();
batch.dispose();
sprite.getTexture().dispose();
}
}
Screen3
public class Scenarios implements Screen {
private TextButtonStyle buttonStyle;
private TextButton[] scene;
private BitmapFont black;
private Stage stage;
private Table table;
private TextureAtlas atlas;
private Skin skin;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
stage.act(delta);
stage.draw();
Gdx.input.setInputProcessor(stage);
if (Gdx.input.isKeyPressed(Keys.BACKSPACE)) {
((Game) Gdx.app.getApplicationListener()).setScreen(new MainMenu());
} else if (Gdx.input.isKeyPressed(Keys.ESCAPE)) {
Gdx.app.exit();
}
}
#Override
public void show() {
atlas = new TextureAtlas("ui/Button.pack");
skin = new Skin(atlas);
stage = new Stage();
table = new Table(skin);
black = new BitmapFont(Gdx.files.internal("fonts/Black.fnt"), false);
black.setScale(Gdx.graphics.getWidth() / 1280f,
Gdx.graphics.getHeight() / 720f);
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
buttonStyle = new TextButtonStyle();
buttonStyle.up = skin.getDrawable("ButtonUp9");
buttonStyle.down = skin.getDrawable("ButtonDown9");
buttonStyle.pressedOffsetX = 1;
buttonStyle.pressedOffsetY = -1;
buttonStyle.font = black;
scene = new TextButton[3];
scene[0] = new TextButton("Scenario 1", buttonStyle);
scene[1] = new TextButton("Scenario 2", buttonStyle);
scene[2] = new TextButton("Scenario 3", buttonStyle);
scene[0].addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
((Game) Gdx.app.getApplicationListener())
.setScreen(new Intro1());
Gdx.audio.newSound(Gdx.files.internal("sounds/button.mp3"))
.play(1);
Gdx.input.vibrate(50);
dispose();
}
});
scene[1].addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
((Game) Gdx.app.getApplicationListener())
.setScreen(new Intro2());
Gdx.audio.newSound(Gdx.files.internal("sounds/button.mp3"))
.play(1);
Gdx.input.vibrate(50);
dispose();
}
});
scene[2].addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
((Game) Gdx.app.getApplicationListener())
.setScreen(new Intro3());
Gdx.audio.newSound(Gdx.files.internal("sounds/button.mp3"))
.play(1);
Gdx.input.vibrate(50);
dispose();
}
});
scene[0].pad(10);
scene[1].pad(10f);
scene[2].pad(10f);
table.add(scene[0]);
table.add(scene[1]);
table.getCell(scene[1]).space(20f);
table.add(scene[2]);
stage.addActor(table);
}
#Override
public void dispose() {
stage.dispose();
skin.dispose();
atlas.dispose();
black.dispose();
}
}
You forgot to dispose sound/music objects. You may do it in dispose method of your Game class.

Categories