JavaFX VBox and HBox layouts - layout

I'm working on a JavaFX application which has a layout generated from an external data structure, composed of
displaying components that know their own aspect ratios (height as a dependent of width)
2 types of structural components that
display all children with an equal width across their page, each child up as much vertical space as needed
display all children down the page using the full width and taking as much vertical space as needed
But I'm finding things aren't displaying as I expect. I've made a simplified case that demonstrates the problem.
The code is below, and the problem is that v3 doesn't get displayed, and I can't for the life of me work out why. I guess there's some facet of VBoxes and HBoxes that I haven't understood.
I'd really appreciate any help or ideas. Thanks in advance!
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import java.util.Random;
public class Test extends Application {
static Random rand = new Random();
public static void main(String args[]) {
Application.launch("something");
}
#Override
public void start(Stage mainStage) throws Exception {
testVBoxes(mainStage);
}
private void testVBoxes(Stage mainStage) {
VBox root = new VBox();
Scene one = new Scene(root, 800, 600, Color.WHITE);
FixedAspectRatioH h1 = new FixedAspectRatioH();
FixedAspectRatioH h2 = new FixedAspectRatioH();
FixedAspectRatioH h3 = new FixedAspectRatioH();
FixedAspectRatioV v1 = new FixedAspectRatioV();
FixedAspectRatioV v2 = new FixedAspectRatioV();
FixedAspectRatioV v3 = new FixedAspectRatioV();
h1.prefWidthProperty().bind(root.widthProperty());
h2.add(v2);
v1.add(h3);
v1.add(h2);
h1.add(v1);
h1.add(v3);
root.getChildren().add(h1);
mainStage.setScene(one);
mainStage.show();
}
private class FixedAspectRatioV extends VBox {
public FixedAspectRatioV() {
Rectangle r = new Rectangle();
r.setFill(Color.rgb(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
r.widthProperty().bind(widthProperty());
r.heightProperty().bind(r.widthProperty().divide(3));
getChildren().add(r);
}
public void add(Region n) {
n.prefWidthProperty().bind(widthProperty());
getChildren().add(n);
}
}
private class FixedAspectRatioH extends HBox {
public FixedAspectRatioH() {
Rectangle r = new Rectangle();
r.setFill(Color.rgb(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
r.widthProperty().bind(widthProperty().divide(4));
r.heightProperty().bind(r.widthProperty());
getChildren().add(r);
}
public void add(Region n) {
HBox.setHgrow(n, Priority.ALWAYS);
getChildren().add(n);
}
}
}

its 2 years but the solution is you forgot
Node.setPrefSize(width,height);
and also add this to your constructor Hbox.setFillHeight(true);

Related

Unable to add objects which extend a JPanel to my JFrame class

I'm working on a game and I'm trying to add a JPanel to the JFrame. I have a separate class which extends JPanel and I create a new object which again, extends JPanel.
However, I get this error: "The method add(Component) in the type Container is not applicable for the arguments (mainMenu)" (mainMenu is the class which extends JPanel).
It suggests adding an argument to match 'add(Component, Object)'
I am at a loss in trying to fix this especially because later in my code, I use the same add argument to add an object whose class extends a JButton. Any help is greatly appreciated.
I have tried creating a regular JPanel and adding that which worked.
(JFrame class)
public class gardenRunner extends JFrame {
public static void run(String[] args)
{
new gardenRunner()
}
public void gardenRunner()
{
mainMenu m = new mainMenu();
add(m); <-- gives error
}
(JPanel class)
public class mainMenu extends JPanel {
public mainMenu()
{
super();
setSize(60, 60);
}
I would expect this to add a JPanel to my JFrame but this results in an error.
Thanks for the help, turns out Eclipse was acting a little buggy and this worked when I deleted my JPanel class and made a new one. Thanks again.

Actor position is incorrect - Libgdx

Please help me, I'm pulling my hair out.
I have a class called "HudBarView" which extends the Group class(scene2d). It takes care of the drawing of the HUD Bar at the top of the screen(Pause button, score, etc).
Another class I have is "HUDManager" which takes care of all the HUD work in the game, including HUD Bar.
These two classes are very short and self-explantory. There is nothing sophisticated.
Now, currently I have only a pause button(ImageButton) in my HUD Bar but the problem is - it is visible only after I resize or pause and then resume the screen.
Here is a gif that describes my problem:
http://i.gyazo.com/6140c4ac1ea0778e4e1afce161ea3dc0.gif
I have tried to play a little bit with the code and I found out that the positioning of the actor is wrong. For instance if I define the position of the button with these values:
Vector2 position = new Vector2(Values.SCREEN_WIDTH-Values.Pause_Width*2,Values.SCREEN_HEIGHT-Values.Pause_Height*2);
Instead of these:
Vector2 position = new Vector2(Values.SCREEN_WIDTH-Values.Pause_Width,Values.SCREEN_HEIGHT-Values.Pause_Height);
It does show up on the screen but at the wrong position and after pause/resume it show up at the correct position.
Here is my HudBarView class:
package views.hud.views;
import views.renderers.HUDManager;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import engine.helpers.AssetsManager;
import engine.helpers.Values;
public class HUDBarView extends Group{
private ImageButton pause;
private HUDManager hud_manager;
private Skin skin;
public HUDBarView(HUDManager hud_manager) {
this.hud_manager = hud_manager;
initiate();
}
private void initiate() {
skin = new Skin(AssetsManager.getAsset(Values.BUTTONS_PACK, TextureAtlas.class));
pause = new ImageButton(skin.getDrawable("pause"));
pause.setSize(Values.Pause_Width, Values.Pause_Height);
pause.setPosition(Values.SCREEN_WIDTH - pause.getWidth(), Values.SCREEN_HEIGHT- pause.getHeight());
addActor(pause);
}
}
HUDManager class:
package views.renderers;
import views.hud.ParticleEffectsActor;
import views.hud.views.HUDBarView;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import engine.helpers.AssetsManager;
import engine.helpers.UIHelper;
import engine.helpers.Values;
public class HUDManager extends Group {
private Stage stage;
private Skin skin;
private Image text;
private HUDBarView hudView;
public HUDManager(Stage stage) {
this.stage = stage;
initiate();
addActor(hudView);
addActor(particles);
}
public void initiate() {
skin = AssetsManager.getAsset(Values.GAME_SKIN_PACK, Skin.class);
hudView = new HUDBarView(this);
particles = new ParticleEffectsActor();
}
public Stage getStage() {
return stage;
}
}
And Here is my game screen problem:
package views.screens;
import views.renderers.GameRenderer;
import views.renderers.HUDManager;
import engine.GameInputHandler;
import engine.GameWorld;
import engine.Values;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.StretchViewport;
/* Created by David Lasry : 10/25/14 */
public class GameScreen extends ScreenWrapper {
private GameWorld world;
private HUDManager hudManager;
private GameRenderer renderer;
private Stage stage;
public GameScreen() {
super();
ScreenHandler.getInstance().getGame().getAssetsManager()
.loadAsstes(2, this);
world = new GameWorld();
stage = new Stage(new StretchViewport(Values.SCREEN_WIDTH,
Values.SCREEN_HEIGHT));
camera = (OrthographicCamera) stage.getCamera();
InputMultiplexer inputs = new InputMultiplexer();
inputs.addProcessor(stage);
inputs.addProcessor(new GameInputHandler(world.getMonkeyManager(),
camera));
Gdx.input.setInputProcessor(inputs);
}
#Override
public void render(float delta) {
switch (state) {
case RUN:
stage.act(delta);
stage.draw();
world.update(delta);
break;
case PAUSE:
break;
}
}
// Callback method that is called when the assets are loaded
#Override
public void assetsLoaded() {
super.assetsLoaded();
renderer = new GameRenderer(world);
hudManager = new HUDManager();
stage.addActor(renderer);
stage.addActor(hudManager);
}
public HUDManager getHudManager() {
return hudManager;
}
#Override
public void dispose() {
stage.dispose();
ScreenHandler.getInstance().getGame().getAssetsManager().unload(2);
}
}
I'm struggling with this problem for almost 3 days and I have no idea what is causing this.
I even opened a new project, duplicated the relevant classes and just tried to position the button at the top right corner of the screen and it worked! So why it doesn't work in my actual game?
Please help !

TableView with different objects (javafx)

Im currently developing a application for watching who is responsible for different Patients, however i havent been able to solve how to fill a table with different object types.
Below is my code for my TableView controller. The TableView will end up with four different object typs, all will be retrieved from a database.
I want my table to hold Patient objects, User objects (responsible) and a RelationManager object.
Below is my code, if you need more of the code, please let me know :-).
package fird.presentation;
import fird.Patient;
import fird.RelationManager;
import fird.User;
import fird.data.DAOFactory;
import fird.data.DataDAO;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
/**
* FXML Controller class
*
* #author SimonKragh
*/
public class KMAMainFrameOverviewController implements Initializable {
#FXML
private TextField txtCPRKMAMainFrame;
#FXML
private TableColumn<Patient, String> TableColumnCPR;
#FXML
private TableColumn<Patient, String> TableColumnFirstname;
#FXML
private TableColumn<Patient, String> TableColumnSurname;
#FXML
private TableColumn<User, String> TableColumnResponsible;
#FXML
private TableColumn<RelationManager, String> TableColumnLastEdited;
#FXML
private TableView<RelationManager> tblPatients;
#FXML
private Button btnShowHistory;
#FXML
private TableColumn<?, ?> TableColumnDepartment;
/**
* Initializes the controller clas #FXML private Button btnShowHistory;
*
* #FXML private TableColumn<?, ?> TableColumnDepartment; s.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// Start of logic for the KMAMainFrameOverviewController
DataDAO dao = DAOFactory.getDataDao();
TableColumnCPR.setCellValueFactory(new PropertyValueFactory<Patient, String>("CPR"));
TableColumnFirstname.setCellValueFactory(new PropertyValueFactory<Patient, String>("Firstname"));
TableColumnSurname.setCellValueFactory(new PropertyValueFactory<Patient, String>("Surname"));
TableColumnResponsible.setCellValueFactory(new PropertyValueFactory<User, String>("Responsible"));
TableColumnLastEdited.setCellValueFactory(new PropertyValueFactory<RelationManager, String>("Last Edited"));
ObservableList<RelationManager> relationData = FXCollections.observableArrayList(dao.getAllActiveRelations());
tblPatients.setItems(relationData);
tblPatients.getColumns().addAll(TableColumnCPR, TableColumnFirstname, TableColumnSurname, TableColumnResponsible, TableColumnLastEdited);
System.out.println(tblPatients.getItems().toString());
}
}
relationData is a RelationManager object returned. This object contains a User object, a Patient object and a Responsible object.
Best,
Simon.
The exact details of how you do this depend on your requirements: for example, for a given RelationManager object, do the User, Patient, or Responsible objects associated with it ever change? Do you need the table to be editable?
But the basic idea is that each row in the table represents some RelationManager, so the table type is TableView<RelationManager>. Each column displays a value of some type (call it S), so each column is of type TableColumn<RelationManager, S>, where S might vary from one column to the next.
The cell value factory is an object that specifies how to get from the RelationManager object to an observable value of type S. The exact way you do this depends on how your model classes are set up.
If the individual objects associated with a given RelationManager never change (e.g. the Patient for a given RelationManager is always the same), then it's pretty straightforward. Assuming you have the usual setup for Patient:
public class Patient {
private StringProperty firstName = new SimpleStringProperty(...);
public StringProperty firstNameProperty() {
return firstName ;
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
// etc etc
}
then you can just do
TableColumn<RelationManager, String> firstNameColumn = new TableColumn<>("First Name");
firstNameColumn.setCellValueFactory(new Callback<CellDataFeatures<RelationManager,String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<RelationManager, String> data) {
return data.getValue() // the RelationManager
.getPatient().firstNameProperty();
}
});
If you are not using JavaFX properties, you can use the same fallback that the PropertyValueFactory uses, i.e.:
TableColumn<RelationManager, String> firstNameColumn = new TableColumn<>("First Name");
firstNameColumn.setCellValueFactory(new Callback<CellDataFeatures<RelationManager,String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<RelationManager, String> data) {
return new ReadOnlyStringWrapper(data.getValue().getPatient().getFirstName());
}
});
but note that this won't update if you change the name of the patient externally to the table.
However, none of this will work if the patient object associated with the relation manager is changed (the cell will still be observing the wrong firstNameProperty()). In that case you need an observable value that changes when either the "intermediate" patient property or the firstNameProperty change. JavaFX has a Bindings API with some select(...) methods that can do this: unfortunately in JavaFX 8 they spew out enormous amounts of warnings to the console if any of the objects along the way are null, which they will be in a TableView context. In this case I would recommend looking at the EasyBind framework, which will allow you to do something like
firstNameColumn.setCellValueFactory( data ->
EasyBind.select(data.getValue().patientProperty())
.selectObject(Patient::firstNameProperty));
(EasyBind requires JavaFX 8, so you if you get to use it, you also get to use lambda expressions and method references :).)
In either case, if you want the table to be editable, there's a little extra work to do for the editable cells in terms of wiring editing commits back to the appropriate call to set a property.

PowerMocking static does not return expected object

I have a problem mocking Calendar.getInstance(). As you now this method returns a Calendar - the object I am mocking.
Right now my code looks like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Calendar.getInstance() gets called various times in surveillance.checkDatabase() and every time it is a new object and not the expected mock of Calendar.
Can anyone see what I am doing wrong?
It seems that you need to add the target test class in the PrepareForTest tag:
#PrepareForTest({ Calendar.class, Surveillance.class })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Calendar.class, Surveillance.class })
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Even Tom Tresansky's example above will need it if we move the Surveillance class to somewhere outside MockCalendarTest class.
I'm not as familiar with the when(object.call()).andReturn(response); but I'm assuming it works the same way as expect.(object.call()).andReturn(response);. If that is the case, then it looks like all you are missing a replay of the class PowerMock.replay(Calendar.class) and you are trying to do a full static mock instead of a partial static mock. This should resolve your issue.
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
PowerMock.mockStaticPartial(Calendar.class, "getInstance"); //Mock Static Partial
expect(Calendar.getInstance()).andReturn(calendar);
PowerMock.replay(Calendar.class); // note the replay of the Class!
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
//Whatever tests you need to do here
}
}
It seems like you're doing everything right. For instance, this test below passes, proving that the Calendar returned by Calendar#getInstance() is in fact the one you set up with the static mocking.
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class MockCalendarTest {
#Test
public void testFailingDatabase() {
mockStatic(Calendar.class);
final Calendar testCalendar = new GregorianCalendar();
testCalendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(testCalendar);
final Surveillance surveillance = new Surveillance();
final Calendar resultCalendar = surveillance.checkDatabase();
assertTrue(testCalendar == resultCalendar);
}
public static class Surveillance {
public Calendar checkDatabase() {
return Calendar.getInstance();
}
}
}
Perhaps post the relevant parts of the Surveillance class so we can see how it's trying to get a new Calendar and assess why it's failing.

How do I get input from a user using j2me canvases? is this even possible?

I am currently trying to learn J2ME and build a connect four game (some of you might know this as 'four in a row'). I've More or less got all of the aspects of my game working, apart from one thing that is driving me mad! This is of course getting the text from the user!
For the two player mode of the game I want to be able to allow each player to enter their name. I am struggling to find a working example of text input that doesn't use the main Midlet.
For example the examples on java2x.com just use a single midlet (no classes or canvases or anything).
As it stands my application's main midlet start method simply opens a main menu class:
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
public void startApp() {
MainMenu mm = new MainMenu();
showScreen(mm);
}
public static void showScreen(Displayable screen) {
Display.getDisplay(instance).setCurrent(screen);
}
public void pauseApp() {
}
public static void quitApp() {
instance.notifyDestroyed();
}
public void destroyApp(boolean unconditional) {
}
}
The main menu class is as follows:
package view;
import javax.microedition.lcdui.*;
import lang.*;
import model.*;
import midlet.Main;
public class MainMenu extends List implements CommandListener {
private Command ok = new Command(StringDefs.currDefs.getString("TEXT_OK"), Command.OK, 1);
public MainMenu() {
super(StringDefs.currDefs.getString("TEXT_TITLE"), List.IMPLICIT);
// we we add in the menu items
append(StringDefs.currDefs.getString("TEXT_PLAY1"), null);
append(StringDefs.currDefs.getString("TEXT_PLAY2"), null);
append(StringDefs.currDefs.getString("TEXT_HIGHSCORETABLE"), null);
append(StringDefs.currDefs.getString("TEXT_HELP"), null);
append(StringDefs.currDefs.getString("TEXT_QUIT"), null);
this.addCommand(ok);
this.setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == ok) {
int selectedItem = this.getSelectedIndex();
if (selectedItem != -1) {
switch (selectedItem) {
case 0:
GameBoard gameBoard = new model.GameBoard();
GameCanvasOnePlayer board = new GameCanvasOnePlayer(gameBoard);
Main.showScreen(board);
break;
case 1:
GameBoard gameBoardTwo = new model.GameBoard();
GameCanvasTwoPlayer GameCanvasTwoPlayer = new GameCanvasTwoPlayer(gameBoardTwo);
Main.showScreen(GameCanvasTwoPlayer);
break;
case 2:
HighScores hc = new HighScores();
midlet.Main.showScreen(hc);
break;
case 3:
Help he = new Help();
midlet.Main.showScreen(he);
break;
case 4:
QuitConfirmation qc = new QuitConfirmation();
midlet.Main.showScreen(qc);
break
}
}
}
}
}
When a two player game is selected (case 1 in the above switch) from this menu I would like two text boxes to appear so that I can get both player names and store them.
What would be the best way of going about this? is this even possible with canvases? And do you know where I can find a relevant example or at least something which may help?
You can either:
1. Make the user enter his input in an ugly Textbox (which takes the whole screen)
2. Use the textbox control I've written from scratch a long time ago which is available here
and looks something like this (3 Textfields shown):
I've got a solution! well sort of.
I can create a form without using the main midlet:
The following main class is part of a source package called midlet (much like in my project):
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
private static UsernameForm unameForm=new UsernameForm();
private static MIDlet instance;
public void startApp() {
instance=this;
showScreen(unameForm); // show user name form
}
public static String getUsername1() {
return(unameForm.getUsername1());
}
public static String getUsername2() {
return(unameForm.getUsername2());
}
public void pauseApp() {
}
public static void showScreen(Displayable d) {
Display.getDisplay(instance).setCurrent(d); // show next screen
}
public void destroyApp(boolean unconditional) {
}
}
The next bit of code is the username form class that is part of a source package called view:
package view;
import javax.microedition.lcdui.*;
public class UsernameForm extends Form implements CommandListener {
private String username1="";
private String username2="";
private TextField tfUsername1=new javax.microedition.lcdui.TextField("User 1","User1",40,TextField.ANY);
private TextField tfUsername2=new javax.microedition.lcdui.TextField("User 2","User2",40,TextField.ANY);
private Command cmdOK=new Command("OK",Command.OK,1);
public UsernameForm() {
super("User details");
append(tfUsername1);
append(tfUsername2);
addCommand(cmdOK);
setCommandListener(this);
}
public void commandAction(Command cmd,Displayable d) {
if (cmd==cmdOK) {
this.setUsername1(tfUsername1.getString());
this.setUsername2(tfUsername2.getString());
// TO DO, GO TO NEXT SCREEN
}
}
/**
* #return the username1
*/
public String getUsername1() {
return username1;
}
/**
* #param username1 the username1 to set
*/
public void setUsername1(String username1) {
this.username1 = username1;
}
/**
* #return the username2
*/
public String getUsername2() {
return username2;
}
/**
* #param username2 the username2 to set
*/
public void setUsername2(String username2) {
this.username2 = username2;
}
}
So it looks like there's no easy way of doing it using canvases, I think I am better of using 'ugly forms' instead as they should work whatever the device.
That's a really sticky situation. Basically you will need to use J2ME's input text widget (which by the way looks horrible). If you don't, you'll end up having to implement all the logic behind the different types of phone keyboards and you won't have access to the dictionary... Your canvas will basically only be capturing keystrokes, not text input...
Sorry.
Here you need to, implement custom Items, all you need to do is to extend the part of the canvas where to want the user/player to enter his/her name to the CustomItems, and implement the customItems predefined abstract methods, and write method for Key Strokes and that's available in the nokia forum. They have explained it pretty good. Check out the Nokia forum.

Resources