Klasa wewnętrzna / klasa anonimowa
Kody źródłowe z odcinka
package pl.am.swing.zdarzenia2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class MyFrame extends JFrame {
private JPanel panel;
public MyFrame() {
setTitle("Zdarzenia");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 400);
panel = new JPanel();
JButton button = new JButton("Zmień kolor tła");
button.addActionListener(this::changeColour);
panel.add(button);
add(panel);
}
private void changeColour(ActionEvent e) {
System.out.println("zostalem klikniety");
Random random = new Random();
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
panel.setBackground(new Color(r, g, b));
}
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
}
}