sintassi
implementa interfaccia ActionListener
implements ActionListener
setta intercetta bottone
oggetto.addActionListener(this);
metodo in cui si gestiscono gli eventi
public void actionPerformed(ActionEvent event)
{
event.getSource() restituisce il bottone che ha generato l'evento}
esempio: form con 3 bottoni e tre messaggi differenti
import javax.swing.*;
import java.awt.event.*;
public class FormAction extends JFrame implements ActionListener
{
// variabili globali}
JPanel pnl = new JPanel(); // aggiugi un pannello in cui inserire i vari componenti
// componenti
JButton bottone1 = new JButton("Informaioni");
JButton bottone2 = new JButton("Avviso");
JButton bottone3 = new JButton("Errore");
public static void main(String args[])
{FormAction form = new FormAction(); // avvia il form Nome_Form}
// costruttore e settaggi del Form Nome_Form
public FormAction()
{super("Titolo Form"); // titolo del Form}
setSize(500 , 200); // dimensioni (ex. 500,200)
setDefaultCloseOperation(EXIT_ON_CLOSE); // operazione da eseguire dei default (metti sempre questa)
setVisible(true); // visualizza
// intercetta eventi bottone
bottone1.addActionListener(this);
bottone2.addActionListener(this);
bottone3.addActionListener(this);
// componenti
pnl.add(bottone1);
pnl.add(bottone2);
pnl.add(bottone3);
add(pnl); // aggiungi pannello
// evento click bottone
@Override
public void actionPerformed(ActionEvent event)
{if (event.getSource() == bottone1)}
{JOptionPane.showMessageDialog(new JFrame(), "Informazioni", "Informazioni", JOptionPane.INFORMATION_MESSAGE);}
if (event.getSource() == bottone2)
{JOptionPane.showMessageDialog(new JFrame(), "Avviso", "Avviso", JOptionPane.WARNING_MESSAGE);}
if (event.getSource() == bottone3)
{JOptionPane.showMessageDialog(new JFrame(), "Errore", "Errore", JOptionPane.ERROR_MESSAGE);}