Obsługa zdarzeń myszy
Kody źródłowe z odcinka
package pl.am.swing.zdarzenia4;
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
public MyFrame() {
setTitle("Zdarzenia myszy");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000, 600);
add(new MyComponent());
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
});
}
}
package pl.am.swing.zdarzenia4;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MyComponent extends JComponent {
private int mouseX = 500;
private int mouseY = 300;
public MyComponent() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
System.out.println("mouseX = " + mouseX);
repaint();
}
});
}
@Override
protected void paintComponent(Graphics g) {
System.out.println("rysowanie");
Graphics2D graphics2D = (Graphics2D) g;
Point point = new Point(mouseX-100, mouseY-100);
Dimension dimension = new Dimension(200, 200);
Rectangle rectangle = new Rectangle(point, dimension);
graphics2D.fill(rectangle);
}
}