Adding an individual array list item to individual tile - java

I am currently trying to place individual items within an array list into individual tiles within a inventory GUI. All the tiles are set up and I can display each array list item individually within the console line.
This is the simple GUI:
This is my attempt so far.
HBox itemTile[] = new HBox[31];
for (int i = 0; i < 30; i++) {
Button deleteButton = new Button("Delete Item");
deleteButton.setOnAction((ActionEvent event) -> {
displayItems2(); //temp info to console - delete item code to be added
JOptionPane.showMessageDialog(null, "Item has been deleted", null, 1);
});
itemTile[i] = new HBox(new Label("Item: " + i + " "));
itemTile[i].setStyle("-fx-border-color: black;");
itemTile[i].setPadding(new Insets(5));
itemTile[i].getChildren().add(deleteButton);
itemTile[i].setAlignment(Pos.CENTER_LEFT);
itemTile[i].setStyle("-fx-background-color: #e5efff; -fx-border-color: black;");
this.getChildren().add(itemTile[i]);
}
}
private void displayItems2(){
this.getChildren().removeAll(this.getChildren());
displayInvStructure();
ArrayList<String> descs = InventoryManager.getInstance().getItemDescriptions();
for (int i = 0; i < descs.size(); i++) {
String retString = descs.get(i);
System.out.println("Array item is = " + " " + i + " " + retString);
}
//If i = itemTile[i]
//Add retString to itemTile[i]
}
How do I place each individual retString into each tile using the itemTile[i]?
I'm relatively new to coding and Java, so I have a sneaking suspicion I am over complicating things.

If you want to assign values to the itemTile array inside a method like displayItems2, there are two possibilities: 1) pass a reference to itemTile into displayItems2 or 2) make itemTile a class member.
Example 1 (pass a reference):
private void displayItems2(HBox itemTile) {
// [...]
itemTile[i] = descs.get(i);
}
Example 2 (class member):
class MyClass {
// [...]
HBox itemTile;
// [...]
private void displayItems2() {
// [...]
itemTile[i] = descs.get(i);
}
}

Related

Creating arrays using Joptionpane input

