Question: (about JAVA)A small question on this small piece of code...? In the code written here:\nhttp://en.wikibooks.org/wiki/Java:Swing\nhow can I call a function when there is a mouse press/release for a button

Answer: The code on wikibooks actually calls System.exit(0) when the exit button is pressed.\nThe code segment is below\n\n        //Creates a button on the calculator that can be used to close the program\n        JButton buttonExit = new JButton("Exit");\n//Creates a keyboard shortcut of Alt+C to use to close the program //instead of having to click on the button\n        buttonExit.setMnemonic(KeyEvent.VK_C);\n        buttonExit.addActionListener(new ActionListener() {\n                public void actionPerformed(ActionEvent e) {\n                System.exit(0); \n                }\n        });\n        //adds the Exit button\n        panel.add(buttonExit);\n\nThere are two ways of doing what you would like.\nFirstly, 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\nSystem.out.println("You pressed the button xx");\ndepending on which button was pressed.\n\nSecondly, 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\nclass FullActionListener // the action listener for all buttons\npublic void actionPerformed(ActionEvent e) {\n    String command = e.getActionCommand();\n    if (command.equals("9")) {\n        // do whatever you need to here for the button 9.\n        System.out.println("You pressed button 9");\n    } else if (command.equals("8")) {\n        // etc\n    }\n}\n\nThen,\nActionListener al = new FullActionListener();\n// the code on wikibooks\n        //creates all of the numbers that would be seen on a calculator\n        JButton button1 = new JButton("1");\n        button1.addActionListener(al);\n        panel.add(button1);\n        JButton button2 = new JButton("2");\n        button2.addActionListener(al);\n        panel.add(button2);\n etc...
This question from the Yahoo Q&A forum is categorized in the topic: Entertainment & Music