0

What should I do if I want to perform an ActionListener on a button again and again, so that it will not give me the same ans again...

For example:

down = new JButton("DOWN-1");
down.setSize(down.getPreferredSize());
down.setLocation(100,200);
down.addActionListener(this);
left=new JButton("LEFT-1");
left.setSize(left.getPreferredSize());
left.setLocation(100,250);
left.addActionListener(this);
right=new JButton("RIGHT-1");
right.setSize(right.getPreferredSize());
right.setLocation(100,300);
right.addActionListener(this);
up1=new JButton("UP-2");
up1.setSize(up1.getPreferredSize());
up1.setLocation(550,150);
up.addActionListener(this);

@Override
public void actionPerformed(ActionEvent a)
{
    int counter=370;

    if (a.getSource()==up) {
        System.out.println(counter);

        x=250+62+62;
        y=60+62+62+62+62+62;
        b1.setLocation(x,counter-62);
        l19.setLocation(x,counter);
    }   
}

In this I want to use up button again and again but it is not working...

Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96

1 Answers1

0

While your question is Sooo very confusing. I think I have been able to extract up some meaning to it. "...if I want to perform an ActionListener on a button again and again,...". My guess is that you mean you want to be able to use the button more than once.

This is what I'm seeing in your code that would make you think you're not able to use it more than once.

@Override
public void actionPerformed(ActionEvent a)
{
    int counter=370;

    if (a.getSource()==up) {
        System.out.println(counter);

        x=250+62+62;
        y=60+62+62+62+62+62;
        b1.setLocation(x,counter-62);
        l19.setLocation(x,counter);
    }   
}

What's happening is that ever click of the button, the location is always set to the same place. The initial location my be different, that's why it appears to be working on the first click (the location will change). But after that, every click leads to the same location, so whatever you expect to move, doesn't.

Though I have no idea what your code does, from your minimal "explanation" (if you can even call it that). I can give a suggestion. It seem that counter is the offsetting factor, so what you may want to do is give the counter a global scope and change its value every time the button is clicked. Something like this

int counter = 370;

@Override
public void actionPerformed(ActionEvent a)
{
    if (a.getSource()==up) {
        counter -= 62;         // this is where you change the value of counter

        System.out.println(counter);

        x=250+62+62;           // I have no idea what this is for
        y=60+62+62+62+62+62;   // or this, so I won't comment
        b1.setLocation(x,counter);   // just use the new counter value
        l19.setLocation(x,counter);
    }   
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720