Create a program that will count the number of times an input name appeared in a list from an input array of 10 names. Using JOptionPne.
(After input of 10 names and for a name to count from the list, and assuming Maria is the name entered to count)
Expected sample output
My code so far:
import javax.swing.JOptionPane;
public class Chapter4Act_Array {
public static void main(String[] args) {
String ArrayOf_Names[] = new String[10];
for (int i = 0; i < ArrayOf_Names.length; i++) {
ArrayOf_Names[i] = JOptionPane.showInputDialog("Enter name" + (i + 1) + ":");
}
System.out.println("Your friends are: ");
for (int i = 0; i < ArrayOf_Names.length; i++) {
System.out.println(ArrayOf_Names[i]);
}
}
}
Little short on information but I think i know what you are trying to accomplish. In the demo code below, a JOptionPane is used to acquire the names from a User. Do do this a custom panel is created and passed to the JOptionPane#showOptionPane() method:
Yes...that's a JOptionPane. This is most likely more than you require but then again there isn't enough info to clarify either way. In any case, here is the code and be sure to read all the comments in code (comments always make the code look more than it really is):
/* Create a JPanel object to display within the JOptionPane
and fill it with the components we want. */
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
JLabel msg = new JLabel("<html><center><font size='4'>Please enter <font "
+ "color=blue>User</font> names into the list below:"
+ "</font></html>");
msg.setVerticalAlignment(JLabel.TOP);
msg.setPreferredSize(new Dimension(135, 60));
jp.add(msg, BorderLayout.NORTH);
// Add a JTextfield and JLabel
JPanel textPanel = new JPanel();
textPanel.setLayout(new BorderLayout());
JLabel name = new JLabel("Enter Name:");
JTextField textField = new JTextField(0);
textPanel.add(name, BorderLayout.NORTH);
textPanel.add(textField, BorderLayout.SOUTH);
jp.add(textPanel, BorderLayout.CENTER);
// Add a JList (in a JScrollPane) and Add/Remove buttons
JPanel listPanel = new JPanel();
DefaultListModel<String> listModel = new DefaultListModel<>();
JList<String> list = new JList<>(listModel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(120, 150));
scrollPane.setViewportView(list);
listPanel.add(scrollPane, BorderLayout.WEST);
// Add/Remove Buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
int listItemCount = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (textField.getText() != null) {
listModel.addElement(textField.getText());
if (listModel.getSize() == 10) {
addButton.setEnabled(false);
return;
}
}
textField.requestFocus();
textField.setSelectionStart(0);
textField.setSelectionEnd(textField.getText().length());
}
});
buttonPanel.add(addButton, BorderLayout.NORTH);
JButton removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener() {
int listItemCount = 0;
#Override
public void actionPerformed(ActionEvent e) {
int selectedIndex = list.getSelectedIndex();
if (list.getSelectedIndex() >= 0) {
listModel.remove(selectedIndex);
}
if (listModel.getSize() < 10) {
addButton.setEnabled(true);
}
if (selectedIndex > 0) {
list.setSelectedIndex(selectedIndex - 1);
}
}
});
buttonPanel.add(removeButton, BorderLayout.CENTER);
listPanel.add(buttonPanel, BorderLayout.EAST);
jp.add(listPanel, BorderLayout.SOUTH);
// Supply what we want the dialog button captions are to be.
Object[] buttons = {"Process", "Cancel"};
// Display the JOptionPane using the Option Dialog.
int res = JOptionPane.showOptionDialog(this, jp, "User Names", 0,
JOptionPane.PLAIN_MESSAGE, null, buttons, 1);
// The following code will no run until the JOptionPane is closed.
/* If the list does not contain 10 names then inform
the User and make him/her do it over again. */
if (listModel.getSize() < 10) {
System.out.println("Not Enough Names! Do it again!");
return;
}
/* Fill a String[] Array with the names in List but,
at the same time keep track of how many times a
specific name was in that list. We use a Map/HashMap
to hold the occurrences information. You really don't
need a String[] Array since the Map can take care of
everything but I thought you might want them separate. */
String[] names = new String[listModel.size()]; // Declare a String[] Array
Map<String, Integer> nameMap = new HashMap<>(); // Declare a Map
// Iterate through the List that was in the dialog using the List Model
for (int i = 0; i < listModel.size(); i++) {
// Get name from list at current index
names[i] = listModel.get(i);
// Is the name already in the Map?
if (nameMap.containsKey(names[i])) {
// Yes, it is ...
// Get the current number of times Count Value for that specific name
int value = nameMap.get(names[i]);
value++; // Increment that value by 1
nameMap.put(names[i], value); // Update the count value for that specific name.
}
else {
/* No, it isn't so add the Name as key and
a count value of 1 for the value. */
nameMap.put(names[i], 1);
}
}
/* Processing the name information is now complete,
we just need to diplay the acquired data now held
within the names[] Array and the nameMap Map. */
/* Display the oringinal list which is now
contained within the names[] String Array. */
for (int i = 0; i < names.length; i++) {
System.out.printf("%-12s%-15s%n", "Name #" + (i+1), names[i]);
}
System.out.println();
/* Now, display the occurrences for all those
names held within nameMap. */
String n;
int o;
for (Map.Entry<String,Integer> entry : nameMap.entrySet()) {
n = entry.getKey();
o = entry.getValue();
System.out.println(n + " appeared " + o
+ (o > 1 ? " times" : " time") + " in the List.");
}
System.out.println();
System.out.println("Process Completed.");
// DONE
If you run this code, your Console Window should display something like this:
Name #1 Bill
Name #2 Jane
Name #3 Marie
Name #4 Tracey
Name #5 Fred
Name #6 Bill
Name #7 Marie
Name #8 Doug
Name #9 Marie
Name #10 Tracey
Marie appeared 3 times in the List.
Bill appeared 2 times in the List.
Fred appeared 1 time in the List.
Jane appeared 1 time in the List.
Doug appeared 1 time in the List.
Tracey appeared 2 times in the List.
Process Completed.
EDIT: Based on comments!
Now that you have provided more info, here is one way it can be achieved. Again, read the comments in code:
public class Chapter4Act_Array {
public static void main(String[] args) {
String arrayOfNames[] = new String[10];
for (int i = 0; i < arrayOfNames.length; i++) {
// Letter case will be ignored during the occurrences processing.
arrayOfNames[i] = JOptionPane.showInputDialog(null, "Please Enter name #" + (i + 1) + ":", "Name",JOptionPane.QUESTION_MESSAGE);
}
System.out.println("Your friends are: ");
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.println(arrayOfNames[i]);
}
System.out.println();
/* List to keep track of the names we've already processed.
This will help to prevent printing the same Name more
than once. */
java.util.List<String> namesAlreadyProcessed = new java.util.ArrayList<>();
int counter;
for (int i = 0; i < arrayOfNames.length; i++) {
counter = 1;
for (int j = 0; j < arrayOfNames.length; j++) {
if (j == i) { continue; } // If we fall onto the same index then skip past it.
if (arrayOfNames[i].equalsIgnoreCase(arrayOfNames[j])) {
counter++;
}
}
/* If counter is greater than 1 then there has been
a name we've encountered more than once. Let's
display the number of times it was encountered
and add that name to namesAlreadyProcessed List. */
if (counter > 1) {
// Have we already processed this name?
boolean processed = false;
for (String name : namesAlreadyProcessed) {
if (name.equalsIgnoreCase(arrayOfNames[i])) {
// Yes, so skip printing the result again for this name.
processed = true;
break;
}
}
/* If No, then let's print the name and count result to
Console Window and add the name to our List. */
if (!processed) {
System.out.println(arrayOfNames[i] + " is in the List " + counter + " times.");
namesAlreadyProcessed.add(arrayOfNames[i]);
}
}
}
}
}

