English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

In the code written here:
http://en.wikibooks.org/wiki/Java:Swing
how can I call a function when there is a mouse press/release for a button

2006-06-05 14:25:54 · 2 answers · asked by TurkishGamer13 3 in Computers & Internet Programming & Design

2 answers

The code on wikibooks actually calls System.exit(0) when the exit button is pressed.
The code segment is below

//Creates a button on the calculator that can be used to close the program
JButton buttonExit = new JButton("Exit");
//Creates a keyboard shortcut of Alt+C to use to close the program //instead of having to click on the button
buttonExit.setMnemonic(KeyEvent.VK_C);
buttonExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//adds the Exit button
panel.add(buttonExit);

There are two ways of doing what you would like.
Firstly, you could copy the 'buttonExit.addActionListener(..); part to every other button and make the function actionPerformed in the new ActionListener do what you would like. For instance, you could get it to write to the console with a line like
System.out.println("You pressed the button xx");
depending on which button was pressed.

Secondly, you could create a seperate ActionListener and implement in the actionPerformed method checks to see which button was pressed. Note, this would need to be a seperate class. For instance
class FullActionListener // the action listener for all buttons
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("9")) {
// do whatever you need to here for the button 9.
System.out.println("You pressed button 9");
} else if (command.equals("8")) {
// etc
}
}

Then,
ActionListener al = new FullActionListener();
// the code on wikibooks
//creates all of the numbers that would be seen on a calculator
JButton button1 = new JButton("1");
button1.addActionListener(al);
panel.add(button1);
JButton button2 = new JButton("2");
button2.addActionListener(al);
panel.add(button2);
etc...

2006-06-05 15:20:52 · answer #1 · answered by Mark aka jack573 7 · 1 0

I've never tried this before, so this is mostly a guess:

You need an actionPerformed method that looks something like this:

puclic void actionPerformed(MouseEvent me) {
if(me.getModifiers()) == me.MOUSE_RELEASED)
functionToCallWhenMouseRelease();
}

I have no idea if this code actually works, so take it with a grain of salt.

2006-06-05 14:39:48 · answer #2 · answered by Anonymous · 0 0

fedest.com, questions and answers