Pierwsze zdarzenie
Kody źródłowe z odcinka
package pl.am.swing.zdarzenia;
import javax.swing.*;
import java.awt.*;
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(new ChaneColorAction(panel));
panel.add(button);
add(panel);
}
public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
}
}
package pl.am.swing.zdarzenia;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class ChaneColorAction implements ActionListener {
private JPanel panel;
public ChaneColorAction(JPanel panel) {
this.panel = panel;
}
@Override
public void actionPerformed(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));
}
}