tags:

views:

96

answers:

5
+1  Q: 

Java Swing event

Hello, I wonder how one should implement an event which will do some Action when a button is pressed, and stop do that action when button is released

I tried to add MouseListerner for this approach. The problem is it will recognize that I have pressed the button. But not which button it is. So wonder how should it be written so it will know which button I have pressed down.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;


public class Main extends JFrame implements MouseListener, ActionListener{

    private JPanel panel1 = new JPanel();
    private JPanel panel2 = new JPanel(new GridLayout(4,4));



    public Main() {
        setSize(300,400);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setLayout(new BorderLayout());
        add(panel1, BorderLayout.NORTH);
        add(panel2, BorderLayout.CENTER);

        String[] buttonNamn = {"1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};

        for(int i=0;i<buttonNamn.length;i++) {
            JButton button = new JButton(buttonNamn[i]);
            panel2.add(button);
            button.addMouseListener(this);
            button.addActionListener(this);
        }

    }
    public static void createGUI() {
        new Main();
    }

    public static void main(String[] args) {

         createGUI();
    }
    @Override
    public void mouseClicked(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void mousePressed(MouseEvent arg0) {
        System.out.println("Pressed");

    }
    @Override
    public void mouseReleased(MouseEvent arg0) {
        System.out.println("Relased");


    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("1")) {
            System.out.println("Foo 1");
        }
        else if(e.getActionCommand().equals("2")){
            System.out.println("Foo 2");
        }
    }
}
A: 

The getSource method of MouseEvent inherited from EventObject should give you a reference to the clicked button java api link

Guy
ah, so there was a getSource. hmm but the action is however invoked one time. Would the approach be loop the action until the mouse button is released?
starcorn
A: 

Use MouseEvent.getButton() to get the button that triggered the event.

PartlyCloudy
getButton returns the mouse button which was clicked
Guy
According to the API: Returns which, if any, of the mouse buttons has changed state. http://java.sun.com/javase/6/docs/api/java/awt/event/MouseEvent.html#getButton%28%29
PartlyCloudy
@Guy: I do agree with your assumption that the OP wants to get the `JButton` that has been pressed instead of the mouse-button, but as it is not absolutely clear, adding your comment and **not** downvoting would have been sufficient in my opinion.
Peter Lang
what I want is which button that is pressed. In that which JButton and not which mouse button.
starcorn
Thanks Peter and klw for clarifying, as opposed to Guy who only managed to vote me down. Thus my answer is wrong, because I misunderstood the "button" you are talking about, sorry.
PartlyCloudy
+1 because that was the way I understood it too.
Pool
@Peter After my initial reading I thought it was obvious that he meant which JButton, but I re-read the question and you are right its not clear from it which button OP is referring to, so yes downvoting was probably unnecessary (undone).
Guy
+1  A: 

You will need invokeLater as described here: http://stackoverflow.com/questions/2034321/java-mytextarea-settexthello-thread-sleep1000-strange-result/2034349#2034349 otherwise your action will block the UI-thread

stacker
+1  A: 

For the start look at SwingUtilities.invokeLater.

For the cancel, I generally use an interface with a cancel operation on it which the Runnable provided to the invokeLater implements, the cancel button then kicks off the cancel simply by calling the cancel operation. How this cancels teh operation depends on what it does, maybe it could set a cancelled flag which the running operation can periodically check to see if it should continue.

vickirk
+1  A: 

Note that you can extend listener implementation classes like MouseAdapter to save yourself some typing (only override the methods you want to use).

Rather than use a single listener and have a bunch of case statements to try and figure out the relationship between the button and the data, add a new listener to each button and hold the data in the listener. This code does this with an anonymous class.

  public static void main(String[] args) {
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(4, 4));
    String[] buttonName = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
        "B", "C", "D", "E", "F" };
    for (final String name : buttonName) {
      JButton button = new JButton(name);
      panel.add(button);
      button.addMouseListener(new MouseAdapter() {
        @Override public void mousePressed(MouseEvent e) {
          System.out.println("pressed:" + name);
        }

        @Override public void mouseReleased(MouseEvent e) {
          System.out.println("released:" + name);
        }
      });
    }
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(panel);
    frame.pack();
    frame.setVisible(true);
  }

Note the use of the final keyword.

There are other ways to express this, if you prefer. This method adds a static inner class:

  private static class MyListener extends MouseAdapter {
    private final String name;

    public MyListener(String name) {
      this.name = name;
    }

    @Override public void mousePressed(MouseEvent e) {
      System.out.println("pressed:" + name);
    }

    @Override public void mouseReleased(MouseEvent e) {
      System.out.println("released:" + name);
    }
  }

  public void addStaticInnerClassListener(JButton button, String name) {
    button.addMouseListener(new MyListener(name));
  }

This one uses a class scoped to the method:

  public void addNameListener(JButton button, final String name) {
    class MyListener extends MouseAdapter {
      @Override public void mousePressed(MouseEvent e) {
        System.out.println("pressed:" + name);
      }

      @Override public void mouseReleased(MouseEvent e) {
        System.out.println("released:" + name);
      }
    }
    button.addMouseListener(new MyListener());
  }

The code/action you want performed will have to be performed in another thread. Swing provides some utility classes for this, such as SwingWorker.

McDowell