Clearing a dropdown counter in Java? - java

I need to clear all the fields in several arrays to re-load a new template to parse. I currently set up a function to clear all the relevant array lists and counts. Those are working fine except I am having a hard time clearing out obrDD inside my clearMicroArray() function.
Here is my current code (without logic to clear obrDD). How can I clear the dropdown information inside my function?
static void clearMicroArray() {
fullMicroArray.clear();
int returnSize = fullMicroArray.size();
System.out.println("size of full array" + returnSize);
obrCount = 0;
fileRowCount = 0;
// obr List
obrList.removeAll(obrList);
obxList.removeAll(obxList);
};
// Populating the OBR number in dropdown
public static void populateOBRDropdown(JComboBox<String> obrDD) {
for (int i = 0; i < fullMicroArray.size(); i++) {
if (fullMicroArray.get(i).substring(0, fullMicroArray.get(i).indexOf("|")).equals("OBR")) {
i++;
obrCount++;
obrDD.addItem("OBR " + obrCount);
}
}
}

obrDD is a JComboBox object that you pass into populateOBRDropdown. Your clearMicroArray method, however, also needs obrDD as an input in order for you to do anything with it. Once you pass a reference to the JComboBox, you can call removeAllItems or removeItem from clearMicroArray.

Related

existence of an element in two List

I want to verify the existence of an element in two JTable that displays questions
The program is when I click on a question in the first list it will be transferred to the second JTable but I do not want to add duplication restrictions so I did not want an issue to be added twice in the second list I want make an added control if it will add the user can not add the second time
table = new JTable();
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
for (int i = 0; i < questions2.size(); i++) {
/* the control code */
Question selected=questions.get(table.getSelectedRow());
questions2.add(selected);
questions.remove(selected);
initDataBindings();
}
}
});
My Result
I do not want this
since you are using Jtables in the question,
you need to check if the value exists in the jtable first if the value doesnt exist then you can add it to the jtable. in the code you have submitted you are not checking if the value exists.
public boolean ifExists(JTable table,string entry) {
int rowCount = table.getRowCount();
int columnCount = table.getColumnCount();
for (int i = 0; i < rowCount; i++) {
String value = "";
for (int j = 0; j < columnCount; j++)
value = value + " " + table.getValueAt(i, j).toString();
if (value.equalsIgnoreCase(entry)) {
return true;
}
}
return false;
}
in the above code im checking the existence of the data using a for loop.
it will iterate over the jtable and return true if the value exist.
if the return value is false then you can go on and add the data. try it with the above code.
Use Set. Lets say you have a first List:
List<Question> questions1 = new ArrayList<Question>();
now, Question must have this methods:
#Override
public int hashCode() {
// Let your IDE generates it based on variables
}
#Override
public boolean equals() {
// Let your IDE generates it based on variables
}
With this method, Set will be able to figure out if two Question are equal, and create hashCode, needed for storing. Best way is if you have unique id, but other stuff can help to. If you add Question class to your Answer, I might help you decide the best implementation of equals() and hashCode() methods.
Now, you place them in HashSet, as Users does some action:
HashSet<Question> questionsSet = new HashSet<Question>();
boolean isPresentInList = questionsSet.contains(question);
questionsSet.add(question);
Method contains will check if that question is present in questionsSet. add will check if there is an equal question in it, defined by rules in equals() method, and if it is, it will override it, else it will just add. In this way, you will not have duplicates in questionsSet.
Now, when you need an arrayList from questionsSet do this:
List<Question> questions2 = Arrays.asList(questionsSet);

Method for printing Arraylist returns []

