WindowListener / WindowAdapter
Kody źródłowe z odcinka
package pl.am.swing.zdarzenia3;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
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);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("czy zapisac dane przed zamknieciem");
}
});
}
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);
}
}