This is my main class. I'm trying to get the string that is being selected from the combobox and "get the wall color" from that string. The problem is that when I run the application, after hitting the playbutton I get an error saying that in line 75 - if (stringWallColor.equals("Default - Black")), stringWallColor is null.
Does that I mean that it uses the public static String stringWallColor which is null as default? And how can I fix this?
public static String stringWallColor;
public static void main(String[] args) {
launch(args);
System.out.println("Done!");
}
public void start(Stage primaryStage) throws Exception {
Main.primaryStage = primaryStage;
MenuBar MENU = new MenuBar();
MenuGenerator.menuCreator(MENU);
Button playButton = new Button("Play Game");
ComboBox<String> wallColorCombo = new ComboBox<>();
wallColorCombo.setPromptText("Choose wall color");
wallColorCombo.getItems().addAll(
"Default - Black",
"Dark Green",
"Dark Red",
"Dark Gray",
"Saddle Brown",
"Midnight Blue",
"Dark Magenta",
"Crimson",
"Navy");
stringWallColor = wallColorCombo.getSelectionModel().getSelectedItem();
gameGrid = new GridPane();
GridPane root = new GridPane();
root.add(MENU,0,0);
root.add(gameGrid, 0, 1);
gameScene = new Scene(root,600,625);
GridPane startGrid = new GridPane();
startGrid.setHgap(20);
startGrid.setVgap(20);
playButton.setLineSpacing(10);
startGrid.add(playButton,8,12);
startGrid.add(wallColorCombo,7,12);
GridPane root0= new GridPane();
root0.add(startGrid,0,1);
Scene startScene = new Scene(root0, 400, 400);
primaryStage.setScene(startScene);
primaryStage.setTitle(GameEngine.GAME_NAME);
primaryStage.show();
System.out.println("Default save file not loaded yet");
playButton.setOnAction(e -> {
MenuGenerator.loadDefaultSaveFile(primaryStage);
System.out.println("Default save file loaded");
primaryStage.setScene(gameScene); });
}
public static Color getWallColor() {
Color wallColor = Color.BLACK;
if (stringWallColor.equals("Default - Black"))
wallColor = Color.BLACK;
if (stringWallColor.equals("Dark Green"))
wallColor = Color.DARKGREEN;
if (stringWallColor.equals("Dark Red"))
wallColor = Color.DARKRED;
if (stringWallColor.equals("Dark Gray"))
wallColor = Color.DARKGRAY;
if (stringWallColor.equals("Saddle Brown"))
wallColor = Color.SADDLEBROWN;
if (stringWallColor.equals("Midnight Blue"))
wallColor = Color.MIDNIGHTBLUE;
if (stringWallColor.equals("Dark Magenta"))
wallColor = Color.DARKMAGENTA;
if (stringWallColor.equals("Crimson"))
wallColor = Color.CRIMSON;
if (stringWallColor.equals("Navy"))
wallColor = Color.NAVY;
return wallColor;
}
}
Solved by setting stringWallColor = wallColorCombo.getSelectionModel().getSelectedItem(); as an action for the playbutton.
Related
3d software allow user to change draw mode dinamically. It can be implemented on javafx ?
Changing draw mode with radio buttons
In this approach a Box instance change its DrawMode with radiobuttons.
This is a single class javafx you can try .
App.java
public class App extends Application {
#Override
public void start(Stage stage) {
var perspective = new PerspectiveCamera(true);
perspective.setNearClip(0.1);
perspective.setFarClip(500);
perspective.setTranslateZ(-150);
Shape3D cube = new Box(50, 50, 50);
cube.setCullFace(CullFace.NONE);
cube.setMaterial(new PhongMaterial(Color.CORAL));
var toggleGroup = new ToggleGroup();
var solid = new RadioButton("solid");
solid.setToggleGroup(toggleGroup);
solid.setSelected(true);
var wire = new RadioButton("wireframe");
wire.setToggleGroup(toggleGroup);
var hBox = new HBox(solid, wire);
toggleGroup.selectedToggleProperty().addListener((o) -> {
Toggle selectedToggle = toggleGroup.getSelectedToggle();
if (selectedToggle == solid) {
cube.setDrawMode(DrawMode.FILL);
}
if (selectedToggle == wire) {
cube.setDrawMode(DrawMode.LINE);
}
});
var group3d = new Group(perspective, cube);
var subscene = new SubScene(group3d, 300, 400, true, SceneAntialiasing.BALANCED);
subscene.setCamera(perspective);
var stack = new StackPane(subscene, hBox);
stage.setScene(new Scene(stack, 300, 400));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
I'm trying to make bar chart by Javafx. However It quite small to see it.
I want to make it more attractive like
Here is code's program
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("JavaFX Chart Demo");
StackPane pane = new StackPane();
pane.getChildren().add(createBarChart());
stage.setScene(new Scene(pane, 400, 200));
stage.show();
}
public ObservableList<XYChart.Series<String, Double>>
getDummyChartData() {
ObservableList<XYChart.Series<String, Double>> data =
FXCollections.observableArrayList();
Series<String, Double> as = new Series<>();
Series<String, Double> bs = new Series<>();
Series<String, Double> cs = new Series<>();
Series<String, Double> ds = new Series<>();
Series<String, Double> es = new Series<>();
Series<String, Double> fs = new Series<>();
as.setName("A-Series");
bs.setName("B-Series");
cs.setName("C-Series");
ds.setName("D-Series");
es.setName("E-Series");
fs.setName("F-Series");
Random r = new Random();
for (int i = 1900; i < 2017; i += 10) {
as.getData().add(new XYChart.Data<>
(Integer.toString(i), r.nextDouble()));
bs.getData().add(new XYChart.Data<>
(Integer.toString(i), r.nextDouble()));
cs.getData().add(new XYChart.Data<>
(Integer.toString(i), r.nextDouble()));
ds.getData().add(new XYChart.Data<>
(Integer.toString(i), r.nextDouble()));
es.getData().add(new XYChart.Data<>
(Integer.toString(i), r.nextDouble()));
fs.getData().add(new XYChart.Data<>
(Integer.toString(i), r.nextDouble()));
}
data.addAll(as, bs, cs, ds, es, fs);
return data;
}
public XYChart<CategoryAxis, NumberAxis>
createBarChart() {
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
BarChart bc = new BarChart<>(xAxis, yAxis);
bc.setData(getDummyChartData());
bc.setTitle("Bar Chart on Random Number");
return bc;
}
}
Please help me how to get it by Javafx. I found it can be solve by JFree Chart However.I don't know how to make it by BarChart javafX. It's really challenge to me these day. Thank you
Just make the chart in a scroll pane.
public void start(Stage stage) throws Exception {
stage.setTitle("JavaFX Chart Demo");
StackPane stackPane = new StackPane();
stackPane.setPrefSize(1000, 200);
stackPane.getChildren().add(createBarChart());
ScrollPane scrollPane = new ScrollPane();
scrollPane.setPrefSize(400, 220);
scrollPane.setContent(stackPane);
stage.setScene(new Scene(scrollPane));
stage.show();
}
I'm trying to set every column minimum width to 100px. I prefer to use tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
Explanation
If you set TableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY) all columns will be equally resized until the TableViews maximum width is reached.
Explanation from
At the moment the width of each column is determined by the width of the TableViewdevided by the number of columns.
I tried to set every column the minimum width but that didn't work. I've also saw that people just created their own callback for the setColumnResizePolicy but I couldn't implement my idea of what should happen.
MCVE
public class MCVE extends Application {
private Scene mainScene;
private Stage mainStage;
private Label filename;
private VBox mainBox;
private TableView<String> tableView;
private Button open;
private Button save;
private Button neu;
private Button settings;
private Button table;
private Button row;
private Button column;
private Button date;
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
initButton();
initTable();
mainStage = new Stage();
filename = new Label("Nr. 100 - Test Data (Applikation: TEST)");
mainScene = new Scene(mainVBox(), 1200, 600);
tableView.prefWidthProperty().bind(mainBox.widthProperty());
tableView.prefHeightProperty().bind(mainBox.heightProperty());
mainStage.setScene(mainScene);
mainStage.show();
}
private GridPane mainGrid() {
GridPane gridPane = new GridPane();
gridPane.setVgap(10);
gridPane.setHgap(10);
gridPane.add(filename, 0, 0);
gridPane.add(buttonBox(), 0, 1);
gridPane.add(tableView, 0, 2);
return gridPane;
}
private VBox buttonBox() {
VBox buttonBox = new VBox();
HBox firstRowBox = new HBox();
HBox secRowBox = new HBox();
firstRowBox.getChildren().addAll(open, save, neu, settings);
firstRowBox.setSpacing(5);
secRowBox.getChildren().addAll(table, row, column, date);
secRowBox.setSpacing(5);
buttonBox.getChildren().addAll(firstRowBox, secRowBox);
buttonBox.setSpacing(5);
buttonBox.prefWidthProperty().bind(mainBox.widthProperty());
return buttonBox;
}
private VBox mainVBox() {
mainBox = new VBox();
mainBox.prefWidthProperty().bind(mainStage.widthProperty().multiply(0.8));
mainBox.setPadding(new Insets(10, 10, 10 ,10));
mainBox.getChildren().add(mainGrid());
return mainBox;
}
private void initButton() {
open = new Button("Open");
open.setPrefWidth(100);
save = new Button("Save");
save.setPrefWidth(100);
neu = new Button("New");
neu.setPrefWidth(100);
settings = new Button("Settings");
settings.setPrefWidth(100);
table = new Button("Table");
table.setPrefWidth(100);
row = new Button("Row");
row.setPrefWidth(100);
column = new Button("Column");
column.setPrefWidth(100);
date = new Button("Date");
date.setPrefWidth(100);
}
private TableView initTable() {
tableView = new TableView<>();
// Create column UserName (Data type of String).
TableColumn<String, String> userNameCol //
= new TableColumn<>("User Name");
// Create column Email (Data type of String).
TableColumn<String, String> emailCol//
= new TableColumn<>("Email");
// Create 2 sub column for FullName.
TableColumn<String, String> firstNameCol //
= new TableColumn<>("First Name");
TableColumn<String, String> lastNameCol //
= new TableColumn<>("Last Name");
// Active Column
TableColumn<String, Boolean> activeCol//
= new TableColumn<>("Active");
tableView.getColumns().addAll(userNameCol, emailCol, firstNameCol, lastNameCol, activeCol);
for (int i = 0; tableView.getColumns().size() < i; i++){
tableView.getColumns().get(i).setMinWidth(100);
}
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
return tableView;
}
}
In the end I expect that after I load the file, the width of the column should still be the TableView width devided by the number of columns expect the width would be < 100px. In this case every width should be 100px and a scrollpane appears (ignores the scrollbar here).
Thank you for your help!
Your constraint of min width is never set...
Just replace this:
for (int i = 0; tableView.getColumns().size() < i; i++){
to this:
for (int i = 0; i < tableView.getColumns().size(); i++) {
Or even better use forEach:
tableView.getColumns().forEach(column -> column.setMinWidth(100));
I have a GUI that takes the input of an image name, and once the refresh button is pressed, its displayed in a fixed position. I want to be able to input a character 'A-G' which will change the X position of the image, and a character '0-6' that will change the Y position of the image. The name of the images are just "A1", "A2"..."A5". So, if the user inputs "A1B3", it will display the image A1 in X-Position 'B' and Y-Position '3'. So B could be 200, and 3 could be 300, which makes the (X,Y) coordinates (200,300).
This is my code that gets the users input for the image.
private void getImage(){
Image img = new Image("comp1110/ass2/gui/assets/" + textField.getText() + ".png", 100, 100, false, false);
ImageView image = new ImageView();
image.setImage(img);
image.setX(100);
image.setY(100);
pane.getChildren().add(image);
}
I think you should do something along the lines of this yes there is some cosmetic issues that you will need to fix. But its only to give you an idea of what to do. It uses a gridpane so you don't have to worry about getting exact coordinates I choose a vbox so I didn't have to worry about layout you can keep the Pane that you have it shouldn't make a difference.
public class Main extends Application {
private GridPane gridPane;
private TextField imageTextField = new TextField();
private HashMap<String,String> hashMap = new HashMap<>();
#Override
public void start(Stage primaryStage) {
fillHashMapValues();
gridPane = new GridPane();
gridPane.setGridLinesVisible(true);
for (int i = 0; i < 7; i++) {
RowConstraints rowConstraints = new RowConstraints();
rowConstraints.setPercentHeight(14);
gridPane.getRowConstraints().add(rowConstraints);
ColumnConstraints columnConstraints = new ColumnConstraints();
columnConstraints.setPercentWidth(14);
gridPane.getColumnConstraints().add(columnConstraints);
gridPane.addColumn(i);
gridPane.addRow(i);
}
imageTextField.setPromptText("Enter Image Letters?");
TextField textField = new TextField();
textField.setPromptText("Enter Coordinates");
Button button = new Button("Go!");
button.setOnAction(event -> {
addToGridPane(textField.getText());
});
VBox vBox = new VBox();
vBox.setPrefSize(300, 300);
vBox.setAlignment(Pos.TOP_CENTER);
vBox.getChildren().addAll(imageTextField, textField, button, gridPane);
primaryStage.setScene(new Scene(vBox));
primaryStage.show();
button.requestFocus();//This is only so you can see the prompt text its irrelevant
}
private void fillHashMapValues(){
hashMap.put("A", "1");
hashMap.put("B", "2");
hashMap.put("C", "3");
hashMap.put("D", "4");
hashMap.put("E", "5");
hashMap.put("F", "6");
hashMap.put("G", "7");
}
private void addToGridPane(String string){
char[] chars = string.toCharArray();
if(chars.length==2){//Do more data validation here
if(hashMap.containsKey(String.valueOf(chars[0]))) {
int xValue = Integer.parseInt(hashMap.get(String.valueOf(chars[0])));
int yValue = Integer.parseInt(String.valueOf(chars[1]));
ImageView image = getImage();
gridPane.add(image, xValue, yValue);
}
}
}
private ImageView getImage(){
Image image = new Image("comp1110/ass2/gui/assets/" + imageTextField.getText() + ".png", 100, 100, false, false);
ImageView imageView = new ImageView();
imageView.setImage(image);
//imageView.setX(100);
//imageView.setY(100);
//pane.getChildren().add(image);
return imageView;
}
public static void main(String[] args) { launch(args); }
}
Im developing an application using javafx, and it works fine when running from net beans, but when i try to run the application through the .jar file,the application starts and i´m able to use some of its functionalities, but not all of them.
When it starts always gives me this error:
This is the a part code :
#Override
public void start(Stage primaryStage)
{
bd=new BD();
bd.iniciarConexao();
stage= primaryStage;
stage.setTitle("Gestão de eventos - AAC");
layerPane = new StackPane();
initRoot();
scene = new Scene(layerPane, 1020, 700);
scene.getStylesheets().addAll(ProjectV2.class.getResource("ProjectV2.css").toExternalForm(),
ProjectV2.class.getResource("calendarstyle.css").toExternalForm());
//MainToolBar-----------------------------------------------------------
nomeAplicacao = new Label("Gestão de eventos - AAC");
hbNomeAplicacao= new HBox();
hbEmblemas = new HBox(40);
emblemas = new ArrayList<>();
toolBar = new ToolBar();
logo = new ImageView(new Image(ProjectV2.class.getResourceAsStream("images/gestaoDeEventos2_2.png")));
//----------------------------------------------------------------------
spacer1= new Region();
spacer2= new Region();
spacer3= new Region();
spacer4= new Region();
centerPane= new BorderPane();
paScrollPane= new ScrollPane();
paVb= new VBox();
paVb.setPrefHeight(500);
hbSubtitulo= new HBox();
subtitulo= new Label("Funcionalidades");
//----------------------------------------------------------------------
//LogToolBar------------------------------------------------------------
logToolBar= new ToolBar();
loginButton = new MenuButton();
loginButton.setId("SettingsButton");
loginButton.setPopupSide(Side.TOP);
loginButton.setGraphic(new ImageView(new Image(ProjectV2.class.getResourceAsStream("images/business_user2.png"))));
mLogin = MenuItemBuilder.create().text("Login").build();
mAddFunc = MenuItemBuilder.create().text("Mudar password").build();
mLogout = MenuItemBuilder.create().text("Logout").build();
//mEditUser = MenuItemBuilder.create().text("Editar funcionário").build();
mFactura= MenuItemBuilder.create().text("Factura").build();
//----------------------------------------------------------------------
stage.setScene(scene);
stage.show();
toogleMaximized();
}
public void toogleMaximized()
{
screen = Screen.getScreensForRectangle(stage.getX(), stage.getY(), 1, 1).get(0);
if (maximized)
{
maximized = false;
if (backupWindowBounds != null) {
stage.setX(backupWindowBounds.getMinX());
stage.setY(backupWindowBounds.getMinY());
stage.setWidth(backupWindowBounds.getWidth());
stage.setHeight(backupWindowBounds.getHeight());
}
}
else
{
maximized = true;
backupWindowBounds = new Rectangle2D(stage.getX(), stage.getY(), stage.getWidth(), stage.getHeight());
stage.setX(screen.getVisualBounds().getMinX());
stage.setY(screen.getVisualBounds().getMinY());
stage.setWidth(screen.getVisualBounds().getWidth());
stage.setHeight(screen.getVisualBounds().getHeight());
}
}