I'm trying to make a booking system for a hotel using the MVC dp. I have a class with a fixed arraylist of rooms (from 1-25) inside the model and class in which I have the showAvailableRooms method in the controller package . I'm asking my View to print out the available rooms but the only thing it prints out is two square brackets ([]).
P.S. The get OccupiedRoom is another method I have in my bookinglist class (model). It checks if the dates you pass it as arguments are a problem to already existing bookings,if it is then it checks if the room is already in that occupied list and if it isn't it adds it to the list.
public void showAvailableRooms(MyDate arrivaldate, MyDate departuredate) {
ArrayList<Room> availablerooms = new ArrayList<Room>();
for (int i = 0; i < 25; i++) {
for (int j = 0; j < l.getOccupiedRoom(arrivaldate, departuredate).size(); j++) {
if (h.getRoom(i) != l.getOccupiedRoom(arrivaldate, departuredate).get(j)) {
availablerooms.add(h.getRoom(i));
} else if (l.getOccupiedRoom(arrivaldate, departuredate).size() == 0) {
System.out.println(h.getAllRooms());
}
}
System.out.println(availablerooms);
}
As i said in comment [] means your list is empty.
you add elements to availablerooms only in your inner loop, but if l.getOccupiedRoom returns you empty list, then code inside inner loop won't be executed, and no empty rooms will be added.
two square brackets ([]). Means that availablerooms doesn't have any entry. Either there are no available rooms, or it isn't getting populated correctly. Please check your logic.

Copying Array from ArrayList Element

I'm building a Java based game in Swing, which is essentially a grid of Jbuttons
I have an Object called Cell, which is a custom JButton with additional parameters for storing objects. The game grid is represented by Cell[][]
I have an arraylist of type Cell[][] to allow me to store the state of the gamegrid after each move. If I want to undo the move, I need to copy the last element of the ArrayList to the game grid to allow it to be displayed on the UI.
My gamegrid is panelHolder and my arraylist is moveHolder.
So far I've tried Collections.copy(panelHolder, moveHolder.get(moveHolder.size())); which will not compile due to the "arguments not being applicable for the type Cell[][]"
I've also tried System.arraycopy(moveHolder.get(moveHolder.size()-1), 0, panelHolder, 0, panelHolder.length);, which throws and out of bounds exception. Initially I thought this was due to the moveHolder.size()-1, but even just as moveHolder.size() it has the same problem.
I've found numerous questions on StackOverflow and others that both show these two ways of doing it, but I can't seem to get it to work. Is there something more obvious I'm missing? Full class method below:
public class UndoClass implements MoveCommand{
public ArrayList<Cell[][]> moveHolder = new ArrayList<Cell[][]>();
public Cell[][] execute(Cell[][] panelHolder) {
if (moveHolder.size() > 0){
Collections.copy(panelHolder, moveHolder.get(moveHolder.size()));
if (moveHolder.size() > 0){
moveHolder.remove(moveHolder.size());
}
}
System.out.println("Move Undone. Undos available:" + moveHolder.size());
return panelHolder;
}
public void addMove(Cell[][] panelHolder){
moveHolder.add(panelHolder);
}
public ArrayList<Cell[][]> getMoves(){
return moveHolder;
}
}
Cell Class
public class Cell extends JButton {
int co_x = 0;
int co_y = 0;
ArrayList<Players> current = new ArrayList <Players>();
}
Just wanted to point our your execute(...) method accepts the Cell[][] both as a parameter and the return argument. That approach is going to force all of your commands to keep copying your input param arrays to the return statement array. Notice if you don't need to keep the two in sync and you just use the return arg, you don't have to worry about copying at all:
Cell[][] lastState = moveHolder.get(moveHolder.size()-1);
moveHolder.remove(moveHolder.size()-1);
return lastState; // Not updating the panelHolder array, just returning
But of course now the input parm and return are out of sync. Instead you might want to encapsulate that state into a single object to make your life easier. Something like this (note that the execute now returns a void):
public ArrayList<GameState> previousStates = new ArrayList<GameState>();
public void execute(GameState currentState) {
if (previousStates .size() > 0) {
GameState lastState = previousStates.get(previousStates.size()-1);
currentState.restoreFrom(lastState);
previousStates .remove(moveHolder.size()-1);
}
}
Good luck on the game!
if (moveHolder.size() > 0) {
for (int i = 0; i < panelHolder.length; i++) {
panelHolder[i] = moveHolder.get(moveHolder.size()-1)[i].clone();
}
moveHolder.remove(moveHolder.size()-1);
}
Try this. You need to make copies of each internal array when copying 2D arrays.
Try a Linked List
LinkedList<Cell[][]> ll = new LinkedList();
ll.removeLast();
panelHolder = ll.clone();

How can I increment a variable on button click?

I'm trying to make a small game like thing for school. It's designed to help you learn your times tables. What I want is for the multiplier of the table to be random each time (5x8 then 5x3 then 5x9 etc).
I've got the generating of the numbers in control with an array as can be seen below
public static Integer[] generateNumbers()
{
Integer[] arr = new Integer[12];
for(int j = 0; j < arr.length; j++)
{
arr[j] = j+1;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.asList(arr));
return arr;
}
How can I make it so that every time the user clicks a button, the next number in the array is selected, baring in mind that the button is declared in another class, and the ActionListener is also declared elsewhere?
Oh and the array is available class-wide as the function is declared like this:
public static Integer[] arr = generateNumbers();
Thematic answer
public class UnicornFrame extends JFrame {
private Integer[] poneyArr = MyClassThatGeneratesNumbers.generateNumbers();
private int poneyCounter = 0;
private JButton poneyButton;
public void poneyInit() {
System.out.println("Unicorns are poney magical friends!");
poneyButton = new JButton("OMG! Ponies!");
// Java 8 Lambdas! Yey!
poneyButton.addActionListener(e -> {
if (poneyCounter >= poneyArr.length) {
poneyArray = MyClassThatGeneratesNumbers.generateNumbers();
poneyCounter = 0;
}
Integer selected = poneyArr[poneyCounter++];
System.out.println("OMG! I have selected " + selected);
});
// other stuff
add(poneyButton, BorderLayout.CENTER);
}
}
The button int he separate class is not needed, the action listener will communicate with your array whenever its clicked, the easiest way I see is to put a public method int the array's class, that takes an index, which then increments the index, and returns the element stored at it.
Have fun coding, but these assignments are meant for you to scratch your head, try writing some code, and let us know if it breaks, rather than asking for general answers.

Having trouble with the arraylist get method

Basically, I have an ArrayList of BudgetItem objects (BudgetItem being a class I made). Each BudgetItem has three instance variables, price, name, and quantity with setters and getters for each. I am adding each BudgetItem to the ArrayList one at a time, each with different information in the price variable. When I go to print out any price element of the ArrayList, using the get method, the console will always print the last price that was entered. Below, I will paste some sample code to help:
public class Register {
private ArrayList<BudgetItem> register = new ArrayList<BudgetItem>();
public Register(double[] price) {
//Creates a register ArrayList with specified number of
//elements and populates it with BudgetItems that contain
//the data in the price array entered in the declaration.
BudgetItem bi = new BudgetItem();
for(int i = 0; i<price.length; i++) {
bi.setPrice(price[i]);
register.add(bi);
if(i=0) { //This if statement is for debugging.
System.out.println(register.get(i).getPrice());
}
}
//This is also for debugging.
double i = register.get(0).getPrice();
System.out.println(i);
}
}
Through my debugging efforts I found that the problem is with the get method in ArrayList. No matter what I do it returns the last instance of price that was entered. My question is why won't the get method return the specified element?
Well the problem is that you always modify the same BudgetItem object.
Try :
for(int i = 0; i<price.length; i++) {
BudgetItem bi = new BudgetItem(); <-- move it inside the for loop
bi.setPrice(price[i]);
register.add(bi);
}
You are only adding a single BudgetItem and setting and resetting its price. You need to add new BudgetItems and set their prices accordingly.
Add BudgetItem bi = new BudgetItem(); inside for loop

Categories