1
我使用java編寫了一個程序,並使用了幾個在我的程序中執行操作的組件(actionListener)。 我想知道此組件何時發生任何操作。例如,當我點擊按鈕或菜單項時,調用一個方法。如何知道何時在我的程序中發生了某個操作
public class ButtonFrame extends JFrame
{
private JButton plainJButton; // button with just text
private JButton fancyJButton; // button with icons
public ButtonFrame()
{
super("Testing Buttons");
setLayout(new FlowLayout()); // set frame layout
plainJButton = new JButton("Plain Button");
add(plainJButton);
fancyJButton = new JButton("Fancy Button");
add(fancyJButton);
// create new ButtonHandler for button event handling
ButtonHandler handler = new ButtonHandler();
fancyJButton.addActionListener(handler);
plainJButton.addActionListener(handler);
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JOptionPane.showMessageDialog(ButtonFrame.this, String.format(
"You pressed: %s", event.getActionCommand()));
}
}
}