Javafx: TextField Handler - java

I don't know why but class member newContact is not getting any data and when I try to print it, it prints null.
Here is the code :
public class CreatContact_Controller {
#FXML
private VBox vBox;
private Contact contact;
private ArrayList<String> newContact = null;
private ArrayList<TextField> textFields = null;
void initData(Contact contact) {
this.contact = contact.clon();
editFields();
}
private void editFields(){
for(int loop = 0 ; loop < contact.getPlaceHolders().size() ; loop++){
HBox hBox = new HBox();
Label label = new Label("Add the new " + contact.getPlaceHolders().get(loop));
TextField textField = new TextField();
textField.setOnAction(getTextField);
hBox.getChildren().addAll(label, textField);
vBox.getChildren().add(hBox);
}
}
private EventHandler<ActionEvent> getTextField =
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
newContact.add(((TextField)event.getSource()).getText());
System.out.println(((TextField)event.getSource()).getText());
}
};
}
How to fix so it adds the value of the textfield ?

Related

TreeItem is Overwritten in JavaFX. How to solve this?

Treeitem is overwriting every time I add a new class. How to solve this?
While adding a new object treeitem should be dynamically increase tried:
adding without using the list
added using the list
tried to add using a loop
This is an example code sorry for naming errors.thanks in advance
marked the place of issue with --------
PanesClass.java
public class PanesClass extends Application {
ObservableList<Connections> cList = FXCollections.observableArrayList();
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("all")#Override
public void start(Stage primaryStage) throws Exception {
NewConnection newConnection = new NewConnection();
SplitPane root = new SplitPane();
AnchorPane first = new AnchorPane();
AnchorPane second = new AnchorPane();
TreeTableView activeConnections = new TreeTableView();
HBox buttonBox = new HBox();
BorderPane topBar = new BorderPane();
Button nConnection = new Button("+");
Button deleteConnection = new Button("X");
Button connect = new Button("Connect");
buttonBox.setSpacing(10);
buttonBox.getChildren().addAll(nConnection, deleteConnection, connect);
topBar.setTop(buttonBox);
TreeTableColumn<String, Connections > cNameColoumn = new TreeTableColumn<>("Name");
cNameColoumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("cname"));
TreeTableColumn<String, Connections> cStatusColoumn = new TreeTableColumn<>("Status");
cStatusColoumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("cstatus"));
activeConnections.getColumns().addAll(cNameColoumn, cStatusColoumn);
activeConnections.setLayoutX(20);
activeConnections.setLayoutY(40);
activeConnections.setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
first.getChildren().addAll(topBar, activeConnections);
root.getItems().addAll(first, second);
Scene sc = new Scene(root, 600, 480);
primaryStage.setScene(sc);
primaryStage.show();
nConnection.setOnAction(new EventHandler<ActionEvent>() {#Override
public void handle(ActionEvent event) {
newConnection.getConnection(activeConnections);
}
});
}
}
NewConnection.java
public class NewConnection {
Connections connection = null;
ObservableList<Connections> cList = FXCollections.observableArrayList();
PanesClass panesClass = new PanesClass();
TreeItem cItem = null;
TreeItem nItem = null;
public void getConnection(TreeTableView<Connections> activeConnections) {
Stage secondaryStage = new Stage();
VBox root = new VBox();
GridPane cDetails = new GridPane();
HBox actionButtons = new HBox();
Button connect = new Button("Connect");
Button save = new Button("Save");
Button cancel = new Button("Cancel");
actionButtons.getChildren().addAll(connect, save, cancel);
actionButtons.setSpacing(10);
Label name = new Label("Username : ");
cDetails.add(name, 0, 0);
TextField uName = new TextField();
cDetails.setHgrow(uName, Priority.ALWAYS);
cDetails.add(uName, 1, 0);
Label password = new Label("Password : ");
cDetails.add(password, 0, 1);
TextField pwd = new TextField();
cDetails.add(pwd, 1, 1);
Label urllink = new Label("URL : ");
cDetails.add(urllink, 0, 2);
TextField url = new TextField();
cDetails.add(url, 1, 2);
cDetails.setVgap(10);
cDetails.setStyle("-fx-padding: 10;" + "-fx-border-style: solid inside;" + "-fx-border-width: 1;" + "-fx-border-insets: 5;" + "-fx-border-radius: 5;" + "-fx-border-color: black;");
root.getChildren().addAll(cDetails, actionButtons);
Scene sc = new Scene(root, 500, 200);
secondaryStage.setScene(sc);
secondaryStage.initModality(Modality.APPLICATION_MODAL);
secondaryStage.show();
save.setOnAction(new EventHandler<ActionEvent>() {
//*-----------------------------------------------------------------------*
#Override
public void handle(ActionEvent event) {
cItem = getitem(cItem);
activeConnections.setRoot(cItem);
activeConnections.setShowRoot(false);
secondaryStage.close();
}
private TreeItem getitem(TreeItem cItem) {
cList.add(new Connections(uName.getText()));
System.out.println(cList);
for (Connections temp: cList) {
System.out.println(temp);
nItem = new TreeItem<Connections>(temp);
System.out.println(nItem);
cItem.getChildren().add(nItem);
}
return cItem;
}
});
System.out.println(cList);
}
}
Connections.java
public class Connections {
private String cname = null;
private String cstatus = null;
private String cpwd = null;
private String curl = null;
public Connections() {
}
public Connections(String cname, String cpwd, String curl) {
super();
this.cname = cname;
this.cpwd = cpwd;
this.curl = curl;
}
public Connections(String cname, String cstatus) {
super();
this.cname = cname;
this.cstatus = cstatus;
}
public String getCpwd() {
return cpwd;
}
public void setCpwd(String cpwd) {
this.cpwd = cpwd;
}
public String getCurl() {
return curl;
}
public void setCurl(String curl) {
this.curl = curl;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCstatus() {
return cstatus;
}
public void setCstatus(String cstatus) {
this.cstatus = cstatus;
}
#Override
public String toString() {
return "Connections [cname=" + cname + ", cstatus=" + cstatus + ", cpwd=" + cpwd + ", curl=" + curl + "]";
}
}
You're not populating your tree, you're creating new items without adding them to your tree.
First thing, you need to create a root:
// Instead of this line
// TreeItem nItem = null;
TreeItem rootItem = new TreeItem();
Then:
activeConnections.setRoot(rootItem);
save.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// clear old connections
rootItem.getChildren().clear();
// Add new connection
cList.add(new Connections(uName.getText(), pwd.getText(), url.getText()));
// create new items and add them to rootItem
for (Connections temp : cList) {
rootItem.getChildren().add(new TreeItem<Connections>(temp));
}
secondaryStage.close();
event.consume();
}
});
NOTE: If you don't have another reason to keep cList, you can remove it and add your new Items directly (no need to clear and regenerate items everytime):
save.setOnAction(event -> {
Connections newConnection = new Connections(uName.getText(), pwd.getText(), url.getText());
rootItem.getChildren().add(new TreeItem<>(newConnection));
secondaryStage.close();
event.consume();
});

