简体   繁体   中英

FXML and Comboboxes

Following an example on : http://code.makery.ch/blog/javafx-8-event-handling-examples/ I have made a basic GUI involving a combobox. When Running my program however none of the items are being added to the combobox what so ever. I would very much appreciate it if you could point out my mistakes as to why it may not be adding the items to the combobox. Here is a ZIP file of my project: https://www.dropbox.com/home/Project-JavaFX All thanks in advance!

Main.java:

package Main;

import Items.Item;
import Items.ItemManager;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Main extends Application {

private static myController uj = new myController();
private static ItemManager im = new ItemManager();


public static void main(String[] args) {
    uj.initialize();
    launch(args);

}

@Override
public void start(Stage primaryStage) throws Exception {
    Pane mainPane = (Pane) FXMLLoader.load(Main.class.getResource("Main.fxml"));
    primaryStage.setScene(new Scene(mainPane));
    primaryStage.show();
}
}

Main.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.net.*?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.layout.AnchorPane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="720.0" prefWidth="1280.0" stylesheets="@myStyle.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Main.myController">
   <children>
      <Rectangle arcHeight="5.0" arcWidth="5.0" fill="WHITE" height="196.0" layoutX="478.0" layoutY="-2.0" stroke="BLACK" strokeType="INSIDE" width="343.0" />
      <ImageView fitHeight="568.0" fitWidth="684.0" layoutX="356.0" layoutY="167.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../../../Pictures/builder.jpg" />
         </image>
      </ImageView>
      <ImageView fitHeight="885.0" fitWidth="857.0" layoutX="629.0" layoutY="187.0" pickOnBounds="true" preserveRatio="true" rotate="90.0">
         <image>
             <Image url="@../../../../Pictures/Uroburos-rootkit-Espionage-Russia.jpg" />
         </image>
      </ImageView>
      <ImageView fitHeight="885.0" fitWidth="857.0" layoutX="-187.0" layoutY="187.0" pickOnBounds="true" preserveRatio="true" rotate="90.0">
         <image>
            <Image url="@../../../../Pictures/Uroburos-rootkit-Espionage-Russia.jpg" />
         </image>
      </ImageView>
      <Line endX="100.0" endY="400.0" layoutX="381.0" layoutY="324.0" startX="100.0" startY="-325.0" />
      <Line endX="425.0" endY="390.0" layoutX="391.0" layoutY="334.0" startX="425.0" startY="-335.0" />
      <ComboBox fx:id="stocks" layoutX="38.0" layoutY="135.0" onAction="#itemPicked" prefHeight="46.0" prefWidth="421.0" promptText="Please Select and Item" />
      <ScrollBar fx:id="currentP" layoutX="857.0" layoutY="108.0" onDragDetected="#getIndexC" orientation="VERTICAL" prefHeight="100.0" prefWidth="400.0" />
      <Button fx:id="remove" layoutX="1007.0" layoutY="53.0" mnemonicParsing="false" onAction="#deleteItem" prefHeight="43.0" prefWidth="250.0" text="Remove From Order">
         <font>
            <Font name="Arial Black" size="20.0" />
         </font>
      </Button>
      <ImageView fitHeight="72.0" fitWidth="79.0" layoutX="491.0" layoutY="74.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../../../Pictures/Uroburos-rootkit-Espionage-Russia.jpg" />
         </image>
      </ImageView>
      <Label layoutX="491.0" layoutY="14.0" prefHeight="60.0" prefWidth="311.0" text="RootKit At your Service" textAlignment="JUSTIFY">
         <font>
            <Font name="Courier New Bold Italic" size="22.0" />
         </font>
      </Label>
      <Label fx:id="message" layoutX="587.0" layoutY="87.0" text="&quot;Protecting&quot; your trade">
         <font>
            <Font name="Courier New Italic" size="15.0" />
         </font>
      </Label>
      <Button fx:id="adding" layoutX="38.0" layoutY="81.0" mnemonicParsing="false" onAction="#addItem" text="Add Item To Order">
         <font>
            <Font name="Arial Black" size="20.0" />
         </font>
      </Button>
      <TextField fx:id="quantity" layoutX="38.0" layoutY="194.0" onAction="#getQuantity" prefHeight="54.0" prefWidth="62.0" promptText="&quot;1&quot;">
         <font>
            <Font size="20.0" />
         </font></TextField>
      <Label layoutX="108.0" layoutY="196.0" text="Quantity" textFill="WHITE">
         <font>
            <Font name="Arial Black" size="34.0" />
         </font>
      </Label>
   </children>
</Pane>

myController.java:

package Main;

import Items.Item;
import Items.ItemManager;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.TextField;

