Calling multiple objects with a method in Java - java

I'm trying to create a calendar using Java GUI and I want to create a method to create the cells of each date. Is there any way to create a method to create a bunch of JTextAreas without manually creating each individual cell?
Creating a cell one by one I do:
public void createCell() {
cell1 = new JTextArea(CELL_DIMENSIONS, CELL_DIMENSIONS);
}

You have many ways of doing that one possibility would be to create a List inside the method with the assistance of a for loop and make the method return it for you to use somewhere else.
public List<JTextArea> createMultipleCells(int numOfCells) {
List<JTextArea> cells = new LinkedList<JTextArea>();
for(int i = 0; i < numOfCells; i++){
cells.add(new JTextArea(CELL_DIMENSIONS, CELL_DIMENSIONS));
}
return cells;
}
Same thing with an array:
public JTextArea[] createMultipleCells(int numOfCells) {
JTextArea[] cells = new JTextArea[numOfCells];
for(int i = 0; i < numOfCells; i++){
cells[i] = new JTextArea(CELL_DIMENSIONS, CELL_DIMENSIONS);
}
return cells;
}

Related

can variable have multiple enum constants in java?

I am building simple java game which the user has to find gold. There are some obstacles like Orc, Goblin, and Poop.
What I am trying to do is that I am creating Cell and Board class.
Inside of my Cell class,
public Cell{
public enum TheCell { Orc, Goblin, Poop, Gold, Empty};
TheCell type;
public Cell(TheCell type){
this.type = type;
}
}
and I make two dimensions in Board class,
public Board{
Cell[][] grid = new Cell[7][7];
Random r = new Random();
for(int i = 0; i<3; i++){
int randNum1 = r.nextInt(7);
int randNum2 = r.nextInt(7);
grid[randNum1][randNum2] = new Cell(Cell.TheCell.Orc);
}
for(int i = 0; i<3; i++){
int randNum1 = r.nextInt(7);
int randNum2 = r.nextInt(7);
grid[randNum1][randNum2] = new Cell(Cell.TheCell.Goblin);
}
}
My question is that, in case of Orc and Goblin are same cell, I wanna keep them both monster in same cell. Is there some how I can keep both or multiple obstacles in same cell? Thank you!
One way to achieve this is to have the Cell class hold a list of all monsters/things that are currently on the cell (using the enum, that is already available)
A more "low level" approach is to use an Integer for the cell and then use bitflags to model multiple obstacles on the same cell.
Update:
I agree with #ajb, in this case an Enum Set should be used
As pointed out by #JimGarrison, the EnumSet approach only works until you need to have more than one instance of an enum value for one cell.
public Cell{
public enum TheCell { Orc, Goblin, Poop, Gold, Empty};
List<TheCell> type = new ArrayList<TheCell>();
public Cell(TheCell type){
addType(type);
}
public addType(TheCell type) {
this.type.add(type);
}
}

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

Clearing a dropdown counter in 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.

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

2d Array not deep cloning, changes affect both arrays

I need to clone a 2d array of Cell objects but it doesn't work as it should. Whenever i clone the maze, it clones it but when i make changes to one, it is also visible on the other
somebody knows what the problem is???
public void cloneMaze(boolean backup)
{
if (backup) {
backupMaze = (Cell[][]) maze.clone();
for (int i = 0; i < maze.length; i++) {
backupMaze[i] = (Cell[]) maze[i].clone();
}
} else {
maze = (Cell[][]) backupMaze.clone();
for (int i = 0; i < backupMaze.length; i++) {
maze[i] = (Cell[]) backupMaze[i].clone();
}
}
}
In your backup maze, you need to create new Cell that are a copy of the first ones
Otherwise both your mazes point to the same objects, thus modification to the cells are reflected in both mazes.
clone() is just a shallow copy of your array, while you seem to look for deep copy.

Categories