Esempio completo con 2 pulsanti, nota le parti in rosso:
codice:import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestFrame extends JFrame implements ActionListener { private JButton pulsante1; private JButton pulsante2; public TestFrame () { super ("Esempio"); setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); setSize (300, 300); pulsante1 = new JButton ("Pulsante 1"); pulsante2 = new JButton ("Pulsante 2"); // Dico ai pulsanti che l'action listener e` questa classe pulsante1.addActionListener (this); pulsante2.addActionListener (this); add (pulsante1, BorderLayout.NORTH); add (pulsante2, BorderLayout.SOUTH); } // Questo metodo DEVE essere dichiarato cosi`: public void actionPerformed (ActionEvent e) { Object src = e.getSource (); if (src == pulsante1) JOptionPane.showMessageDialog (this, "Hai premuto il pulsante 1"); else if (src == pulsante2) JOptionPane.showMessageDialog (this, "Hai premuto il pulsante 2"); } public static void main (String[] args) { SwingUtilities.invokeLater (new Runnable() { public void run () { TestFrame f = new TestFrame (); f.setVisible (true); } }); } }

Rispondi quotando