java.lang.ClassCastException whilst using JAVAFX

I get the error "java.lang.ClassCastException". I'm trying to make a calculator and with JAVAFX (with SceneBuilder - if that's necessary), and I can't trace where I did wrong on the code.
I'm trying to make a new window appear when the button "HISTORY" is clicked and it should show all the previous operations performed.
java.lang.ClassCastException: application.controller.MainWindowController cannot be cast to application.controller.HistoWindowController
MainWindowController is:
public class MainWindowController {
private Main main;
#FXML
TextField input1;
#FXML
TextField input2;
#FXML
Label showAnswer;
public void setMain(Main main){
this.main = main;
}
public void showAnswerSTR(String str) {
showAnswer.setText("Answer: " + str);;
}
#FXML
public void showHistory() {
main.HistoryViewer();
}
#FXML
public void addNumbers(){
Float inputA = Float.parseFloat(input1.getText());
Float inputB = Float.parseFloat(input2.getText());
Addition x = new Addition();
String ans = x.operation(inputA, inputB);
showAnswerSTR(ans);
}
#FXML
public void subtractNumbers(){
Float inputA = Float.parseFloat(input1.getText());
Float inputB = Float.parseFloat(input2.getText());
Subtraction x = new Subtraction();
String ans = x.operation(inputA, inputB);
showAnswerSTR(ans);
}
#FXML
public void multiplyNumbers(){
Float inputA = Float.parseFloat(input1.getText());
Float inputB = Float.parseFloat(input2.getText());
Multiplication x = new Multiplication();
String ans = x.operation(inputA, inputB);
showAnswerSTR(ans);
}
#FXML
public void divideNumbers(){
Float inputA = Float.parseFloat(input1.getText());
Float inputB = Float.parseFloat(input2.getText());
Division x = new Division();
String ans = x.operation(inputA, inputB);
showAnswerSTR(ans);
}
}
HistoWindowController is:
public class HistoWindowController {
#FXML
VBox HistoryViewer;
public void showHistory(){
StringTokenizer str = new StringTokenizer(getHistory(),";");
while(str.hasMoreTokens()){
HistoryViewer.getChildren().add(new Label(str.nextToken().toString()));
}
}
private String history = "H I S T O R Y;";
public void addHistory(String history) {
this.history += history + ";";
}
public String getHistory() {
return history;
}
/*public String historyReader() {
StringTokenizer str = new StringTokenizer(getHistory(),";");
String temp = "";
if(str.hasMoreTokens()) {
temp += str.nextToken();
temp += "\n";
}
return temp;
}*/
}
Main is:
public class Main extends Application {
private Stage primaryStage;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/mainView.fxml"));
AnchorPane mainFXML = (AnchorPane) loader.load();
Scene scene = new Scene(mainFXML);
primaryStage.setScene(scene);
primaryStage.show();
MainWindowController mainWindow = loader.getController();
mainWindow.setMain(this);
} catch(Exception e) {
e.printStackTrace();
}
}
public void HistoryViewer(){
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/HistoryView.fxml"));
AnchorPane histoView = (AnchorPane) loader.load();
Scene scene = new Scene(histoView);
primaryStage.setScene(scene);
primaryStage.show();
HistoWindowController histoControl = loader.getController();
histoControl.showHistory();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Thanks in advance
I guess this is the line where it happens (check the stacktrace): HistoWindowController histoControl = loader.getController();
the value of the fx:controller attribute in HistoryView.fxml is MainWindowController
Thanks #fabian

JavaFX printing rows into TextFields

I have a table with on my SQL server with 16 rows, I am trying to print out the BasePT column into a bunch of TextFields but I cannot figure out how. Am I suppose to create a separate string for each row? How can I minimize code and be able to get each row to show up on each TextField?
//Table 100
// Button
public void loadButton(){
connection = SqlConnection.FormulaConnection();
try {
String SQL = "Select * FROM '100';";
ResultSet rs = connection.createStatement().executeQuery(SQL);
while (rs.next()) {
//insert BasePT from Row Yellow into YellowText TextField
String Yellow = rs.getString("BasePt");
YellowText.setText(Yellow);
//insert BasePT from Row 012 Yellow into TwoYellowText TextField
String TwoYellow = rs.getString("BasePT");
TwoYellowText.setText(TwoYellow);
}
} catch (Exception e) {
e.printStackTrace();
}
}
If you do NOT want to use a Tableview as yelliver suggested, you can try this:
public VBox loadButton(){
connection = SqlConnection.FormulaConnection();
VBox vBox = new VBox();
try {
String SQL = "Select * FROM '100';";
ResultSet rs = connection.createStatement().executeQuery(SQL);
while (rs.next()) {
String yellow = rs.getString("BasePt");
TextField textField = new TextField(yellow);
vBox.getChildren().add(textField);
}
} catch (Exception e) {
e.printStackTrace();
}
return vBox;
}
You can then add the VBox where you want to have all the textFields.
In the following examples I use a array of String[] arrays with elements for the row data. It should be easy enough to use the data from the database instead.
The standard way: TableView
Simply use a Item class containing a property for each table column:
public class Item {
public Item(String baseFormula, String basePt) {
this.baseFormula = new SimpleStringProperty(baseFormula);
this.basePt = new SimpleStringProperty(basePt);
}
private final StringProperty basePt;
private final StringProperty baseFormula;
public final String getBaseFormula() {
return this.baseFormula.get();
}
public final void setBaseFormula(String value) {
this.baseFormula.set(value);
}
public final StringProperty baseFormulaProperty() {
return this.baseFormula;
}
public final String getBasePt() {
return this.basePt.get();
}
public final void setBasePt(String value) {
this.basePt.set(value);
}
public final StringProperty basePtProperty() {
return this.basePt;
}
#Override
public String toString() {
return "Item{" + "basePt=" + basePt.get() + ", baseFormula=" + baseFormula.get() + '}';
}
}
And use a TableView with a column for each database column. Use a cellFactory that displays TextFields and modifies the property belonging to the column on a change of the TextField's text property:
#Override
public void start(Stage primaryStage) {
TableView<Item> table = new TableView<>();
Callback<TableColumn<Item, String>, TableCell<Item, String>> factory = column -> new TableCell<Item, String>() {
private final TextField textField;
{
textField = new TextField();
textField.textProperty().addListener((observable, oldValue, newValue) -> {
// write to property
WritableValue<String> property = (WritableValue<String>) getTableColumn().getCellObservableValue(getIndex());
property.setValue(newValue);
});
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(textField);
if (!Objects.equals(textField.getText(), item)) {
// only modify if TextField wasn't source of the change
// to prevent carret movement
textField.setText(item);
}
}
}
};
TableColumn<Item, String> formulaColumn = new TableColumn<>("baseFormula");
formulaColumn.setCellValueFactory(cd -> cd.getValue().baseFormulaProperty());
formulaColumn.setCellFactory(factory);
TableColumn<Item, String> ptColumn = new TableColumn<>("basePt");
ptColumn.setCellValueFactory(cd -> cd.getValue().basePtProperty());
ptColumn.setCellFactory(factory);
table.getColumns().addAll(formulaColumn, ptColumn);
String[][] data = {
{"Hello", "World"},
{"Hello2", "World2"},
{"Hello3", "World3"},
{"Hello4", "World4"},
{"Hello5", "World5"},
{"Hello6", "World6"}
};
for (String[] d : data) {
table.getItems().add(new Item(d[0], d[1]));
}
Button btn = new Button("print");
btn.setOnAction(evt -> System.out.println(table.getItems()));
Scene scene = new Scene(new VBox(table, btn));
primaryStage.setScene(scene);
primaryStage.show();
}
Alternative
If you don't want to use a TableView, GridPane would be a suitable Pane to produce a layout like this:
#Override
public void start(Stage primaryStage) {
String[][] data = {
{"Hello", "World"},
{"Hello2", "World2"},
{"Hello3", "World3"},
{"Hello4", "World4"},
{"Hello5", "World5"},
{"Hello6", "World6"}
};
Insets margin = new Insets(4);
int nextRow = 1;
GridPane gridPane = new GridPane();
Text heading1 = new Text("BaseFormula");
Text heading2 = new Text("BasePT");
GridPane.setMargin(heading1, margin);
GridPane.setMargin(heading2, margin);
gridPane.addRow(0, heading1, heading2);
for (String[] d : data) {
TextField tf = new TextField(d[0]);
TextField tf2 = new TextField(d[1]);
GridPane.setMargin(tf, margin);
GridPane.setMargin(tf2, margin);
gridPane.addRow(nextRow++, tf, tf2);
}
// add lines
// subtract stroke width
DoubleBinding height = gridPane.heightProperty().subtract(1);
// margin = 1/2 stroke width
Insets vMargin = new Insets(0.5, 0, 0.5, 0);
// add vertical lines
for (int i = 0; i < 3; i++) {
Line vLine = new Line();
GridPane.setMargin(vLine, vMargin);
System.out.println(vLine.getStrokeWidth());
vLine.endYProperty().bind(height);
gridPane.add(vLine, i, 0, 1, nextRow);
}
// procede accordingly with horizontal lines
DoubleBinding width = gridPane.widthProperty().subtract(1);
Insets hMargin = new Insets(0, 0.5, 0, 0.5);
for (int i = 0; i <= nextRow; i++) {
Line hLine = new Line();
GridPane.setMargin(hLine, hMargin);
hLine.setStartX(1);
hLine.endXProperty().bind(width);
// Insert at the top of the cell
GridPane.setValignment(hLine, VPos.TOP);
gridPane.add(hLine, 0, i, 2, 1);
}
Scene scene = new Scene(new StackPane(new Group(gridPane)), 500, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
you can replace this snippet with your ResultSet rs
ResultSet rs = null;//reference it to your rs
TableView<String[]> tv = new TableView<String[]>();
final int columnCount = rs.getMetaData().getColumnCount();
for(int i =1; i <= columnCount; i++){
TableColumn<String[], String> tc = new TableColumn<String[], String>();
tc.setText(rs.getMetaData().getColumnName(i));
final int k = i-1;
tc.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<
String[],String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<String[],
String> param) {
return new SimpleStringProperty(param.getValue()[k]);
}
});
tc.setCellFactory(new Callback<TableColumn<String[],String>,
TableCell<String[],String>>() {
#Override
public TableCell<String[], String> call(TableColumn<String[],
String> param) {
return new TableCell<String[], String>(){
#Override
protected void updateItem(String arg0, boolean arg1) {
super.updateItem(arg0, arg1);
if(arg1){
setText("");
return;
}else{
setText(arg0);
}
}
};
}
});
}
while(rs.next()){
String[] s = new String[columnCount];
for(int i = 1; i <= columnCount; i++){
s[i -1] = rs.getString(i);
}
tv.getItems().add(s);
}
This will put you in the right direction. Hope it helps/.

