This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
i have a problem with ArrayLists in Java.
The problem is that when i add an element to the list (pointStorer), the index doesn't increment and every time it resets and remains zero.
Here's my code (well it's only the important part of the code):
private ArrayList pointStorer = new ArrayList();
private Point pointValues = new Point();
public void mouseClicked(MouseEvent e) {
pointValues.setLocation(e.getX(), e.getY());
mousePointX = pointValues.x;
mousePointY = pointValues.y;
repaint();
}
public void paint(Graphics g){
pointStorer.add(pointValues);
System.out.println("Index point "+pointStorer.indexOf(pointValues));
}
I use the method .indexOf to know what's the index of the element that i've just added, but it remains always zero.
Thank you in advance for your help.
You only have one Point instance which you keep adding to the ArrayList, so all the indices of the ArrayList contain the same Point.
To add a new Point each time the mouse is clicked, you should create a new Point instance :
public void mouseClicked(MouseEvent e) {
Point pointValues = new Point();
pointValues.setLocation(e.getX(), e.getY());
mousePointX = pointValues.x;
mousePointY = pointValues.y;
repaint();
}
You should instantiate your pointStorer variable inside your paint() method
Related
This question already has answers here:
Ball to Ball Collision - Detection and Handling
(15 answers)
Closed last year.
I'm creating a shooter game and im unsure on how to make it detect the fact that the bullet has hit the enemy. This is the boolean that was given
boolean isShot(Bullet bullet) //is shot sequence
{
if (bullet!=null)
{
if (abs(this.x - bullet.x) < 20 &&
abs(this.y - bullet.y) < 20)
return true;
}
return false;
}
and this is the part where i try make it detect the collision and make the enemy disappear but it keeps giving me errors no matter what i try.
import java.util.ArrayList;
int score;
Player p1;
Enemy[] e= new Enemy[4];
ArrayList<Bullet> bullet = new ArrayList<Bullet>();
void setup()
{
size (1000, 1000);
p1= new Player(500,5, 40);
e[1]= new Enemy(100,1000,3);
e[2]= new Enemy(500,800,3);
e[3]= new Enemy(700,700,3);
// b1= new Bullet(500,500,-5);
}
void draw()
{
background(255);
p1.render();
e[1].render();
e[1].move();
e[2].render();
e[2].move();
e[3].render();
e[3].move();
text("Score:" + score,50,50);
for (Bullet b: bullet)
{
b.render();
b.move();
}
if (e[1].isShot(Bullet))
{
e[1]=null;
}
Its at the bottom of this peice of code. When i try put bullet in lowercase it says "the function isShot() expects paramaters like "isShot(Bullet)" but when i capitalise the B in bullet it tells me that bullet isnt a variable.
"bullet" with lowercase b is an array of Bullets, but isShot() expects a single Bullet object. And "Bullet" with capital B is not a variable, but a class (I suppose).
So, you either need to create another object of Bullet or use one of the Bullet object in your "bullet" ArrayList.
You are almost there.
I suggest you use more meaningful names for your parameters.
First of all, you have to populate the ArrayList bullet in your setup() or elsewhere you want in your code.
After this, if you want to check that condition using isShot function you should pass to it an instance of an Object, not the class Object itself.
This can be easily achieved by including the function in your for loop.
While it is always good to practice, I suggest you to first understand the basics of the language and then move to more complex examples (custom classes, arrays iterations and so on).
void setup()
{
size (1000, 1000);
p1= new Player(500,5, 40);
e[1]= new Enemy(100,1000,3);
e[2]= new Enemy(500,800,3);
e[3]= new Enemy(700,700,3);
bullet.add(new Bullet(500,500,-5)); // e.g. to populate array
}
void draw()
{
background(255);
p1.render();
e[1].render();
e[1].move();
e[2].render();
e[2].move();
e[3].render();
e[3].move();
text("Score:" + score,50,50);
for (Bullet b: bullet)
{
b.render();
b.move();
if (e[1].isShot(b)) // now you can use b which is an instance of Bullet
{
e[1]=null;
}
}
I want to enter the X and Y coordinates of mouse adapter to array . But whenever I insert them into array using for loop, the whole array is getting filled with same value. How can I insert X and Y coordinates to the array every time the JPanel is clicked?
Code:
addMouseListener(new MouseAdapter () {
public void mouseClicked(MouseEvent e) {
setBackground(Color.RED);
int k[]=new int[18];
int l[]=new int[18];
for(int i=0;i<=17;i++) {
k[i]=e.getX();
l[i]=e.getY();
}
}
});
It's not clear from the OP where the data is meant to be going. Assuming it's being used elsewhere then -
// NOTE: perhaps use CopyOnWriteArrayList or synchronize all
// use of clicks for MT safety..
final List<Point> clicks = new ArrayList<Point>();
X.addMouseListener(new MouseAdapter () {
public void mouseClicked(MouseEvent e) {
setBackground(Color.RED);
clicks.add(e.getPoint());
}
});
Each time the mouse is clicked another point is added to the clicks array.
HT to #AndrewThompson
This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 6 years ago.
I am doing some kind of arkanoid, and I got stuck. The way I do it is through JFrame, JPanel and with Timer. So what I do each timer update is
this
public class Controller implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
ball.move();
desk.move();
deskCollision();
squareCollision();
repaint();
}
}
I created Arraylist of squares, and I printed them. When I check the collision with squares and ball, it works. So now I want to remove a specific square, when a ball hits it and change direction of a ball. Firstly, I tried it without any kind of a loop, like this.
if(ListOfSquares.get(24).getBounds2D().intersects(ball.getBounds2D())){
ball.dy = 1;
ball.dx = -1;
ListOfSquares.remove(24);
}
This works as well. But as I want to make a loop which will go trough all of the squares and always remove the specific square, I am lost. I have done it like this, but
it ends up with a bug -- Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException --
for(Square square : ListOfSquares){
int index = ListOfSquares.indexOf(square);
if (ball.getBounds2D().intersects(square.getBounds2D())) {
if(ball.dx == -1 && ball.dy == -1){
ball.dy = 1;
ball.dx = -1;
ListOfSquares.remove(index);
}
//etc...
}
}
Thanks for your help.
Iterator may help you:
Iterator<String> iter = ListOfSquares.iterator();
while (iter.hasNext()) {
Square squ = iter.next();
if (someCondition)
iter.remove();
}
Refference:How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?
So I am making a java program that quizzes students on the capital of the USA states.(I am fairly new to JAVA) Okay guys so here is part of my program:
class SetUpButtonActionListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
for(int i=0; i < state.size(); i++)
{
question = (String)(state.get(i));
//i++;
countryName.setText(question);
}
}
}
The problem is when I am trying to call the ArrayList one by one in the SetUpButtonActionListener class. It runs fine, but when I click on the New Problem button its supposed to show each one state and ask the user for the capital(haven't gotten to this part yet). However, when I click the button it doesn't show up with anything. I am not really to sure what I am doing wrong. Any help would be awesome!
state is and will remain empty until you call stateName(). This explain the observed behavior.
You probably want to add a call to stateName() at the beginning of your constructor.
you should call filling method of your list in the constructor
public QuizPanel()
{
stateName()
setUpButton = new JButton("New problem!");
add(setUpButton);
setUpButton.addActionListener(new SetUpButtonActionListener());
...
}
First of all, you need to call stateName() to fill the array.
Second, this way you did, every time the button is clicked, the method actionPerformed is called, and the loop runs with all the values of the array, always finishing getting the last value.
What you need is to maintain a value pointing to the next value of the array, so this way, every time you click the button, only the next item is got.
class SetUpButtonActionListener implements ActionListener{
int currentIndex = 0;
public void actionPerformed(ActionEvent e) {
//verify if the index is inside the array (reseting it if not)
//get the value
//increase the index
}
}
I want to ask a question about arraylist. In my program I defined an arraylist and an user defined object. The problem is when I want to add an object to this arraylist, it adds object, but next time when I give the different values to user object, it sets values of the old object that I added before to the new one. I mean, for example I have 13 in my old object and the new one is 14, it makes the old one 14. I couldn't find a solution for this. I'M working on a drawing program. I'm posting some parts of the code.
public class Tester extends JPanel implements MouseMotionListener, MouseListener {
ArrayList<Lines> array = new ArrayList<Lines>();
Lines l1;
...
public Tester(){
l1 = new Lines();
l1.point1 = new Point();
l1.point2 = new Point();
l1.denklem = new int[3];
And thi is how I add object into arraylist
else if(lineci == true){
if(mouseclicks == 0){
l1.point1.x = e.getX();
l1.point1.y = e.getY();
statusBar.setText( String.format( "Clicked at [%d, %d]",
e.getX(), e.getY() ) );
mouseclicks++;
starter = false;
}
else if(mouseclicks == 1){
l1.point2.x = e.getX();
l1.point2.y = e.getY();
statusBar.setText( String.format( "Clicked at [%d, %d]",
e.getX(), e.getY() ) );
mouseclicks = 0;
int a = l1.point2.y - l1.point1.y;
int b = l1.point1.x - l1.point2.x;
int c = (l1.point2.x * l1.point1.y) - (l1.point1.x * l1.point2.y);
l1.denklem[0] = a;
l1.denklem[1] = b;
l1.denklem[2] = c;
array.add(l1);
// array3.add(l1);
repaint();
}
}
When I click mouse, if lineci is true, it draws a line according to points. I get always last lines when I print elements of arraylist. If I draw 10 lines, 10 elements of the arraylist are the same. It never keeps old values inside arraylist. By the way boolean starter is not important. I just forget to remove it.
You are simply adding the same object repeatedly to the list. Each addition to the list is merely adding a reference to the same object: l1. Hence, when you update the state of l1, the old "object" also appears to have changed.
To rectify this you need to create a new instance of Lines for each addition you wish to perform.
You're referencing the original l1 object, so it will modify the original l1 object--whether or not it's in the list.
If you want to create a new object, create a new object.
i think your l1 reference is still pointing the previous object added to the arrayList , you should override the reference as soon as you add the object to the arraylist .
by either
l1 = new Lines();
or
l1 = null;
Use l1.clone() before changing the value inside if you want to keep all values same but one and the class is clonable or create a new object which is better for your case.