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