Update JLabel text error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm having some problems updating JLabel text. I have a AddCollection JDialog that calls it's controller and then updates the main view statusbar. However, when I apply the same technique to my AddHolding JDialog and controller I am getting a Null Pointer Exception. I have been at it for hours now, but can't see where I am going wrong. Is it something to do with my chaining?
Below is my code that relates to the problem at hand.
public class LMSDriver
{
public static void main(String[] args)
{
LMSModel model = new LMSFacade();
AddCollectionPanel colPanel = new AddCollectionPanel(model);
colPanel.setVisible(true);
}
}
public class AddCollectionPanel extends JDialog
{
private LMSModel model;
private AddCollectionController controller;
private LibraryView view;
private Box mainBox, hBox1, hBox2, hBox3;
private JLabel jlCode, jlTitle;
private JButton submitBtn;
private JTextField codeField;
private JTextField titleField;
public AddCollectionPanel(LMSModel model)
{
super();
this.model = model;
this.controller = new AddCollectionController(this);
setTitle("Add Collection");
setSize(300,160);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
mainBox = Box.createVerticalBox();
hBox1 = Box.createHorizontalBox();
hBox2 = Box.createHorizontalBox();
hBox3 = Box.createHorizontalBox();
jlCode = new JLabel("Collection Code: ");
jlTitle = new JLabel("Collection Title: ");
codeField = new JTextField(10);
titleField = new JTextField(10);
submitBtn = new JButton("Submit");
submitBtn.addActionListener(controller);
hBox1.add(jlCode);
hBox1.add(Box.createHorizontalStrut(12));
hBox1.add(codeField);
hBox2.add(jlTitle);
hBox2.add(Box.createHorizontalStrut(10));
hBox2.add(titleField);
hBox3.add(Box.createHorizontalStrut(120));
hBox3.add(submitBtn);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox1);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox2);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox3);
add(mainBox);
setVisible(true);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.view = new LibraryView(model);
}
public String getCodeField()
{
String codeText = new String(codeField.getText());
return codeText;
}
public void clearCodeField()
{
codeField.setText("");
}
public String getTitleField()
{
String titleText = new String(titleField.getText());
return titleText;
}
public void clearTitleField()
{
titleField.setText("");
}
public JButton getSubmitBtn()
{
return submitBtn;
}
public LMSModel getModel()
{
return model;
}
public AddCollectionController getController()
{
return controller;
}
public LibraryView getView()
{
return view;
}
}
public class AddCollectionController implements ActionListener
{
private AddCollectionPanel colPanel;
private LMSModel model;
private LibraryCollection lib;
private JLabel colCode;
private JLabel totalBooks;
private JLabel totalVideos;
public AddCollectionController(AddCollectionPanel collectionPanel)
{
this.colPanel = collectionPanel;
model = this.colPanel.getModel();
}
#Override
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == colPanel.getSubmitBtn())
{
lib = new LibraryCollection(colPanel.getCodeField(), colPanel.getTitleField());
model.addCollection(lib);
System.out.println(lib);
System.out.println(model.getCollection());
colCode = colPanel.getView().getLibraryStatusbar().getColCode();
colCode.setText("CollectionCode: " + colPanel.getCodeField() + " | ");
totalBooks = colPanel.getView().getLibraryStatusbar().getTotalBooks();
totalBooks.setText("Total Books: " + model.countBooks() + " | ");
totalVideos = colPanel.getView().getLibraryStatusbar().getTotalVideos();
totalVideos.setText("Total Videos: " + model.countVideos());
colPanel.dispose();
}
}
}
public class LibraryView extends JFrame
{
private LMSModel model;
private LibraryToolbar toolbar;
private LibraryPanel panel;
private LibraryStatusbar statusbar;
private LibraryMenu menu;
private LibraryViewController controller;
private AddCollectionPanel addCollectionPanel;
private AddBookPanel addBookPanel;
public LibraryView(LMSModel model)
{
this.model = model;
this.controller = new LibraryViewController(this);
toolbar = new LibraryToolbar(this);
panel = new LibraryPanel(this);
statusbar = new LibraryStatusbar(this);
menu = new LibraryMenu(this);
JFrame library = new JFrame("Library");
library.setSize(1024, 720);
library.setLayout(new BorderLayout(5,5));
library.setLocationRelativeTo(null);
library.add(toolbar, BorderLayout.WEST);
library.add(menu, BorderLayout.NORTH);
library.add(panel, BorderLayout.CENTER);
library.add(statusbar, BorderLayout.SOUTH);
library.setVisible(true);
library.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public LMSModel getModel()
{
return model;
}
public void setModel(LMSModel model)
{
this.model = model;
}
public LibraryMenu getLibraryMenu()
{
return menu;
}
public LibraryToolbar getLibraryToolbar()
{
return toolbar;
}
public LibraryPanel getLibraryPanel()
{
return panel;
}
public LibraryStatusbar getLibraryStatusbar()
{
return statusbar;
}
public LibraryViewController getController()
{
return controller;
}
public void setController(LibraryViewController controller)
{
this.controller = controller;
}
public AddCollectionPanel getAddCollectionPanel()
{
return addCollectionPanel;
}
public void setAddCollectionPanel(AddCollectionPanel addCollectionPanel)
{
this.addCollectionPanel = addCollectionPanel;
}
public AddBookPanel getAddBookPanel()
{
return addBookPanel;
}
public void setAddBookPanel(AddBookPanel addBookPanel)
{
this.addBookPanel = addBookPanel;
}
}
public class AddBookPanel extends JDialog
{
private LMSModel model;
private AddBookController controller;
private LibraryView view;
private Box mainBox, hBox1, hBox2, hBox3;
private JLabel jlCode, jlTitle;
private JButton addBookBtn;
private JTextField codeField;
private JTextField titleField;
public AddBookPanel(LMSModel model)
{
super();
this.model = model;
this.controller = new AddBookController(this);
setTitle("Add Book");
setSize(300,160);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
mainBox = Box.createVerticalBox();
hBox1 = Box.createHorizontalBox();
hBox2 = Box.createHorizontalBox();
hBox3 = Box.createHorizontalBox();
jlCode = new JLabel("Book Code: ");
jlTitle = new JLabel("Book Title: ");
codeField = new JTextField(10);
titleField = new JTextField(10);
addBookBtn = new JButton("Add Book");
addBookBtn.addActionListener(controller);
hBox1.add(jlCode);
hBox1.add(Box.createHorizontalStrut(12));
hBox1.add(codeField);
hBox2.add(jlTitle);
hBox2.add(Box.createHorizontalStrut(10));
hBox2.add(titleField);
hBox3.add(Box.createHorizontalStrut(120));
hBox3.add(addBookBtn);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox1);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox2);
mainBox.add(Box.createVerticalStrut(10));
mainBox.add(hBox3);
add(mainBox);
setVisible(true);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
public String getCodeField()
{
String codeText = new String(codeField.getText());
return codeText;
}
public void clearCodeField()
{
codeField.setText("");
}
public String getTitleField()
{
String titleText = new String(titleField.getText());
return titleText;
}
public void clearTitleField()
{
titleField.setText("");
}
public JButton getAddBookBtn()
{
return addBookBtn;
}
public LMSModel getModel()
{
return model;
}
public AddBookController getController()
{
return controller;
}
public LibraryView getView()
{
return view;
}
}
public class AddBookController implements ActionListener {
private AddBookPanel bookPanel;
private LMSModel model;
private int code;
private LibraryView view;
private JLabel colCode;
private JLabel totalBooks;
private JLabel totalVideos;
public AddBookController(AddBookPanel bookPanel) {
this.bookPanel = bookPanel;
model = this.bookPanel.getModel();
}
#Override
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == bookPanel.getAddBookBtn())
{
code = Integer.parseInt(bookPanel.getCodeField().trim());
Holding h = new Book(code, bookPanel.getTitleField());
model.addHolding(h);
System.out.println(h);
colCode = bookPanel.getView().getLibraryStatusbar().getColCode();
colCode.setText("CollectionCode: " + bookPanel.getCodeField() + " | ");
totalBooks = bookPanel.getView().getLibraryStatusbar().getTotalBooks();
totalBooks.setText("Total Books: " + model.countBooks() + " | ");
totalVideos = bookPanel.getView().getLibraryStatusbar().getTotalVideos();
totalVideos.setText("Total Videos: " + model.countVideos());
bookPanel.dispose();
}
}
}
The problem is probably in all the methods where you are doing JLabel.setText. You probably need to first call the initialization method before setting the text. A NullPointerException exception happens when the object you are changing is null, and if you are getting a NullPointerException when you are changing the text of a JLabel, it means your JLabel is null.
I noticed you are using getters to initialize your objects...Don't... Why getters and setters are evil, but that's a topic that you should get into later. For now, you need to initialize your JLabel!
Look, there is a big difference between declaring and initializing variables. Here is the simplist way I can put it:
Object imAnObject; //Declaring
Now, because you didn't do:
Object imAnObject = new Object(); //Initializing
Then, imAnObject is still null! So obviously there will be a NullPointerException.
How to in initialize your JLabels:
So, right now, you only declare it by doing the following:
private JLabel jlCode, jlTitle;
But you never initialize jlCode or jlTitle. So, somewhere before you try changing the text
You need to initialize it. How?
jlCode = new JLabel();