JavaFx CheckTreeView how to check which item is unchecked?

I am using ControlsFX for CheckTreeView. I have lots of elements in CheckTreeView and i dont want to traverse through all the elements in this tree ( because it takes lots of time due to number of elements in the tree). Is there a method like checkTreeView.getLastUncheckedItem(); to get the last unchecked one.
Currently I am checking the number of elements that checked and comparing it with counter.
If (CountPrev > Count){
//Something Unchecked Do Stuff
}
But again, i cant find what is unchecked without traverse through all elements.
EDIT:
When user checks an item on CheckTreeView, I get that item by
String lastCheckedItem = checkTreeView.getCheckModel().
getCheckedItems().get(treeView.getCheckModel().getCheckedItems().size()-1).toString();
Now I need something like this for the unchecked item
Take a ArrayList 'allItem' and Store all TreeItems, then
after Store selected item in ObservableList 'Selecteditems' using
getCheckedItems() method, Now remove selected item in ArrayList like
below code:
Here allTreeItems is a CheckBoxTreeItem
List<String> allItem = new ArrayList<>();
for (int j = 0; j < allTreeItems.getValue().length(); j++) {
allItem.add(allTreeItems.getChildren().get(j).getValue());
}
if (CountPrev > Count) {
ObservableList<TreeItem<String>> Selecteditems = checkTreeView.getCheckModel().getCheckedItems();
allItem.remove(Selecteditems);
System.out.println("UnChecked Item :" + allItem);
for (int k = 0; k < allItem.size(); k++) {
System.out.println(allItem.get(k));
}
}
Guys thank you so much for your help!
I've accepted Calips' answer because of time and effort he gave for my question.
This is what I've been looking for:
checkTreeView.getCheckModel().getCheckedItems().addListener(new ListChangeListener<TreeItem<String>>() {
#Override public void onChanged(ListChangeListener.Change<? extends TreeItem<String>> change) {
updateText(checkedItemsLabel, change.getList());
while (change.next()) {
System.out.println("============================================");
System.out.println("Change: " + change);
System.out.println("Added sublist " + change.getAddedSubList());
System.out.println("Removed sublist " + change.getRemoved());
System.out.println("List " + change.getList());
System.out.println("Added " + change.wasAdded() + " Permutated " + change.wasPermutated() + " Removed " + change.wasRemoved() + " Replaced "
+ change.wasReplaced() + " Updated " + change.wasUpdated());
System.out.println("============================================");
}
}
});
Resource:
https://github.com/jinghai/controlsfx/blob/master/controlsfx-samples/src/main/java/org/controlsfx/samples/checked/HelloCheckTreeView.java
Stack<YourClassOfTheCheckModel> recentlyUnchcked = new Stack<YourClassOfTheCheckModel>();
yourTreeView.getSelectionModel().
selectedItemProperty().addListener( new ChangeListener() {
#Override
public void changed(ObservableValue observable, Object oldValue,
Object newValue) {
TreeItem<YourClassOfTheCheckModel> selectedItem =
(TreeItem<YourClassOfTheCheckModel>) newValue;
CheckModel checkModel = checkTreeView.getCheckModel().
bool checked = checkModel.isChecked (selectedItem);
if(checked==false){
recentlyUnchcked.push(yourObjectOfTheCheckModel);
}
}
});
Hope this will help or give you an idea though i don't know if this will work (code not tested, have no IDE right now).

scroll view in relation to tts android

