Beh ci eri quasi. Devi dichiarare la classe MyButtonListener fuori dal metodo main.
Essendo il contesto statico, devi anche dichiararla come classe statica.
Inoltre devi importare ActionEvent e ActionListener.
codice:
package desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Main {
private static class MyButtonListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
System.out.print("ciao ita");
}
}
public static void main(String[] args){
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton button = new JButton("Hello again");
panel.add(button);
frame.add(panel);
MyButtonListener listener = new MyButtonListener();
button.addActionListener(listener);
}
}
Volendo, puoi anche usare classi anonime:
codice:
package desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Main {
public static void main(String[] args){
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton button = new JButton("Hello again");
panel.add(button);
frame.add(panel);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Ciao");
}
}
);
}
}
O, in maniera simile al tuo codice iniziale:
codice:
package desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Main {
public static void main(String[] args){
JFrame frame = new JFrame("Test");
frame.setVisible(true);
frame.setSize(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("ciao");
}
};
JButton button = new JButton("Hello again");
panel.add(button);
frame.add(panel);
button.addActionListener(listener);
}
}
Fai caso a questo "panel.add(button);". Se non lo metti dentro al panel, non lo vedrai sullo schermo.