JavaFX begginer's simple calculator event handling

Hey I'm a begginer at java and i've only been doing this for a short period of time, anyways for my final project in java basics i need to make a simple calculator with a gui, i thought it won't be that hard but i was kinda wrong :P i have managed to do the most (i think) but am stuck atm with the event handling for the operations and setting the value to calculate, here is my code and could you please give me suggestions or tips on how to do it :D
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.WritableObjectValue;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class Calculator extends Application {
private DoubleProperty value = new SimpleDoubleProperty();
#Override
public void start(Stage primaryStage) {
FlowPane pane = new FlowPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets ( 30 , 20 , 30 , 20));
pane.setHgap(5);
pane.setVgap(5);
pane.setMinWidth(400);
pane.setPrefWidth(400);
pane.setMaxWidth(400);
TextField Rezultat = new TextField();
Rezultat.setEditable(false);
Rezultat.setAlignment(Pos.CENTER);
Rezultat.setMinSize(336, 40);
Rezultat.textProperty().bind(Bindings.format("%.0f" , value));
pane.getChildren().add(Rezultat);
Button sedmica = new Button("7");
Button osmica = new Button("8");
Button devetka = new Button("9");
Button plus = new Button("+");
sedmica.setMinSize(80, 80);
osmica.setMinSize(80, 80);
devetka.setMinSize(80, 80);
plus.setMinSize(80, 80);
pane.getChildren().add(sedmica);
sedmicaHandler handler7 = new sedmicaHandler();
sedmica.setOnAction(handler7);
pane.getChildren().add(osmica);
osmicaHandler handler8 = new osmicaHandler();
osmica.setOnAction(handler8);
pane.getChildren().add(devetka);
devetkaHandler handler9 = new devetkaHandler();
devetka.setOnAction(handler9);
pane.getChildren().add(plus);
plusHandler handlerplus = new plusHandler();
plus.setOnAction(handlerplus);
Button cetvorka = new Button("4");
Button petica = new Button("5");
Button sestica = new Button("6");
Button minus = new Button("-");
cetvorka.setMinSize(80, 80);
petica.setMinSize(80, 80);
sestica.setMinSize(80, 80);
minus.setMinSize(80, 80);
pane.getChildren().add(cetvorka);
cetvorkaHandler handler4 = new cetvorkaHandler();
cetvorka.setOnAction(handler4);
pane.getChildren().add(petica);
peticaHandler handler5 = new peticaHandler();
petica.setOnAction(handler5);
pane.getChildren().add(sestica);
sesticaHandler handler6 = new sesticaHandler();
sestica.setOnAction(handler6);
pane.getChildren().add(minus);
minusHandler handlerminus = new minusHandler();
minus.setOnAction(handlerminus);
Button trica = new Button("3");
Button dvica = new Button("2");
Button jedinica = new Button("1");
Button puta = new Button("*");
trica.setMinSize(80, 80);
dvica.setMinSize(80, 80);
jedinica.setMinSize(80, 80);
puta.setMinSize(80, 80);
pane.getChildren().add(jedinica);
jedinicaHandler handler1 = new jedinicaHandler();
jedinica.setOnAction(handler1);
pane.getChildren().add(dvica);
dvicaHandler handler2 = new dvicaHandler();
dvica.setOnAction(handler2);
pane.getChildren().add(trica);
tricaHandler handler3 = new tricaHandler();
trica.setOnAction(handler3);
pane.getChildren().add(puta);
putaHandler handlerputa = new putaHandler();
puta.setOnAction(handlerputa);
Button nula = new Button("0");
Button jednako = new Button("=");
Button podijeljeno = new Button("/");
Button EE = new Button ("EE");
nula.setMinSize(80, 80);
jednako.setMinSize(80, 80);
podijeljeno.setMinSize(80, 80);
EE.setMinSize(80, 80);
pane.getChildren().add(EE);
EEHandler handlerEE = new EEHandler();
EE.setOnAction(handlerEE);
pane.getChildren().add(nula);
nulaHandler handler0 = new nulaHandler();
nula.setOnAction(handler0);
pane.getChildren().add(jednako);
jednakoHandler handlerjednako = new jednakoHandler();
jednako.setOnAction(handlerjednako);
pane.getChildren().add(podijeljeno);
podijeljenoHandler handlerpodijeljeno = new podijeljenoHandler();
podijeljeno.setOnAction(handlerpodijeljeno);
Scene scene = new Scene(pane);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main (String[] args) {
Application.launch(args);
}
}
class nulaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
value.set(0);
}
}
class jedinicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("1");
}
}
class dvicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("2");
}
}
class tricaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("3");
}
}
class cetvorkaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("4");
}
}
class peticaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("5");
}
}
class sesticaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("6");
}
}
class sedmicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("7");
}
}
class osmicaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("8");
}
}
class devetkaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("9");
}
}
class plusHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("+");
}
}
class minusHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("-");
}
}
class putaHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("*");
}
}
class podijeljenoHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("/");
}
}
class jednakoHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("=");
}
}
class EEHandler implements EventHandler<ActionEvent>{
#Override
public void handle(ActionEvent e){
System.out.println("EE");
}
}
My handlers are just basic ones, they print the number into the console so you can disregard them, i saw some examples with the value.set commands should i go with them or ? please help deadline is in 2 weeks. Thanks a lot
I will not do the homework for you, but just a few tips:
variable-names should start with a lowercase letter (TextField rezultat, not Rezultat)
think about what exactly you expect to happen when you press the buttons:
what should your calculator do, if you press 5 '-' '+' 55. should it subtract or add 55 from 5)
do you want to calculate more than one operation? (5+5+5+5/5)
what about decimal numbers? (you can not fill them in, at your current design)
And you do nearly the same thing for every button.(or at least for 10 buttons you have the same logic)
you can create your application in a loop:
public class Calculator extends Application {
private TextField textField = new TextField();
#Override
public void start(Stage primaryStage) {
List<String> buttons = Arrays.asList("7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", "=", "/", "EE");
FlowPane pane = new FlowPane();
pane.setAlignment(Pos.CENTER);
pane.setPadding(new Insets(30, 20, 30, 20));
pane.setHgap(5);
pane.setVgap(5);
pane.setMinWidth(400);
pane.setPrefWidth(400);
pane.setMaxWidth(400);
textField.setEditable(false);
textField.setAlignment(Pos.CENTER);
textField.setMinSize(336, 40);
// Rezultat.textProperty().bind(Bindings.format("%.0f", value));
pane.getChildren().add(textField);
for (String button : buttons) {
Button b = new Button(button);
b.setMinSize(80, 80);
pane.getChildren().add(b);
b.setOnAction((e) -> doSomething(b.getText()));
}
Scene scene = new Scene(pane);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
private void doSomething(String text) {
if (text.equalsIgnoreCase("=")) {
// Calc
}
else if (text.equalsIgnoreCase("EE")) {
// EE
} else if (text.equalsIgnoreCase("+") || text.equalsIgnoreCase("-") || text.equalsIgnoreCase("*") || text.equalsIgnoreCase("/")) {
// + - * /
}
// ....
else {
// numeric
textField.appendText(text);
}
}
public static void main(String[] args) {
Application.launch(args);
}
}
public class View extends Application{
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage){
primaryStage.setTitle("Calculator");
GridPane root = new GridPane();
Label textBox1 = new Label("Text1");
root.add(textBox1, 0, 0, 5, 1);
Label textBox2 = new Label("Text2");
root.add(textBox2, 0, 1, 5, 1);
textBox1.setId("lblTextBox1");
textBox2.setId("lblTextBox2");
Button btn0 = new Button("0");
Button btn1 = new Button("1");
Button btn2 = new Button("2");
Button btn3 = new Button("3");
Button btn4 = new Button("4");
Button btn5 = new Button("5");
Button btn6 = new Button("6");
Button btn7 = new Button("7");
Button btn8 = new Button("8");
Button btn9 = new Button("9");
btn0.setId("btn0");
btn1.setId("btn1");
btn2.setId("btn2");
btn3.setId("btn3");
btn4.setId("btn4");
btn5.setId("btn5");
btn6.setId("btn6");
btn7.setId("btn7");
btn8.setId("btn8");
btn9.setId("btn9");
Button btnDot = new Button(".");
Button btnPlus = new Button("+");
Button btnMinus = new Button("-");
Button btnTimes = new Button("*");
Button btnDivide = new Button("/");
Button btnEquals = new Button("=");
Button btnMC = new Button("MC");
Button btnMR = new Button("MR");
Button btnMS = new Button("MS");
Button btnMPlus = new Button("M+");
Button btnMMinus = new Button("M-");
Button btnBack = new Button("<=");
Button btnCE = new Button("CE");
Button btnC = new Button("C");
Button btnPlusOrMinus = new Button("+/-");
Button btnSqrt = new Button("sqrt");
Button btnPercentage= new Button("%");
Button btn1OverX = new Button("1/x");
btnPlus.setId("btnPlus");
btnTimes.setId("btnTimes");
btnDot.setId("btnDot");
btnEquals.setId("btnEquals");
btnC.setId("btnClear");
btn0.setMaxHeight(Double.MAX_VALUE);
btn0.setMaxWidth(Double.MAX_VALUE);
btn1.setMaxHeight(Double.MAX_VALUE);
btn1.setMaxWidth(Double.MAX_VALUE);
btn2.setMaxHeight(Double.MAX_VALUE);
btn2.setMaxWidth(Double.MAX_VALUE);
btn3.setMaxHeight(Double.MAX_VALUE);
btn3.setMaxWidth(Double.MAX_VALUE);
btn4.setMaxHeight(Double.MAX_VALUE);
btn4.setMaxWidth(Double.MAX_VALUE);
btn5.setMaxHeight(Double.MAX_VALUE);
btn5.setMaxWidth(Double.MAX_VALUE);
btn6.setMaxHeight(Double.MAX_VALUE);
btn6.setMaxWidth(Double.MAX_VALUE);
btn7.setMaxHeight(Double.MAX_VALUE);
btn7.setMaxWidth(Double.MAX_VALUE);
btn8.setMaxHeight(Double.MAX_VALUE);
btn8.setMaxWidth(Double.MAX_VALUE);
btn9.setMaxHeight(Double.MAX_VALUE);
btn9.setMaxWidth(Double.MAX_VALUE);
btnEquals.setMaxHeight(Double.MAX_VALUE);
btnEquals.setMaxWidth(Double.MAX_VALUE);
btnMC.setMaxHeight(Double.MAX_VALUE);
btnMC.setMaxWidth(Double.MAX_VALUE);
btnMMinus.setMaxHeight(Double.MAX_VALUE);
btnMMinus.setMaxWidth(Double.MAX_VALUE);
btnPlusOrMinus.setMaxHeight(Double.MAX_VALUE);
btnPlusOrMinus.setMaxWidth(Double.MAX_VALUE);
btnPercentage.setMaxHeight(Double.MAX_VALUE);
btnPercentage.setMaxWidth(Double.MAX_VALUE);
btnSqrt.setMaxHeight(Double.MAX_VALUE);
btnSqrt.setMaxWidth(Double.MAX_VALUE);
btn1OverX.setMaxHeight(Double.MAX_VALUE);
btn1OverX.setMaxWidth(Double.MAX_VALUE);
btnPlus.setMaxHeight(Double.MAX_VALUE);
btnPlus.setMaxWidth(Double.MAX_VALUE);
btnMinus.setMaxHeight(Double.MAX_VALUE);
btnMinus.setMaxWidth(Double.MAX_VALUE);
btnTimes.setMaxHeight(Double.MAX_VALUE);
btnTimes.setMaxWidth(Double.MAX_VALUE);
btnDivide.setMaxHeight(Double.MAX_VALUE);
btnDivide.setMaxWidth(Double.MAX_VALUE);
btnCE.setMaxHeight(Double.MAX_VALUE);
btnCE.setMaxWidth(Double.MAX_VALUE);
btnC.setMaxHeight(Double.MAX_VALUE);
btnC.setMaxWidth(Double.MAX_VALUE);
btnDot.setMaxHeight(Double.MAX_VALUE);
btnDot.setMaxWidth(Double.MAX_VALUE);
root.add(btnMC,0,1);
root.add(btnMR,1,1);
root.add(btnMS,2,1);
root.add(btnMPlus,3,1);
root.add(btnMMinus,4,1);
root.add(btnBack,0,2);
root.add(btnCE,1,2);
root.add(btnC,2,2);
root.add(btnPlusOrMinus,3,2);
root.add(btnSqrt,4,2);
root.add(btn7,0,3);
root.add(btn8,1,3);
root.add(btn9,2,3);
root.add(btnDivide,3,3);
root.add(btnPercentage,4,3);
root.add(btn4,0,4);
root.add(btn5,1,4);
root.add(btn6,2,4);
root.add(btnTimes,3,4);
root.add(btn1OverX,4,4);
root.add(btn1,0,5);
root.add(btn2,1,5);
root.add(btn3,2,5);
root.add(btnMinus,3,5);
root.add(btnEquals,4,5,1,2);
root.add(btn0,0,6,2,1);
root.add(btnDot,2,6);
root.add(btnPlus,3,6);
root.setVgap(5);
root.setHgap(5);
root.setPadding(new Insets(5,5,5,5));
primaryStage.setScene(new Scene(root));
primaryStage.show();
Controller controller = new Controller(primaryStage.getScene());
}
}
public class Model {
SimpleDoubleProperty totalResult = new SimpleDoubleProperty(0);
SimpleDoubleProperty curNumber = new SimpleDoubleProperty(0);
SimpleStringProperty stringDisplayed = new SimpleStringProperty();
String operatorPressed = "";
Boolean isDecimal = false;
int decimalCouter = 0;
public void plusOperator(){
calculate();
operatorPressed = "+";
}
public void calculate(){
switch (operatorPressed){
case "+" :
totalResult.set(totalResult.get()+ curNumber.get());
stringDisplayed.set(stringDisplayed.get()+" + " +curNumber.get());
break;
case "*" :
totalResult.set(totalResult.get()*curNumber.get());
stringDisplayed.set(stringDisplayed.get()+" * " +curNumber.get());
break;
default:
totalResult.set(curNumber.get());
stringDisplayed.set(curNumber.get()+"");
}
curNumber.set(0);
operatorPressed = "";
isDecimal = false;
decimalCouter = 0;
}
public void multiplyOperator(){
calculate();
operatorPressed = "*";
}
public void equalsOperator(){
calculate();
curNumber.setValue(totalResult.get());
totalResult.set(0);
}
public void clearOperator(){
totalResult.setValue(0);
curNumber.setValue(0);
stringDisplayed.set("");
decimalCouter = 0;
isDecimal = false;
}
public void pressedNumber(int number){
if(!isDecimal){
curNumber.setValue(curNumber.get()*10+number);
}
else{
decimalCouter++;
Double tempCurrentNum = curNumber.get();
tempCurrentNum = tempCurrentNum*Math.pow(10,decimalCouter);
tempCurrentNum = tempCurrentNum+number;
tempCurrentNum = tempCurrentNum*Math.pow(10,-decimalCouter);
curNumber.set(tempCurrentNum);
}
}
public void dotOperator(){
isDecimal = true;
}
}
public class Controller {
Model newModel = new Model();
Controller(Scene scene){
Button btnPlus, btnTimes, btnEquals, btnClear, btnDot;
Label textBox1, textBox2;
for(int ii=0;ii<=9;ii++){
Button button = (Button)scene.lookup("#btn"+ii);
int finalIi = ii;
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
pressedNumber(finalIi);
}
});
}
btnPlus = (Button)scene.lookup("#btnPlus");
btnTimes = (Button)scene.lookup("#btnTimes");
btnEquals = (Button)scene.lookup("#btnEquals");
btnDot = (Button)scene.lookup("#btnDot");
btnClear = (Button)scene.lookup("#btnClear");
textBox1 = (Label)scene.lookup("#lblTextBox1");
textBox2 = (Label)scene.lookup("#lblTextBox2");
btnPlus.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
plusOperator();
}
});
btnTimes.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
multiplyOperator();
}
});
btnEquals.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
equalsOperator();
}
});
btnClear.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
clearOperator();
}
});
btnDot.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
dotOperator();
}
});
textBox1.textProperty().bind(newModel.stringDisplayed);
textBox2.textProperty().bind(newModel.curNumber.asString());
}
public void pressedNumber(int number){
newModel.pressedNumber(number);
}
public void plusOperator(){
newModel.plusOperator();
}
public void multiplyOperator(){
newModel.multiplyOperator();
}
public void equalsOperator(){
newModel.equalsOperator();
}
public void clearOperator(){
newModel.clearOperator();
}
public void dotOperator(){
newModel.dotOperator();
}
}

Categories