how can i scroll a view (recyclerview) in relation to my tts,
ive looked at onUtterance but it seems to only have a start and stop listener, so i need to think outside the box, i give my tts a string from an Arraylist like this
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++)
{
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
speakWords(words);
I was thinking about cutting the string up into sections and giving it to the TTS one string at a time and move the view as I go. I already give my gridlayout manager an int for the amount of columns (called columns).
The array list adds a comma after every word, so I was thinking something like
find the nth/(column) comma
split the string
check if tts is speaking and listen for onUtterance onDone to pass new string
read the string
move the view
and keep doing this until theres no words left and coding for the remainder % im not sure how to do all of that so if anyone wants to help feel free, (I think Im looking at StringUtils and creating each smaller string with a for loop and passing them to the tts in onUtteranceListener onDone, but im still a little new to android), but mainly does anyone have a better way
okay this is what i have so far but it could probably use some work im still an amateur, I've split the string into blocks based on the size of the screen, and the handler that scrolls the screen relies on the amount of letters in each broken up string, also the smoothscrolltoposition is scrolling a custom layout manager that scrolls pretty slowly im having an issue though where on some devices the array list counting the words will only reach 20 not sure why but ill ask and hopefully update this when ive fixed it so here is my speak and move method
public void speakAndMove(){
final ArrayList<String> list = new ArrayList<>();
SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(0);
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++) {
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
Integer numOfWords = list.size();
words = list.toString();
Integer count = 0;
Integer startPoint = 0;
scrollPos = 0;
final Integer speed = words.length() * 15;
Integer leftOver = 0;
final int columns = getResources().getInteger(R.integer.grid_columns);
System.out.println(numOfWords);
ArrayList<String> arrayList = new ArrayList<>();
if (list.size() <= columns) {
if (words.contains("[]")) {
speakWords("");
} else if (words.contains(", 's")) {
formatString = words.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (words.contains(", ing")) {
formatString = words.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(words);
}
}
if (list.size()>=columns) {
for (int i = 0; i < words.length(); i++) {
if (words.charAt(i) == ',') {
count++;
if (count == columns) {
String ab = words.substring(startPoint, i + 1);
//speakWords(ab);
if (ab.contains(", 's")) {
formatString = ab.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab.contains(", ing")) {
formatString = ab.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab);
}
startPoint = i + 1;
count = 0;
leftOver = words.length() - startPoint;
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("main string"+" scroll " + scrollPos + " startpoint " + startPoint +" speed " + speed);
}
}
if (leftOver > 0) {
String ab2 = words.substring(startPoint, words.length());
//speakWords(ab2);
if (ab2.contains(", 's")) {
formatString = ab2.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab2.contains(", ing")) {
formatString = ab2.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab2);
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("leftovers "+ leftOver + " scroll " + scrollPos + " startpoint " + startPoint +" count " + scrollPos);
count = 0;
//scrollPos = 0;
}
}
final Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
scrollPos = scrollPos + columns;
SpeakGrid.recyclerView.getLayoutManager().smoothScrollToPosition(SpeakGrid.recyclerView, null ,scrollPos);
System.out.println("position "+ scrollPos + " speed " + speed + " list size " + list.size());
if (scrollPos < list.size())
h.postDelayed(this,speed);
// close this activity
}
}, speed);
}

Adding a variable element to an array in java

