public class Q233043003 implements Runnable {
private static final int INTERVAL = 1000 / 30; // ~30 fps
private JFrame frame;
private WierdComponent wierd;
private Timer renderTimer;
@Override
public void run() {
initComponents();
initEvents();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
this.renderTimer = new Timer(INTERVAL, wierd::nextFrame);
renderTimer.start();
}
private void initComponents() {
this.frame = new JFrame(getClass().getSimpleName());
this.wierd = new WierdComponent();
Container pane = frame.getContentPane();
pane.setLayout(new BorderLayout());
pane.add(wierd, BorderLayout.CENTER);
}
private void initEvents() {
MouseAdapter mouseListener = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
wierd.pressed(e);
}
};
wierd.addMouseListener(mouseListener);
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int res = JOptionPane.showConfirmDialog(frame, "Exit?",
"EXIT", JOptionPane.YES_NO_OPTION);
if (res != JOptionPane.YES_OPTION) {
return;
}
if (renderTimer != null) {
renderTimer.stop();
}
frame.setVisible(false);
frame.dispose();
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Q233043003());
}
}
public class WierdComponent extends JComponent {
private final int WIDTH = 400;
private final int HEIGHT = 400;
private final int XC = 50;
private final int YC = 50;
private int x = 5;
private int y = 5;
private int ovalX = 150;
private int x1 = 250;
private int x2 = 270;
private int x3 = 290;
private boolean ovalColorChanged = false;
WierdComponent() {
super();
setOpaque(true);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
}
public void pressed(MouseEvent e) {
int xx = e.getX();
int yy = e.getY();
if (xx >= ovalX && xx <= ovalX + XC
&& yy >= y && yy <= y + YC) {
ovalColorChanged = !ovalColorChanged;
RepaintManager rm = RepaintManager.currentManager(this);
rm.addDirtyRegion(this, ovalX, y, XC, YC);
rm.paintDirtyRegions();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(UIManager.getColor("Panel.background"));
g2.fillRect(getX(), getY(), getWidth(), getHeight());
g2.setPaint(Color.GREEN);
g2.fillOval(x, 75, 15, 15);
if (ovalColorChanged) {
g2.setPaint(Color.YELLOW);
} else {
g2.setPaint(Color.RED);
}
g2.fillOval(ovalX, y, XC, YC);
int[] xs = {x1, x2, x3};
int[] ys = {100, 80, 110};
g2.setPaint(Color.BLUE);
g2.drawPolygon(xs, ys, xs.length);
g2.dispose();
}
public void nextFrame(ActionEvent actionEvent) {
if (y<75) {
x+=4;
y+=2;
x1-=2;
x2-=2;
x3-=2;
} else {
if (x1 < 290) {
x1 += 5;
}
}
RepaintManager rm = RepaintManager.currentManager(this);
rm.markCompletelyDirty(this);
rm.paintDirtyRegions();
}
}