TreeItem is Overwritten in JavaFX. How to solve this? - java

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();
});

Related

Trying to add data to tableView from arrayList (javaFx)

I am trying to populate the tableView with the data that is in the observableList but it will not show up when i run the program.
Here are parts of my program:
private TableView<Crypto> tableView = new TableView<Crypto>();
private static ArrayList<Crypto> cryptoData = new ArrayList();
private static ObservableList<Crypto> data = FXCollections.observableArrayList(cryptoData);
//*******Crypto Class************
static class Crypto{
private SimpleStringProperty coinName,
coinsBought,
costPerCoin,
totalSpent,
currentPrice,
currentValue,
profit,
roi;
public String getcoinName() {
return coinName.get();
}
public String getCoinsBought() {
return coinsBought.get();
}
public String getCostPerCoin() {
return costPerCoin.get();
}
public String getTotalSpent() {
return totalSpent.get();
}
public String getCurrentPrice() {
return currentPrice.get();
}
public String getCurrentValue() {
return currentValue.get();
}
public String getProfit() {
return profit.get();
}
public String getRoi() {
return roi.get();
}
Crypto(String name, String numBought, String costPerCoin, String totalSpent, String curPrice, String curValue, String profit, String roi){
this.coinName = new SimpleStringProperty(name);
this.coinsBought = new SimpleStringProperty(numBought);
this.costPerCoin = new SimpleStringProperty(costPerCoin);
this.totalSpent = new SimpleStringProperty(totalSpent);
this.currentPrice = new SimpleStringProperty(curPrice);
this.currentValue = new SimpleStringProperty(curValue);
this.profit = new SimpleStringProperty(profit);
this.roi = new SimpleStringProperty(roi);
}
#Override
public String toString() {
return ("[" + coinName.get() + ", " + coinsBought.get() + ", " + costPerCoin.get() + ", " +
totalSpent.get() + ", " + currentPrice.get() + ", " + currentValue.get() + ", " +
profit.get() + ", " + roi.get() + "]");
}
}//*********END Crypto Class*************
#Override
public void start(Stage primaryStage) {
try {
GridPane root = new GridPane();
//title text
Text titleText = new Text();
titleText.setText("Crypto Portfolio");
titleText.setY(600);
titleText.setFont(Font.font("Veranda", FontWeight.BOLD, FontPosture.REGULAR,40));
//refresh button
Button refresh = new Button("Refresh Prices");
refresh.setOnAction(e -> {
//ADD button refresh
});
//total amount text
Text totalDollar = new Text();
totalDollar.setText(getTotalDollar());
//table columns
TableColumn coinColumn = new TableColumn("Coin");
coinColumn.setCellValueFactory(new PropertyValueFactory<>("coinName"));
TableColumn costColumn = new TableColumn("Cost");
costColumn.setCellValueFactory(new PropertyValueFactory<>("totalSpent"));
TableColumn coinBoughtColumn = new TableColumn("Coins Bought");
coinBoughtColumn.setCellValueFactory(new PropertyValueFactory<>("coinsBought"));
TableColumn costPerCoinColumn = new TableColumn("Cost per Coin");
costPerCoinColumn.setCellValueFactory(new PropertyValueFactory<>("costPerCoin"));
TableColumn currentPriceColumn = new TableColumn("Current Coin Price");
currentPriceColumn.setCellValueFactory(new PropertyValueFactory<>("currentPrice"));
TableColumn currentValueColumn = new TableColumn("Curren Value");
currentValueColumn.setCellValueFactory(new PropertyValueFactory<>("currentValue"));
TableColumn profitColumn = new TableColumn("Profit");
profitColumn.setCellValueFactory(new PropertyValueFactory<>("profit"));
TableColumn roiColumn = new TableColumn("ROI");
roiColumn.setCellValueFactory(new PropertyValueFactory<>("roi"));
tableView.setItems(data);
tableView.getColumns().addAll(coinColumn, costColumn, coinBoughtColumn, costPerCoinColumn, currentPriceColumn, currentValueColumn, profitColumn, roiColumn);
Scene scene = new Scene(root,1200,900);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
root.setHgap(10);
root.setVgap(10);
//sets gridLines visible for debug
root.setGridLinesVisible(true);
primaryStage.setScene(scene);
primaryStage.setTitle("Mike's Crypto Portfolio");
root.add(titleText, 0,0);
root.add(refresh, 3, 0);
root.add(tableView, 0, 1);
primaryStage.show();
new Thread () {
#Override
public void run() {
try {
readCSV("crypto.csv");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
} catch(Exception e) {
e.printStackTrace();
}
}//*****************END Start***************************
}
I thought if I added this it would work but I get a WARNING: Can not retrieve property 'coinName' in PropertyValueFactory: javafx.scene.control.cell.PropertyValueFactory#2cc2c23 with provided class type: class application.Main$Crypto java.lang.IllegalStateException: Cannot read from unreadable property coinName
but for everything besides coinName the error also adds :java.lang.RuntimeException: java.lang.IllegalAccessException: class com.sun.javafx.reflect.Trampoline cannot access a member of class application.Main$Crypto with modifiers "public"
for(Crypto coin : cryptoData) {
data.add(coin);
}

New item is not updated in the TreeTableView from while getting data from DB?

New to javafx in learning stage.I am trying to Update the data from the database but when the call the
getConnection method the list is updated but the Treeitem is not updated in the view.
On the first screen it shows the available Db's but after creating new the tree table view is not updating even after calling the getConnection();
marked the place where needed solution with "//-----------------Calling Here for Updation"
Tried
1.Used Refresh();
2.tried to clear the view;
PaneClass.java
public class PanesClass extends Application {
ObservableList<Connections> cList = FXCollections.observableArrayList();
DbConnection dbConnection = new DbConnection();
TreeItem rootItem = new TreeItem();
TreeTableView activeConnections = new TreeTableView();
AnchorPane firstPane = new AnchorPane();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
NewConnection newConnection = new NewConnection();
SplitPane root = new SplitPane();
AnchorPane secondPane = new AnchorPane();
HBox buttonBox = new HBox();
BorderPane topBar = new BorderPane();
Button nConnection = new Button("+");
buttonBox.getChildren().addAll(nConnection);
topBar.setTop(buttonBox);
TreeTableColumn<String, Connections> cNameColoumn = new TreeTableColumn<>("Name");
cNameColoumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("name"));
TreeTableColumn<String, Connections> cStatusColoumn = new TreeTableColumn<>("Status");
cStatusColoumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("status"));
activeConnections.getColumns().addAll(cNameColoumn, cStatusColoumn);
activeConnections.setLayoutX(20);
activeConnections.setLayoutY(40);
firstPane.getChildren().addAll(topBar, activeConnections);
root.getItems().addAll(firstPane, secondPane);
Scene sc = new Scene(root, 600, 480);
primaryStage.setScene(sc);
primaryStage.show();
activeConnections.setShowRoot(false);
getconnection();
nConnection.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
newConnection.getConnection(activeConnections);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
});
}
void getconnection() throws ClassNotFoundException, SQLException {
rootItem.getChildren().clear();
cList.clear();
cList = dbConnection.getDatabase();
for (Connections temp : cList) {
rootItem.getChildren().add(new TreeItem<Connections>(temp));
System.out.println(temp);
}
activeConnections.setRoot(rootItem);
activeConnections.refresh();
}
}
NewConnection.java
public class NewConnection {
Connections connection = null;
ObservableList<Connections> cList = FXCollections.observableArrayList();
PanesClass panesClass = new PanesClass();
TreeItem<Connections> cItem = null;
TreeItem rootItem = new TreeItem();
public void getConnection(TreeTableView<Connections> activeConnections) throws ClassNotFoundException, SQLException {
DbConnection dbConnection=new DbConnection();
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);
//cList=dbConnection.getDatabase();
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);
cDetails.setVgap(10);
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) {
try {
dbConnection.setNewDatabase(uName.getText());
panesClass.getconnection();//-----------------*Calling Here for Updation*
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
secondaryStage.close();
event.consume();
}
});
}
}
Connections.java
public class Connections {
private String name;
private String password;
private String url;
public Connections() {
super();
}
public Connections(String name, String password, String url) {
super();
this.name = name;
this.password = password;
this.url = url;
}
public Connections(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Override
public String toString() {
return "Connections [name=" + name + ", password=" + password + ", url=" + url + "]";
}
}

Javafx: TextField Handler

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 ?

JTextArea not updating when selection changes in JComboBox

I am trying to add a class for each course in the drop down menu on the right corner of the image, as shown in the code in the action Performed there is one class but the same class opens for all the courses so how can i make each one of them open a different class?
this part is confusing me im not sure if i need to do anything with it or not
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
the list of courses in the left corner works perfectly fine with me but my only problem is instead of the list on the left i want the list on the right to work and it has something to do with crse
public class CourseWork extends JFrame implements ActionListener, KeyListener {
CommonCode cc = new CommonCode();
JPanel pnl = new JPanel(new BorderLayout());
JTextArea txtNewNote = new JTextArea();
JTextArea txtDisplayNotes = new JTextArea();
JTextField search = new JTextField();
ArrayList<String> note = new ArrayList<>();
ArrayList<String> course = new ArrayList<>();
JComboBox courseList = new JComboBox();
String crse = "";
AllNotes allNotes = new AllNotes();
public static void main(String[] args) {
// This is required for the coursework.
//JOptionPane.showMessageDialog(null, "Racha Chaouby");
CourseWork prg = new CourseWork();
}
// Using MVC
public CourseWork() {
model();
view();
controller();
}
#Override
public void actionPerformed(ActionEvent ae) {
if ("Close".equals(ae.getActionCommand())) {
}
if ("Course".equals(ae.getActionCommand())) {
crse = courseList.getSelectedItem().toString();
COMP1752 cw = new COMP1752();
}
if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
}
if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
}
if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
}
if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
if ("Course1752".equals(ae.getActionCommand())) {
COMP1752 cw = new COMP1752();
}
if ("Course1753".equals(ae.getActionCommand())) {
COMP1753 cw = new COMP1753();
}
if ("Cours1110".equals(ae.getActionCommand())) {
MATH1110 cw = new MATH1110();
}
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped not coded yet.");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed not coded yet.");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased not coded yet.");
}
private void model() {
course.add("COMP1752");
course.add("COMP1753");
course.add("MATH1110");
crse = course.get(0);
//Note nt = new Note();
//nt.noteID = 1;
//t.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "Arrays are of fixed length and are inflexible.";
//allNotes.allNotes.add(nt);
//nt = new Note();
//nt.noteID = 2;
//nt.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "ArraysList can be added to and items can be deleted.";
//allNotes.allNotes.add(nt);
}
private void view() {
Font fnt = new Font("Georgia", Font.PLAIN, 24);
JMenuBar menuBar = new JMenuBar();
JMenu kurs = new JMenu();
kurs = new JMenu("Courses");
kurs.setToolTipText("Course tasks");
kurs.setFont(fnt);
kurs.add(makeMenuItem("COMP1752", "Course1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("COMP1753", "Course1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("MATH1110", "Course1110", "Coursework requirments.", fnt));
menuBar.add(kurs);
JMenu note = new JMenu();
note = new JMenu("Note");
note.setToolTipText("Note tasks");
note.setFont(fnt);
note.add(makeMenuItem("New", "NewNote", "Create a new note.", fnt));
note.addSeparator();
note.add(makeMenuItem("Close", "Close", "Clear the current note.", fnt));
menuBar.add(note);
menuBar.add(makeMenuItem("Exit", "Exit", "Close this program", fnt));
// This will add each course to the combobox
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
this.setJMenuBar(menuBar);
JToolBar toolBar = new JToolBar();
// Setting up the ButtonBar
JButton button = null;
button = makeButton("Document", "Coursework",
"Open the coursework window.",
"Coursework");
toolBar.add(button);
button = makeButton("Create", "NewNote",
"Create a new note.",
"New");
toolBar.add(button);
button = makeButton("closed door", "Close",
"Close this note.",
"Close");
toolBar.add(button);
toolBar.addSeparator();
button = makeButton("exit button", "Exit",
"Exit from this program.",
"Exit");
toolBar.add(button);
toolBar.addSeparator();
// This forces anything after it to the right.
toolBar.add(Box.createHorizontalGlue());
search.setMaximumSize(new Dimension(6900, 30));
search.setFont(fnt);
toolBar.add(search);
toolBar.addSeparator();
button = makeButton("search", "SearchKeyword",
"Search for this text.",
"Search");
toolBar.add(button);
add(toolBar, BorderLayout.NORTH);
JPanel pnlWest = new JPanel();
pnlWest.setLayout(new BoxLayout(pnlWest, BoxLayout.Y_AXIS));
pnlWest.setBorder(BorderFactory.createLineBorder(Color.black));
txtNewNote.setFont(fnt);
pnlWest.add(txtNewNote);
JButton btnAddNote = new JButton("Add note");
btnAddNote.setActionCommand("NewNote");
btnAddNote.addActionListener(this);
pnlWest.add(btnAddNote);
add(pnlWest, BorderLayout.WEST);
JPanel cen = new JPanel();
cen.setLayout(new BoxLayout(cen, BoxLayout.Y_AXIS));
cen.setBorder(BorderFactory.createLineBorder(Color.black));
txtDisplayNotes.setFont(fnt);
cen.add(txtDisplayNotes);
add(cen, BorderLayout.CENTER);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Coursework");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // Needed to ensure that the items can be seen.
}
private void controller() {
addAllNotes();
}
protected JMenuItem makeMenuItem(
String txt,
String actionCommand,
String toolTipText,
Font fnt) {
JMenuItem mnuItem = new JMenuItem();
mnuItem.setText(txt);
mnuItem.setActionCommand(actionCommand);
mnuItem.setToolTipText(toolTipText);
mnuItem.setFont(fnt);
mnuItem.addActionListener(this);
return mnuItem;
}
protected JButton makeButton(
String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Create and initialize the button.
JButton button = new JButton();
button.setToolTipText(toolTipText);
button.setActionCommand(actionCommand);
button.addActionListener(this);
//Look for the image.
String imgLocation = System.getProperty("user.dir")
+ "\\icons\\"
+ imageName
+ ".png";
File fyle = new File(imgLocation);
if (fyle.exists() && !fyle.isDirectory()) {
// image found
Icon img;
img = new ImageIcon(imgLocation);
button.setIcon(img);
} else {
// image NOT found
button.setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
private void addNote(String text) {
allNotes.addNote(allNotes.getMaxID(), crse, text);
addAllNotes();
}
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotes()) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
public String getDateAndTime() {
String UK_DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
String ukDateAndTime;
Calendar cal = Calendar.getInstance();
SimpleDateFormat uksdf = new SimpleDateFormat(UK_DATE_FORMAT_NOW);
ukDateAndTime = uksdf.format(cal.getTime());
return ukDateAndTime;
}
}
code snippet
this is the AllNotes class:
public class AllNotes extends CommonCode {
private ArrayList<Note> allNotes = new ArrayList<>();
private String crse = "";
private int maxID = 0;
AllNotes() {
readAllNotes();
}
public final int getMaxID() {
maxID++;
return maxID;
}
private void readAllNotes() {
ArrayList<String> readNotes = new ArrayList<>();
readNotes = readTextFile(appDir + fileSeparator + "Notes.txt");
System.out.println(readNotes.get(0));
if (!"File not found".equals(readNotes.get(0))) {
allNotes.clear();
for (String str : readNotes) {
String[] tmp = str.split("\t");
int nid = Integer.parseInt(tmp[0]);
Note n = new Note(nid, tmp[1], tmp[2], tmp[3]);
allNotes.add(n);
if (nid > maxID) {
maxID = nid;
}
}
}
maxID++;
}
public void addNote(int maxID, String course, String note) {
Note myNote = new Note(maxID, course, note);
allNotes.add(myNote);
writeAllNotes();
}
public ArrayList<Note> getAllNotes() {
return allNotes;
}
private void writeAllNotes() {
String path = appDir + fileSeparator +"Notes.txt";
ArrayList<String> writeNote = new ArrayList<>();
for (Note n : allNotes) {
String tmp = n.getNoteID() + "\t";
tmp += n.getCourse() + "\t";
tmp += n.getDayte() + "\t";
tmp += n.getNote();
writeNote.add(tmp);
}
try {
writeTextFile(path, writeNote);
} catch (IOException ex) {
System.out.println("Problem! " + path);
}
}
public String searchAllNotesByKeyword(String noteList, int i, String s) {
if (i == allNotes.size()) {
return noteList;
}
if (allNotes.get(i).getNote().contains(s)) {
noteList += allNotes.get(i).getNote() + "\n";
}
return searchAllNotesByKeyword(noteList, i + 1, s);
}
}
When you init your drop down of courses, set the action command to be the same value that you record in your file, this will make everything consistent when looking up notes from the file. so this way
kurs.add(makeMenuItem("Course 1752", "COMP1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1753", "COMP1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1110", "MATH1110", "Coursework requirments.", fnt));
Then change actionPerformed to store the selected value form the drop down to the crse attribute, and call addAllNotes() to refresh the notes list
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("actionPerformed: " + ae.getActionCommand());
if ("Close".equals(ae.getActionCommand())) {
} else if ("Course".equals(ae.getActionCommand())) {
// set the value of the selected element into the crse attribute
crse = courseList.getSelectedItem().toString();
// Refresh the text area
addAllNotes();
} else if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
} else if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
} else if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
} else if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
System.out.println("selectedCourse: " + crse);
}
in AllNotes, create a new method to return the notes for a specific course.
public ArrayList<Note> getAllNotesForCourse(String course) {
ArrayList<Note> notes = new ArrayList<>();
for(Note note : allNotes) {
if(course.equalsIgnoreCase(note.getCourse())) {
notes.add(note);
}
}
return notes;
}
then in the addAllNotes method, call getAllNotesForCourse, passing the selected course. This will update txtDisplayNotes with the notes from the selected course
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotesForCourse(crse)) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
I think this is all I modified and it works for me.

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/.

Categories