String plants [] = {"Sunflower", "Pea Shooter", "Cherry Bomb", "Wall-Nut", "Potato Mine", "Snow Pea", "Chomper "};
int sunlight [] = {50, 100, 150, 50, 25, 175, 150};
for (int i = 0; i < plants.length; i++) {
System.out.println ((i+1) + "\t" + plants [i] + "\t" + sunlight [i]);
}
This prints out the array regularly, and this part works.
String addplant = IBIO.inputString ("\nWhich plant do you add? ");
int addsl = IBIO.inputInt ("How much sunlight do you add to that plant? ");
plants [] = {"Sunflower", "Pea Shooter", "Cherry Bomb", "Wall-Nut", "Potato Mine", "Snow Pea", "Chomper ", addplant};
sunlight [] = {50, 100, 150, 50, 25, 175, 150, addsl};
for (int i = 0; i < plants.length; i++) {
System.out.println ((i+1) + "\t" + plants [i] + "\t" + sunlight [i]); }
Similarly, I want a new array to be printed out based on the value the user inputs. The new element should appear at the end of the array.
I must get input using IBIO.input. It stores the user input into a variable.
However, what I tried does not work. Instead, it just says "VariableDeclaratorId expected after this token" and highlights the new array I made.
I am wondering how I would add a variable element to my array, and am unsure of how to do this. I tried googling many things but nothing seemed to have worked.
Arrays have a constant size, you can't resize them. Probably what you want is an ArrayList. Also you didn't ask but I noticed you have two arrays of related data correlated by index, this can get messy. Since plants are likely to have more than two kinds attributes I suggest using a class like this:
private class Plant {
String plant;
int sunlight;
public Plant(String plant, int sunlight) {
this.plant = plant;
this.sunlight = sunlight;
}
}
public void someMethod() {
ArrayList<Plant> plants = new ArrayList<Plant>();
plants.add( new Plant("Sunflower", 50));
plants.add( new Plant("Pea Shooter", 100));
...
for (int i = 0; i < plants.size(); i++) {
System.out.println((i + 1) + "\t" + plants.get(i).plant + "\t" + plants.get(i).sunlight);
}
}
Then if you delete Pea Shooters, you won't have the chance to forget deleting the sunlight element for Pea Shooters. Plus it's nice and clean if you decide to something like this:
private class Plant {
String plant;
int sunlight;
float soilPh;
public Plant(String plant, int sunlight, float soilPh) {
this.plant = plant;
this.sunlight = sunlight;
this.soilPh = soilPh;
}
}
public void someMethod() {
ArrayList<Plant> plants = new ArrayList<Plant>();
plants.add( new Plant("Sunflower", 50, 6.5f));
plants.add( new Plant("Pea Shooter", 100, 7f));
...
for (int i = 0; i < plants.size(); i++) {
System.out.println((i + 1) + "\t" + plants.get(i).plant + "\t" + plants.get(i).sunlight + "\t" + plants.get(i).soilPh);
}
}
Edit you need to import:
import java.util.ArrayList;
The better and the more "Java" way is to use List, because it has a better structure for manipulation of its items.
ArrayList<String> plants = new ArrayList<>(Arrays.asList("Sunflower", "Pea Shooter", "Cherry Bomb", "Wall-Nut", "Potato Mine", "Snow Pea", "Chomper"));
ArrayList<Integer> sunlight = new ArrayList<>(Arrays.asList(50, 100, 150, 50, 25, 175, 150));
Then you just add an item to the List with the method add() to the end.
plants.add(addplant);
sunlight.add(addsl);
Getting the wanted item works similar like with arrays. Use the get(index) method. The following method assume your lists of the same size.
for (int i=0; i<plants.size(); i++) {
System.out.println((i+1) + "\t" + plants.get(i) + "\t" + sunlight.get(i));
}
In the other case you would change the condition in your for-cycle to Math.min(plants.size(), sunlight.size()).
Also the usage of Map would be a good idea.
Map<String, Integer> myMap = new HashMap<>();
Adding items with the method put(...).
Arrays cannot be added to. You probably know this since you are reassigning the value of the array, putting in all the old elements plus the new one. This will cause problems because you've hard-coded it and the next time an item is added it will not contain any previously added new elements.
The best thing to do is to use a map, to store the plant and the amount of sunlight, like this:
Map<String, Integer> plantsAndSunlight = new HashMap<String, Integer>();
plantsAndSunlight.put("Sunflower", 50);
plantsAndSunlight.put("Peashooter", 100);
:
:
Then to add a new elements just add it to the end using the put function from above, passing in the elements you got from user inout:
String addplant = IBIO.inputString ("\nWhich plant do you add? ");
int addsl = IBIO.inputInt ("How much sunlight do you add to that plant? ");
plantsAndSunlight.put(addplant, addsl);

Create JLabel Array

I have 34 labels with images i can't figure how do i make when ill click the label itself to get selected and in the down right corner that "Selected: " to get changed on every label select.
The labels variable names are from n1 to n34 i have this code so far but in the list getSelectedNumbers()
List<JLabel> lotteryBoxes = new ArrayList<>();
List<JLabel> getSelectedNumbers() {
List<JLabel> numbers = new ArrayList<>();
Iterator<JLabel> it = lotteryBoxes.iterator();
while (it.hasNext()) {
JLabel nr = it.next();
if (nr.isCursorSet()) {
numbers.add(nr);
Selected.setText("Selected: " + nr);
}
return numbers;
}
I do not know what to do, please give me some answers.
If you create the labels in a loop, you can add a handler to them. Either the same handler that checks which of the labels was clicked, or a separate handler for each one.
Here there is a separate handler for each and the labels are put into an array so you can use them later (outside the loop).
int numberOfLabels = 34;
JLabel[] labels = new JLabel[numberOfLabels];
for (int index=0; index<numberOfLabels; index++) {
String labelText = "" + (index + 1);
final JLabel label = new JLabel(labelText));
final int labelNumber = index + 1;
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// do something, you can use "label" in here, eg:
selected.setText(label.getText());
// you have access to the number in "labelNumber"
}
});
somePanel.add(label);
labels[index] = label; // save the label if you need to access it later
}

Categories