import java.awt.event.MouseAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
class MouseEvent {
private Point position;
private String type;
Point getPosition() { return position; }
String getType() { return type; }
MouseEvent(Point position, String type) {
this.position = position;
this.type = type;
}
}
abstract class Component {
private Rectangle bounds;
Component(Rectangle bounds) {
this.bounds = bounds;
}
int getWidth() {
return bounds.width;
}
int getHeight() {
return bounds.height;
}
Rectangle getBounds() {
return bounds;
}
abstract void mouseEvent(MouseEvent e);
abstract void paint(Graphics2D g);
}
class Container extends Component {
private ArrayList<Component> components = new ArrayList<>();
Container(Rectangle bounds) {
super(bounds);
}
void add(Component comp) {
components.add(comp);
}
void mouseEvent(MouseEvent e) {
for(Component cp: components) {
if(cp.getBounds().contains(e.getPosition())) {
MouseEvent e2 =
new MouseEvent(new Point(e.getPosition().x - cp.getBounds().x,
e.getPosition().y - cp.getBounds().y),
e.getType());
cp.mouseEvent(e2);
}
}
}
void paint(Graphics2D g) {
for(Component cp: components) {
Rectangle bounds = cp.getBounds();
Graphics2D g2 = (Graphics2D)g.create(bounds.x, bounds.y,
bounds.width, bounds.height);
cp.paint(g2);
g2.dispose();
}
}
}
class Window extends Container {
Window(Rectangle bounds) {
super(bounds);
}
@Override
void paint(Graphics2D g) {
g.setColor(Color.BLUE);
g.fillRect(0, 0, getWidth(), getHeight());
super.paint(g);
}
}
class Button extends Component {
private String name;
Button(String name, Rectangle bounds) {
super(bounds);
this.name = name;
}
void mouseEvent(MouseEvent e) {
System.out.println("button \"" + name + "\" mouse " + e.getType());
}
void paint(Graphics2D g) {
g.setColor(Color.RED);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
g.drawString(name, 10, 20);
}
}
public class GUI extends JPanel {
static Component comp;
public static void main(String[] args) {
Window window = new Window(new Rectangle(100, 100, 800, 600));
window.add(new Button("Click me", new Rectangle(200, 200, 100, 50)));
Container container = new Container(new Rectangle(0, 0 , 1024, 768));
container.add(window);
comp = container;
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI gui = new GUI();
gui.setPreferredSize(new Dimension(1024, 768));
gui.addMouseListener(new MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent e) {
comp.mouseEvent(new MouseEvent(e.getPoint(), "clicked"));
}
});
frame.add(gui);
frame.pack();
frame.setVisible(true);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
comp.paint(g2);
}
}