public class myController {

@FXML
private TextField quantity;

@FXML
private Button adding;

@FXML
private ScrollBar currentP;

@FXML
private Label message;

@FXML
public static ComboBox stocks = new ComboBox();

@FXML
private Button remove;

public static ObservableList<String> options = FXCollections.observableArrayList();

int count = 0;

private static ItemManager im = new ItemManager();


@FXML
void itemPicked(ActionEvent event) {

}


@FXML
void getIndexC(ActionEvent event) {

}

@FXML
void deleteItem(ActionEvent event) {

}

@FXML
void addItem(ActionEvent event) {

}

@FXML
void getQuantity(ActionEvent event) {

}


public void initialize() {
    // TODO Auto-generated method stub
    for(int i = 0; i < im.inventoryItems.size(); i++) {
        options.add(im.inventoryItems.get(i).getName());
    }
    stocks.setItems(options);
}

}

Item.java:

package Items;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class Item {

//Items definitions

public static Item hammer = new Item(0, "Hammer", 5.0);
public static Item tape = new Item(1, "Tape", 3.0);
public static Item test = new Item(2, "Rare", 4.0);

protected int quantity, id;
protected String name;
protected BufferedImage sprite;
protected double price, totalPrice;

public static void updateTotalPrice(Item i) {
    i.setTotalPrice(i.getQuantity()*i.getPrice());
}

public Item (int id, String name, double price) {
    this.id = id;
    this.name = name;
    this.price = price;
    //quantity = 1;
    //this.totalPrice = price;
}

//Getters and Setters

public int getQuantity() {
    return quantity;
}

public double getTotalPrice() {
    return totalPrice;
}

public void setTotalPrice(double totalPrice) {
    this.totalPrice = totalPrice;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}



}

ItemManager.java:

package Items;

import java.util.ArrayList;

public class ItemManager {

public static ArrayList<Item> inventoryItems;

public static void ItemManager() {
    inventoryItems = new ArrayList<Item>();
    inventoryItems.add(Item.hammer);
    inventoryItems.add(Item.tape);
    inventoryItems.add(Item.test);
}

public Item getItemFromID(int id) {
    for (Item i : inventoryItems) {
        if (i.getId() == id) {
            return i;
        }
    }
    return null;
}

public void addItem(Item i, int quantity) {
    boolean flag = false;
    for (Item item : inventoryItems) {
        if (i.getId() == item.getId()) {
            item.setQuantity(item.getQuantity()+quantity);
            Item.updateTotalPrice(item);
            flag = true;
            //call the method to update the information box in the inventory GUI
            break;
        }
    }
    if (!flag) {
        inventoryItems.add(i);
        //call method for adding new info box in inventory GUI
    }
}

public void removeItem(int id) {
    for (Item item : inventoryItems) {
        if (item.getId() == this.getItemFromID(id).getId()) {
            item.setQuantity(item.getQuantity()-1);
            if (item.getQuantity() <= 0) {
                inventoryItems.remove(item);
            }
            break;
        }
    }
}

//Getters and Setters



}

There are several things I recommend to change:

Main class

private static myController uj = new myController();
private static ItemManager im = new ItemManager();

as well as

uj.initialize();

Should be removed from the Main class. The controller's initialize method is automatically called by FXMLLoader . Furthermore uj is a different instance to the one used with your fxml. The im field is simply unnecessary since it's never used in the class.

ItemManager class

public static void ItemManager() {
    inventoryItems = new ArrayList<Item>();
    inventoryItems.add(Item.hammer);
    inventoryItems.add(Item.tape);
    inventoryItems.add(Item.test);
}

This is neither a constructor nor a method for creating an object. It's never used but it seems to serve the purpose of a "static constructor". You should use a static initializer instead to initialize static fields:

public final static ArrayList<Item> inventoryItems;

static {
    inventoryItems = new ArrayList<Item>();
    inventoryItems.add(Item.hammer);
    inventoryItems.add(Item.tape);
    inventoryItems.add(Item.test);
}

Furthermore there's a unhealthy mix of static data and non-static methods accessing it in the ItemsManager class. I'd recommend using a proper

mainController class

@FXML
public static ComboBox stocks = new ComboBox();

fxml elements are not injected to static fields. Therefore the field should be changed to this:

@FXML
private ComboBox stocks;

Also I recommend using a non-static options field or one initialized in a static initializer since loading the scene multiple times currently results in the same items being added over and over again.

Moreover if you want to keep the ItemManager.inventoryItems field static the im field is unnecessary you only use static members of the class which is bad practice and also unnecessary since you can use the class name instead of the instance:

public void initialize() {
    // TODO Auto-generated method stub
    for (int i = 0; i < ItemManager.inventoryItems.size(); i++) {
        options.add(ItemManager.inventoryItems.get(i).getName());
    }
    stocks.setItems(options);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM