public class VintagePocketWatch extends JPanel implements ActionListener {
code
private Timer timer;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(400, 400));
timer = new Timer(1000, this); // обновление каждую секунду
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка циферблата
g.setColor(new Color(222, 184, 135)); // Светло-коричневый цвет для циферблата
g.fillOval(50, 50, 300, 300);
// Отрисовка золотой кромки
g.setColor(new Color(255, 215, 0)); // Золотой цвет
g.drawOval(50, 50, 300, 300); // Кромка циферблата
// Римские цифры для меток
String[] romanNumerals = {"XII", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI"};
// Отрисовка римских цифр
for (int i = 0; i < 12; i++) {
double angle = Math.toRadians(i * 30); // 30 градусов между метками
int x = (int) (200 + 100 * Math.cos(angle - Math.PI / 2)); // Положение по X
int y = (int) (200 + 100 * Math.sin(angle - Math.PI / 2)); // Положение по Y
// Установка шрифта для римских цифр
g.setFont(new Font("Serif", Font.BOLD, 20));
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(romanNumerals[i]);
int textHeight = fm.getHeight();
// Вычисляем позицию для центрирования текста
g.drawString(romanNumerals[i], x - textWidth / 2, y + textHeight / 2);
}
// Получение текущего времени
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) % 12;
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
// Угол для стрелок
double hourAngle = Math.toRadians(hour * 30 + minute * 0.5); // 30° за час + 0.5° за минуту
double minuteAngle = Math.toRadians(minute * 6); // 6° за минуту
double secondAngle = Math.toRadians(second * 6); // 6° за секунду
// Отрисовка стрелок часов
g.setColor(Color.BLACK);
g.drawLine(200, 200, (int) (200 + 60 * Math.cos(hourAngle - Math.PI / 2)), (int) (200 + 60 * Math.sin(hourAngle - Math.PI / 2)));
g.drawLine(200, 200, (int) (200 + 90 * Math.cos(minuteAngle - Math.PI / 2)), (int) (200 + 90 * Math.sin(minuteAngle - Math.PI / 2)));
g.setColor(Color.RED);
g.drawLine(200, 200, (int) (200 + 100 * Math.cos(secondAngle - Math.PI / 2)), (int) (200 + 100 * Math.sin(secondAngle - Math.PI / 2)));
}
@Override
public void actionPerformed(ActionEvent e) {
repaint(); // Перерисовка панели каждую секунду
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Assistant
User
Assistant
User
Assistant
User
Assistant
User
Assistant
} Сделай в середине циферблата дополнительный декоративный механизм состоящий из 5 шестеренок соединённых между собой, который будут анимированы вращением
Добавление анимированного механизма, состоящего из пяти вращающихся зубчатых шестеренок, может значительно усложнить ваш код. Вот как вы можете это сделать:
Создайте класс Gear, который будет представлять отдельную шестеренку.
Нарисуйте каждую шестеренку в paintComponent.
Обновите угол каждой шестеренки в actionPerformed для создания анимации.
Вот пример кода, как это сделать:
java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
public class VintagePocketWatch extends JPanel implements ActionListener {
private Timer timer;
private Gear[] gears;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(400, 400));
timer = new Timer(1000, this); // обновление каждую секунду
timer.start();
gears = new Gear[5];
for (int i = 0; i < gears.length; i++) {
gears[i] = new Gear(200, 200, 20 + i * 10, 10 + i * 2, i % 2 == 0);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка циферблата
g.setColor(new Color(222, 184, 135)); // Светло-коричневый цвет для циферблата
g.fillOval(50, 50, 300, 300);
// Отрисовка золотой кромки
g.setColor(new Color(255, 215, 0)); // Золотой цвет
g.drawOval(50, 50, 300, 300); // Кромка циферблата
// Римские цифры для меток
String[] romanNumerals = {"XII", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI"};
// Отрисовка римских цифр
for (int i = 0; i < 12; i++) {
double angle = Math.toRadians(i * 30); // 30 градусов между метками
int x = (int) (200 + 100 * Math.cos(angle - Math.PI / 2)); // Положение по X
int y = (int) (200 + 100 * Math.sin(angle - Math.PI / 2)); // Положение по Y
// Установка шрифта для римских цифр
g.setFont(new Font("Serif", Font.BOLD, 20));
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(romanNumerals[i]);
int textHeight = fm.getHeight();
// Вычисляем позицию для центрирования текста
g.drawString(romanNumerals[i], x - textWidth / 2, y + textHeight / 2);
}
// Анимация шестерёнок
for (Gear gear : gears) {
gear.draw(g);
}
// Получение текущего времени
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) % 12;
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
// Угол для стрелок
double hourAngle = Math.toRadians(hour * 30 + minute * 0.5); // 30° за час + 0.5° за минуту
double minuteAngle = Math.toRadians(minute * 6); // 6° за минуту
double secondAngle = Math.toRadians(second * 6); // 6° за секунду
// Отрисовка стрелок часов
g.setColor(Color.BLACK);
g.drawLine(200, 200, (int) (200 + 60 * Math.cos(hourAngle - Math.PI / 2)), (int) (200 + 60 * Math.sin(hourAngle - Math.PI / 2)));
g.drawLine(200, 200, (int) (200 + 90 * Math.cos(minuteAngle - Math.PI / 2)), (int) (200 + 90 * Math.sin(minuteAngle - Math.PI / 2)));
g.setColor(Color.RED);
g.drawLine(200, 200, (int) (200 + 100 * Math.cos(secondAngle - Math.PI / 2)), (int) (200 + 100 * Math.sin(secondAngle - Math.PI / 2)));
}
@Override
public void actionPerformed(ActionEvent e) {
for (Gear gear : gears) {
gear.update();
}
repaint(); // Перерисовка панели каждую секунду
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Gear {
private int x, y, radius, teeth;
private double angle;
private boolean clockwise;
public Gear(int x, int y, int radius, int teeth, boolean clockwise) {
this.x = x;
this.y = y;
this.radius = radius;
this.teeth = teeth;
this.clockwise = clockwise;
this.angle = 0;
}
public void update() {
if (clockwise) {
angle += Math.toRadians(5);
} else {
angle -= Math.toRadians(5);
}
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.GRAY);
g2d.setStroke(new BasicStroke(2));
for (int i = 0; i < teeth; i++) {
double toothAngle = angle + i * (2 * Math.PI / teeth);
int toothX = (int) (x + radius * Math.cos(toothAngle));
int toothY = (int) (y + radius * Math.sin(toothAngle));
g2d.drawLine(x, y, toothX, toothY);
}
// Нарисовать тело шестеренки
g2d.drawOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
Объяснение:
Gear Class: Новый класс Gear представляет отдельную шестеренку с параметрами её позиции, радиуса, количества зубцов и направления вращения.
Метод update: Обновляет угол вращения шестеренки.
Метод draw: Отрисовывает шестеренку с зубцами, используя Graphics2D для более сложного рисования.
Это базовое решение; вы можете дополнительно настроить радиусы, количество зубцов и другие параметры шестеренок для более интересного визуального эффекта.
public class VintagePocketWatch extends JPanel implements ActionListener {
code
private Timer timer;
private Gear[] gears;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(400, 400));
timer = new Timer(1000, this); // обновление каждую секунду
timer.start();
gears = new Gear[5];
for (int i = 0; i < gears.length; i++) {
gears[i] = new Gear(200, 200, 20 + i * 10, 10 + i * 2, i % 2 == 0);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка циферблата
g.setColor(new Color(222, 184, 135)); // Светло-коричневый цвет для циферблата
g.fillOval(50, 50, 300, 300);
// Отрисовка золотой кромки
g.setColor(new Color(255, 215, 0)); // Золотой цвет
g.drawOval(50, 50, 300, 300); // Кромка циферблата
// Римские цифры для меток
String[] romanNumerals = {"XII", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI"};
// Отрисовка римских цифр
for (int i = 0; i < 12; i++) {
double angle = Math.toRadians(i * 30); // 30 градусов между метками
int x = (int) (200 + 100 * Math.cos(angle - Math.PI / 2)); // Положение по X
int y = (int) (200 + 100 * Math.sin(angle - Math.PI / 2)); // Положение по Y
// Установка шрифта для римских цифр
g.setFont(new Font("Serif", Font.BOLD, 20));
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(romanNumerals[i]);
int textHeight = fm.getHeight();
// Вычисляем позицию для центрирования текста
g.drawString(romanNumerals[i], x - textWidth / 2, y + textHeight / 2);
}
// Анимация шестерёнок
for (Gear gear : gears) {
gear.draw(g);
}
// Получение текущего времени
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) % 12;
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
// Угол для стрелок
double hourAngle = Math.toRadians(hour * 30 + minute * 0.5); // 30° за час + 0.5° за минуту
double minuteAngle = Math.toRadians(minute * 6); // 6° за минуту
double secondAngle = Math.toRadians(second * 6); // 6° за секунду
// Отрисовка стрелок часов
g.setColor(Color.BLACK);
g.drawLine(200, 200, (int) (200 + 60 * Math.cos(hourAngle - Math.PI / 2)), (int) (200 + 60 * Math.sin(hourAngle - Math.PI / 2)));
g.drawLine(200, 200, (int) (200 + 90 * Math.cos(minuteAngle - Math.PI / 2)), (int) (200 + 90 * Math.sin(minuteAngle - Math.PI / 2)));
g.setColor(Color.RED);
g.drawLine(200, 200, (int) (200 + 100 * Math.cos(secondAngle - Math.PI / 2)), (int) (200 + 100 * Math.sin(secondAngle - Math.PI / 2)));
}
@Override
public void actionPerformed(ActionEvent e) {
for (Gear gear : gears) {
gear.update();
}
repaint(); // Перерисовка панели каждую секунду
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Gear {
private int x, y, radius, teeth;
private double angle;
private boolean clockwise;
code
public Gear(int x, int y, int radius, int teeth, boolean clockwise) {
this.x = x;
this.y = y;
this.radius = radius;
this.teeth = teeth;
this.clockwise = clockwise;
this.angle = 0;
}
public void update() {
if (clockwise) {
angle += Math.toRadians(5);
} else {
angle -= Math.toRadians(5);
}
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.GRAY);
g2d.setStroke(new BasicStroke(2));
for (int i = 0; i < teeth; i++) {
double toothAngle = angle + i * (2 * Math.PI / teeth);
int toothX = (int) (x + radius * Math.cos(toothAngle));
int toothY = (int) (y + radius * Math.sin(toothAngle));
g2d.drawLine(x, y, toothX, toothY);
}
// Нарисовать тело шестеренки
g2d.drawOval(x - radius, y - radius, radius * 2, radius * 2);
}
} Сделай более приятное сочетание цветов, измени сами часы
Конечно! Давайте придадим часам более современный вид, комбинируя приятные цветовые тона и улучшая интерфейс. Я предложу небольшой набор изменений, включая новые цвета и модернизированный, лаконичный стиль для шестеренок и циферблата. Вот обновленный код:
java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
public class VintagePocketWatch extends JPanel implements ActionListener {
private Timer timer;
private Gear[] gears;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(400, 400));
timer = new Timer(1000, this); // обновление каждую секунду
timer.start();
gears = new Gear[5];
for (int i = 0; i < gears.length; i++) {
int offset = (i - 2) * 40; // Центрируем шестеренки относительно друг друга
gears[i] = new Gear(200 + offset, 200, 30 - i * 5, 12, i % 2 == 0);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка циферблата фоном в мягком сером цвете
g.setColor(new Color(240, 240, 240));
g.fillOval(50, 50, 300, 300);
// Отрисовка кромки циферблата в стальном синем цвете
g.setColor(new Color(70, 130, 180));
g.drawOval(50, 50, 300, 300);
// Римские цифры для меток в более светлом, зеленоватом оттенке
String[] romanNumerals = {"XII", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI"};
g.setColor(new Color(60, 179, 113));
for (int i = 0; i < 12; i++) {
double angle = Math.toRadians(i * 30); // 30 градусов между метками
int x = (int) (200 + 120 * Math.cos(angle - Math.PI / 2)); // Положение по X
int y = (int) (200 + 120 * Math.sin(angle - Math.PI / 2)); // Положение по Y
g.setFont(new Font("Serif", Font.BOLD, 18));
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(romanNumerals[i]);
int textHeight = fm.getHeight();
g.drawString(romanNumerals[i], x - textWidth / 2, y + textHeight / 2);
}
// Анимация шестерёнок
for (Gear gear : gears) {
gear.draw(g);
}
// Получение текущего времени
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) % 12;
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
// Угол для стрелок
double hourAngle = Math.toRadians(hour * 30 + minute * 0.5); // 30° за час + 0.5° за минуту
double minuteAngle = Math.toRadians(minute * 6); // 6° за минуту
double secondAngle = Math.toRadians(second * 6); // 6° за секунду
// Отрисовка стрелок часов, используя насыщенную морскую зелень
g.setColor(new Color(32, 178, 170));
g.drawLine(200, 200, (int) (200 + 60 * Math.cos(hourAngle - Math.PI / 2)), (int) (200 + 60 * Math.sin(hourAngle - Math.PI / 2)));
g.drawLine(200, 200, (int) (200 + 90 * Math.cos(minuteAngle - Math.PI / 2)), (int) (200 + 90 * Math.sin(minuteAngle - Math.PI / 2)));
g.setColor(new Color(255, 69, 0));
g.drawLine(200, 200, (int) (200 + 100 * Math.cos(secondAngle - Math.PI / 2)), (int) (200 + 100 * Math.sin(secondAngle - Math.PI / 2)));
}
@Override
public void actionPerformed(ActionEvent e) {
for (Gear gear : gears) {
gear.update();
}
repaint(); // Перерисовка панели каждую секунду
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Gear {
private int x, y, radius, teeth;
private double angle;
private boolean clockwise;
public Gear(int x, int y, int radius, int teeth, boolean clockwise) {
this.x = x;
this.y = y;
this.radius = radius;
this.teeth = teeth;
this.clockwise = clockwise;
this.angle = 0;
}
public void update() {
angle += clockwise ? Math.toRadians(5) : Math.toRadians(-5);
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(119, 136, 153)); // светло-серый
g2d.setStroke(new BasicStroke(2));
for (int i = 0; i < teeth; i++) {
double toothAngle = angle + i * (2 * Math.PI / teeth);
int toothX = (int) (x + (radius + 5) * Math.cos(toothAngle));
int toothY = (int) (y + (radius + 5) * Math.sin(toothAngle));
g2d.drawLine(x, y, toothX, toothY);
}
// Нарисовать тело шестеренки
g2d.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
Ключевые изменения:
Цвета: Я заменил цвета на более современные и мягкие, добавив оттенки серого, стального синего, морской зелени и насыщенного оранжевого для улучшения визуального восприятия.
Расположение шестеренок: Придал центральной композиции более интересный вид, разместив шестеренки относительно друг друга.
Стрелки и цифры: Цвета стрелок и цифры теперь используют более насыщенные, но приятные для глаз оттенки.
Эти изменения помогут придать часам более современный и стильный вид, сохранив при этом элемент роскошного винтажа.
public class VintagePocketWatch extends JPanel implements ActionListener {
code
private Timer timer;
private Gear[] gears;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(400, 400));
timer = new Timer(1000, this); // обновление каждую секунду
timer.start();
gears = new Gear[5];
for (int i = 0; i < gears.length; i++) {
int offset = (i - 2) * 40; // Центрируем шестеренки относительно друг друга
gears[i] = new Gear(200 + offset, 200, 30 - i * 5, 12, i % 2 == 0);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка циферблата фоном в мягком сером цвете
g.setColor(new Color(240, 240, 240));
g.fillOval(50, 50, 300, 300);
// Отрисовка кромки циферблата в стальном синем цвете
g.setColor(new Color(70, 130, 180));
g.drawOval(50, 50, 300, 300);
// Римские цифры для меток в более светлом, зеленоватом оттенке
String[] romanNumerals = {"XII", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI"};
g.setColor(new Color(60, 179, 113));
for (int i = 0; i < 12; i++) {
double angle = Math.toRadians(i * 30); // 30 градусов между метками
int x = (int) (200 + 120 * Math.cos(angle - Math.PI / 2)); // Положение по X
int y = (int) (200 + 120 * Math.sin(angle - Math.PI / 2)); // Положение по Y
g.setFont(new Font("Serif", Font.BOLD, 18));
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(romanNumerals[i]);
int textHeight = fm.getHeight();
g.drawString(romanNumerals[i], x - textWidth / 2, y + textHeight / 2);
}
// Анимация шестерёнок
for (Gear gear : gears) {
gear.draw(g);
}
// Получение текущего времени
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) % 12;
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
// Угол для стрелок
double hourAngle = Math.toRadians(hour * 30 + minute * 0.5); // 30° за час + 0.5° за минуту
double minuteAngle = Math.toRadians(minute * 6); // 6° за минуту
double secondAngle = Math.toRadians(second * 6); // 6° за секунду
// Отрисовка стрелок часов, используя насыщенную морскую зелень
g.setColor(new Color(32, 178, 170));
g.drawLine(200, 200, (int) (200 + 60 * Math.cos(hourAngle - Math.PI / 2)), (int) (200 + 60 * Math.sin(hourAngle - Math.PI / 2)));
g.drawLine(200, 200, (int) (200 + 90 * Math.cos(minuteAngle - Math.PI / 2)), (int) (200 + 90 * Math.sin(minuteAngle - Math.PI / 2)));
g.setColor(new Color(255, 69, 0));
g.drawLine(200, 200, (int) (200 + 100 * Math.cos(secondAngle - Math.PI / 2)), (int) (200 + 100 * Math.sin(secondAngle - Math.PI / 2)));
}
@Override
public void actionPerformed(ActionEvent e) {
for (Gear gear : gears) {
gear.update();
}
repaint(); // Перерисовка панели каждую секунду
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Gear {
private int x, y, radius, teeth;
private double angle;
private boolean clockwise;
code
public Gear(int x, int y, int radius, int teeth, boolean clockwise) {
this.x = x;
this.y = y;
this.radius = radius;
this.teeth = teeth;
this.clockwise = clockwise;
this.angle = 0;
}
public void update() {
angle += clockwise ? Math.toRadians(5) : Math.toRadians(-5);
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(119, 136, 153)); // светло-серый
g2d.setStroke(new BasicStroke(2));
for (int i = 0; i < teeth; i++) {
double toothAngle = angle + i * (2 * Math.PI / teeth);
int toothX = (int) (x + (radius + 5) * Math.cos(toothAngle));
int toothY = (int) (y + (radius + 5) * Math.sin(toothAngle));
g2d.drawLine(x, y, toothX, toothY);
}
// Нарисовать тело шестеренки
g2d.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
} Сделай на фоне эффект сильно бегущего времени вперед, добавь постройки деревья, как они вырастают и опадают
Добавление эффекта стремительно изменяющегося времени в сочетании с элементами развития и угасания природы может быть сложной задачей, но это выполнимо с анимацией. Мы можем создать анимационный цикл, который будет обновлять сцену и играть эффекты роста и увядания. Следующий пример кода создаст такую сцену:
Эффект времени: Добавим визуальный элемент, который имитирует быстрое течение времени.
Рост и увядание деревьев: Будем визуализировать рост и увядание деревьев с изменением времени.
Этот пример не будет идеально реалистичным, но он пытается создать простую визуализацию предложенных эффектов:
java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class VintagePocketWatch extends JPanel implements ActionListener {
private Timer timer;
private int step; // Переменная шаг для эффекта времени
private List<Tree> trees;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(600, 600));
timer = new Timer(100, this); // обновление каждые 100 ms для плавной анимации
timer.start();
step = 0; // начальный шаг
trees = new ArrayList<>();
// Создаем деревья с начальными случаями
Random random = new Random();
for (int i = 0; i < 10; i++) {
int x = 50 + random.nextInt(500);
trees.add(new Tree(x, 400, random.nextInt(50) + 50));
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка фона
g.setColor(new Color(70, 130, 180));
g.fillRect(0, 0, getWidth(), getHeight());
// Ускоренное время
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(Color.WHITE);
String timeMessage = "Time is Flying: " + (step / 10) % 24 + ":00";
g.drawString(timeMessage, 20, 40);
// Отрисовка деревьев
for (Tree tree : trees) {
tree.draw(g, step);
}
}
@Override
public void actionPerformed(ActionEvent e) {
step++;
if (step % 500 == 0) { // Рестарт времени и деревьев каждые 50 секунд
step = 0;
// Пересаживаем деревья
Random random = new Random();
for (Tree tree : trees) {
tree.reset(random.nextInt(500) + 50);
}
}
repaint(); // Перерисовка панели
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch with Time Flow");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Tree {
private int x, baseY, maxHeight;
private int growthRate; // Скорость роста дерева
public Tree(int x, int y, int maxHeight) {
this.x = x;
this.baseY = y;
this.maxHeight = maxHeight;
this.growthRate = maxHeight / 100; // Разделите на шаги для роста
}
public void draw(Graphics g, int step) {
int currentHeight = Math.min(maxHeight, step * growthRate * 2); // Рост
int witherHeight = maxHeight - Math.min(maxHeight, (step - 250) * growthRate * 2); // Увядание
int height = (step < 250) ? currentHeight : witherHeight;
g.setColor(new Color(34, 139, 34)); // Цвет для деревьев
g.fillRect(x, baseY - height, 5, height);
g.setColor(new Color(139, 69, 19)); // Цвет ствола
g.fillRect(x + 2, baseY, 1, height / 5);
}
public void reset(int newMaxHeight) {
this.maxHeight = newMaxHeight;
this.growthRate = maxHeight / 100;
}
}
Основные идеи:
Эффект времени: Используем параметр step для управления временем, которое "летит" со скоростью.
Деревья: Деревья растут до определенной высоты, затем увядают, чтобы создать впечатление цикличности времени.
В этом примере упрощенные деревья растут и увядают с изменением времени. Текущее "время" меняется с каждым кадром, чтобы подчеркнуть "ускоренное" течение времени. Визуализация проста и абстрактна, и вы можете улучшить её, добавив дополнительные элементы или усложнив анимации.
public class VintagePocketWatch extends JPanel implements ActionListener {
code
private Timer timer;
private int step; // Переменная шаг для эффекта времени
private List<Tree> trees;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(600, 600));
timer = new Timer(100, this); // обновление каждые 100 ms для плавной анимации
timer.start();
step = 0; // начальный шаг
trees = new ArrayList<>();
// Создаем деревья с начальными случаями
Random random = new Random();
for (int i = 0; i < 10; i++) {
int x = 50 + random.nextInt(500);
trees.add(new Tree(x, 400, random.nextInt(50) + 50));
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка фона
g.setColor(new Color(70, 130, 180));
g.fillRect(0, 0, getWidth(), getHeight());
// Ускоренное время
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(Color.WHITE);
String timeMessage = "Time is Flying: " + (step / 10) % 24 + ":00";
g.drawString(timeMessage, 20, 40);
// Отрисовка деревьев
for (Tree tree : trees) {
tree.draw(g, step);
}
}
@Override
public void actionPerformed(ActionEvent e) {
step++;
if (step % 500 == 0) { // Рестарт времени и деревьев каждые 50 секунд
step = 0;
// Пересаживаем деревья
Random random = new Random();
for (Tree tree : trees) {
tree.reset(random.nextInt(500) + 50);
}
}
repaint(); // Перерисовка панели
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch with Time Flow");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Tree {
private int x, baseY, maxHeight;
private int growthRate; // Скорость роста дерева
code
public Tree(int x, int y, int maxHeight) {
this.x = x;
this.baseY = y;
this.maxHeight = maxHeight;
this.growthRate = maxHeight / 100; // Разделите на шаги для роста
}
public void draw(Graphics g, int step) {
int currentHeight = Math.min(maxHeight, step * growthRate * 2); // Рост
int witherHeight = maxHeight - Math.min(maxHeight, (step - 250) * growthRate * 2); // Увядание
int height = (step < 250) ? currentHeight : witherHeight;
g.setColor(new Color(34, 139, 34)); // Цвет для деревьев
g.fillRect(x, baseY - height, 5, height);
g.setColor(new Color(139, 69, 19)); // Цвет ствола
g.fillRect(x + 2, baseY, 1, height / 5);
}
public void reset(int newMaxHeight) {
this.maxHeight = newMaxHeight;
this.growthRate = maxHeight / 100;
}
} и это код в один файл public class VintagePocketWatch extends JPanel implements ActionListener {
code
}
class Gear {
private int x, y, radius, teeth;
private double angle;
private boolean clockwise;
code
public Gear(int x, int y, int radius, int teeth, boolean clockwise) {
this.x = x;
this.y = y;
this.radius = radius;
this.teeth = teeth;
this.clockwise = clockwise;
this.angle = 0;
}
public void update() {
angle += clockwise ? Math.toRadians(5) : Math.toRadians(-5);
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(119, 136, 153)); // светло-серый
g2d.setStroke(new BasicStroke(2));
for (int i = 0; i < teeth; i++) {
double toothAngle = angle + i * (2 * Math.PI / teeth);
int toothX = (int) (x + (radius + 5) * Math.cos(toothAngle));
int toothY = (int) (y + (radius + 5) * Math.sin(toothAngle));
g2d.drawLine(x, y, toothX, toothY);
}
// Нарисовать тело шестеренки
g2d.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
Конечно, я помогу вам объединить эти два кода в один, используя оба набора функций: анимацию механизма часов и растущие/угасающие деревья. Я буду стараться, чтобы оба элемента взаимодействовали в единой визуальной композиции.
Вот как может выглядеть объединенный код:
java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class VintagePocketWatch extends JPanel implements ActionListener {
private Timer timer;
private int step; // Переменная шаг для эффекта времени
private List<Tree> trees;
private Gear[] gears;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(600, 600));
timer = new Timer(100, this); // обновление каждые 100 ms для плавной анимации
timer.start();
step = 0; // начальный шаг
trees = new ArrayList<>();
// Создаем деревья с начальными параметрами
Random random = new Random();
for (int i = 0; i < 10; i++) {
int x = 50 + random.nextInt(500);
trees.add(new Tree(x, 500, random.nextInt(50) + 50));
}
// Инициализация шестеренок
gears = new Gear[5];
for (int i = 0; i < gears.length; i++) {
int offset = (i - 2) * 40; // Центрируем шестеренки относительно друг друга
gears[i] = new Gear(300 + offset, 300, 30 - i * 5, 12, i % 2 == 0);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка фона
g.setColor(new Color(70, 130, 180));
g.fillRect(0, 0, getWidth(), getHeight());
// Ускоренное время
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(Color.WHITE);
String timeMessage = "Time is Flying: " + (step / 10) % 24 + ":00";
g.drawString(timeMessage, 20, 40);
// Отрисовка деревьев
for (Tree tree : trees) {
tree.draw(g, step);
}
// Отрисовка циферблата
g.setColor(new Color(240, 240, 240));
g.fillOval(200, 150, 300, 300);
// Отрисовка кромки циферблата
g.setColor(new Color(70, 130, 180));
g.drawOval(200, 150, 300, 300);
// Римские цифры для меток
String[] romanNumerals = {"XII", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI"};
g.setColor(new Color(60, 179, 113));
for (int i = 0; i < 12; i++) {
double angle = Math.toRadians(i * 30); // 30 градусов между метками
int x = (int) (350 + 120 * Math.cos(angle - Math.PI / 2)); // Положение по X
int y = (int) (300 + 120 * Math.sin(angle - Math.PI / 2)); // Положение по Y
g.setFont(new Font("Serif", Font.BOLD, 18));
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(romanNumerals[i]);
int textHeight = fm.getHeight();
g.drawString(romanNumerals[i], x - textWidth / 2, y + textHeight / 2);
}
// Анимация шестерёнок
for (Gear gear : gears) {
gear.draw(g);
}
// Получение текущего времени
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) % 12;
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
// Угол для стрелок
double hourAngle = Math.toRadians(hour * 30 + minute * 0.5); // 30° за час + 0.5° за минуту
double minuteAngle = Math.toRadians(minute * 6); // 6° за минуту
double secondAngle = Math.toRadians(second * 6); // 6° за секунду
// Отрисовка стрелок часов
g.setColor(new Color(32, 178, 170));
g.drawLine(350, 300, (int) (350 + 60 * Math.cos(hourAngle - Math.PI / 2)), (int) (300 + 60 * Math.sin(hourAngle - Math.PI / 2)));
g.drawLine(350, 300, (int) (350 + 90 * Math.cos(minuteAngle - Math.PI / 2)), (int) (300 + 90 * Math.sin(minuteAngle - Math.PI / 2)));
g.setColor(new Color(255, 69, 0));
g.drawLine(350, 300, (int) (350 + 100 * Math.cos(secondAngle - Math.PI / 2)), (int) (300 + 100 * Math.sin(secondAngle - Math.PI / 2)));
}
@Override
public void actionPerformed(ActionEvent e) {
step++;
for (Gear gear : gears) {
gear.update();
}
if (step % 500 == 0) { // Рестарт времени и деревьев каждые 50 секунд
step = 0;
// Пересаживаем деревья
Random random = new Random();
for (Tree tree : trees) {
tree.reset(random.nextInt(50) + 50);
}
}
repaint(); // Перерисовка панели
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch with Time Flow and Nature");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Tree {
private int x, baseY, maxHeight;
private int growthRate; // Скорость роста дерева
public Tree(int x, int y, int maxHeight) {
this.x = x;
this.baseY = y;
this.maxHeight = maxHeight;
this.growthRate = maxHeight / 100; // Разделите на шаги для роста
}
public void draw(Graphics g, int step) {
int currentHeight = Math.min(maxHeight, step * growthRate * 2); // Рост
int witherHeight = maxHeight - Math.min(maxHeight, (step - 250) * growthRate * 2); // Увядание
int height = (step < 250) ? currentHeight : witherHeight;
g.setColor(new Color(34, 139, 34)); // Цвет для деревьев
g.fillRect(x, baseY - height, 5, height);
g.setColor(new Color(139, 69, 19)); // Цвет ствола
g.fillRect(x + 2, baseY, 1, height / 5);
}
public void reset(int newMaxHeight) {
this.maxHeight = newMaxHeight;
this.growthRate = maxHeight / 100;
}
}
class Gear {
private int x, y, radius, teeth;
private double angle;
private boolean clockwise;
public Gear(int x, int y, int radius, int teeth, boolean clockwise) {
this.x = x;
this.y = y;
this.radius = radius;
this.teeth = teeth;
this.clockwise = clockwise;
this.angle = 0;
}
public void update() {
angle += clockwise ? Math.toRadians(5) : Math.toRadians(-5);
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(119, 136, 153)); // светло-серый
g2d.setStroke(new BasicStroke(2));
for (int i = 0; i < teeth; i++) {
double toothAngle = angle + i * (2 * Math.PI / teeth);
int toothX = (int) (x + (radius + 5) * Math.cos(toothAngle));
int toothY = (int) (y + (radius + 5) * Math.sin(toothAngle));
g2d.drawLine(x, y, toothX, toothY);
}
// Нарисовать тело шестеренки
g2d.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
Объяснение:
Совмещение элементов: Я переместил часы вправо в сцене, чтобы оставить место для дерева и значительного фона на панели JPanel.
Шестеренки и деревья: Оба элемента присутствуют на единой панели, создавая интересные визуальные эффекты взаимодействия. Шестеренки вращаются, а деревья растут и увядают, символизируя бег времени.
public class VintagePocketWatch extends JPanel implements ActionListener {
code
private Timer timer;
private int step; // Переменная шаг для эффекта времени
private List<Tree> trees;
private Gear[] gears;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(600, 600));
timer = new Timer(100, this); // обновление каждые 100 ms для плавной анимации
timer.start();
step = 0; // начальный шаг
trees = new ArrayList<>();
// Создаем деревья с начальными параметрами
Random random = new Random();
for (int i = 0; i < 10; i++) {
int x = 50 + random.nextInt(500);
trees.add(new Tree(x, 500, random.nextInt(50) + 50));
}
// Инициализация шестеренок
gears = new Gear[5];
for (int i = 0; i < gears.length; i++) {
int offset = (i - 2) * 40; // Центрируем шестеренки относительно друг друга
gears[i] = new Gear(300 + offset, 300, 30 - i * 5, 12, i % 2 == 0);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка фона
g.setColor(new Color(70, 130, 180));
g.fillRect(0, 0, getWidth(), getHeight());
// Ускоренное время
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(Color.WHITE);
String timeMessage = "Time is Flying: " + (step / 10) % 24 + ":00";
g.drawString(timeMessage, 20, 40);
// Отрисовка деревьев
for (Tree tree : trees) {
tree.draw(g, step);
}
// Отрисовка циферблата
g.setColor(new Color(240, 240, 240));
g.fillOval(200, 150, 300, 300);
// Отрисовка кромки циферблата
g.setColor(new Color(70, 130, 180));
g.drawOval(200, 150, 300, 300);
// Римские цифры для меток
String[] romanNumerals = {"XII", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI"};
g.setColor(new Color(60, 179, 113));
for (int i = 0; i < 12; i++) {
double angle = Math.toRadians(i * 30); // 30 градусов между метками
int x = (int) (350 + 120 * Math.cos(angle - Math.PI / 2)); // Положение по X
int y = (int) (300 + 120 * Math.sin(angle - Math.PI / 2)); // Положение по Y
g.setFont(new Font("Serif", Font.BOLD, 18));
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(romanNumerals[i]);
int textHeight = fm.getHeight();
g.drawString(romanNumerals[i], x - textWidth / 2, y + textHeight / 2);
}
// Анимация шестерёнок
for (Gear gear : gears) {
gear.draw(g);
}
// Получение текущего времени
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) % 12;
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
// Угол для стрелок
double hourAngle = Math.toRadians(hour * 30 + minute * 0.5); // 30° за час + 0.5° за минуту
double minuteAngle = Math.toRadians(minute * 6); // 6° за минуту
double secondAngle = Math.toRadians(second * 6); // 6° за секунду
// Отрисовка стрелок часов
g.setColor(new Color(32, 178, 170));
g.drawLine(350, 300, (int) (350 + 60 * Math.cos(hourAngle - Math.PI / 2)), (int) (300 + 60 * Math.sin(hourAngle - Math.PI / 2)));
g.drawLine(350, 300, (int) (350 + 90 * Math.cos(minuteAngle - Math.PI / 2)), (int) (300 + 90 * Math.sin(minuteAngle - Math.PI / 2)));
g.setColor(new Color(255, 69, 0));
g.drawLine(350, 300, (int) (350 + 100 * Math.cos(secondAngle - Math.PI / 2)), (int) (300 + 100 * Math.sin(secondAngle - Math.PI / 2)));
}
@Override
public void actionPerformed(ActionEvent e) {
step++;
for (Gear gear : gears) {
gear.update();
}
if (step % 500 == 0) { // Рестарт времени и деревьев каждые 50 секунд
step = 0;
// Пересаживаем деревья
Random random = new Random();
for (Tree tree : trees) {
tree.reset(random.nextInt(50) + 50);
}
}
repaint(); // Перерисовка панели
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch with Time Flow and Nature");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Tree {
private int x, baseY, maxHeight;
private int growthRate; // Скорость роста дерева
code
public Tree(int x, int y, int maxHeight) {
this.x = x;
this.baseY = y;
this.maxHeight = maxHeight;
this.growthRate = maxHeight / 100; // Разделите на шаги для роста
}
public void draw(Graphics g, int step) {
int currentHeight = Math.min(maxHeight, step * growthRate * 2); // Рост
int witherHeight = maxHeight - Math.min(maxHeight, (step - 250) * growthRate * 2); // Увядание
int height = (step < 250) ? currentHeight : witherHeight;
g.setColor(new Color(34, 139, 34)); // Цвет для деревьев
g.fillRect(x, baseY - height, 5, height);
g.setColor(new Color(139, 69, 19)); // Цвет ствола
g.fillRect(x + 2, baseY, 1, height / 5);
}
public void reset(int newMaxHeight) {
this.maxHeight = newMaxHeight;
this.growthRate = maxHeight / 100;
}
}
class Gear {
private int x, y, radius, teeth;
private double angle;
private boolean clockwise;
code
public Gear(int x, int y, int radius, int teeth, boolean clockwise) {
this.x = x;
this.y = y;
this.radius = radius;
this.teeth = teeth;
this.clockwise = clockwise;
this.angle = 0;
}
public void update() {
angle += clockwise ? Math.toRadians(5) : Math.toRadians(-5);
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(119, 136, 153)); // светло-серый
g2d.setStroke(new BasicStroke(2));
for (int i = 0; i < teeth; i++) {
double toothAngle = angle + i * (2 * Math.PI / teeth);
int toothX = (int) (x + (radius + 5) * Math.cos(toothAngle));
int toothY = (int) (y + (radius + 5) * Math.sin(toothAngle));
g2d.drawLine(x, y, toothX, toothY);
}
// Нарисовать тело шестеренки
g2d.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
} в методе public VintagePocketWatch ошибки, так же не достает несколько библиотек
Похоже, что основной проблемой является назначение координат для деревьев и шестеренок, а также отсутствие некоторых библиотек. Давайте разберём ошибки и добавим недостающие импорты.
Исправления:
Недостающие пакеты: Убедитесь, что все необходимые пакеты импортированы в начале файла.
Убедитесь в использовании конструктора: Проверьте, правильно ли применены параметры и инициированы переменные внутри конструктора.
Контекст импорта: Убедитесь, что Timer и другие используемые объекты имеют правильные импорты.
Вот исправленный код:
java
package comp_grafic;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
public class VintagePocketWatch extends JPanel implements ActionListener {
private Timer timer;
private int step; // Переменная шаг для эффекта времени
private List<Tree> trees;
private Gear[] gears;
public VintagePocketWatch() {
this.setPreferredSize(new Dimension(600, 600));
timer = new Timer(100, this); // обновление каждые 100 ms для плавной анимации
timer.start();
step = 0; // начальный шаг
trees = new ArrayList<>();
// Создаем деревья с начальными параметрами
Random random = new Random();
for (int i = 0; i < 10; i++) {
int x = 50 + random.nextInt(500);
trees.add(new Tree(x, 500, random.nextInt(50) + 50));
}
// Инициализация шестеренок
gears = new Gear[5];
for (int i = 0; i < gears.length; i++) {
int offset = (i - 2) * 40; // Центрируем шестеренки относительно друг друга
gears[i] = new Gear(300 + offset, 300, 30 - i * 5, 12, i % 2 == 0);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Отрисовка фона
g.setColor(new Color(70, 130, 180));
g.fillRect(0, 0, getWidth(), getHeight());
// Ускоренное время
g.setFont(new Font("Arial", Font.BOLD, 30));
g.setColor(Color.WHITE);
String timeMessage = "Time is Flying: " + (step / 10) % 24 + ":00";
g.drawString(timeMessage, 20, 40);
// Отрисовка деревьев
for (Tree tree : trees) {
tree.draw(g, step);
}
// Отрисовка циферблата
g.setColor(new Color(240, 240, 240));
g.fillOval(200, 150, 300, 300);
// Отрисовка кромки циферблата
g.setColor(new Color(70, 130, 180));
g.drawOval(200, 150, 300, 300);
// Римские цифры для меток
String[] romanNumerals = {"XII", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI"};
g.setColor(new Color(60, 179, 113));
for (int i = 0; i < 12; i++) {
double angle = Math.toRadians(i * 30); // 30 градусов между метками
int x = (int) (350 + 120 * Math.cos(angle - Math.PI / 2)); // Положение по X
int y = (int) (300 + 120 * Math.sin(angle - Math.PI / 2)); // Положение по Y
g.setFont(new Font("Serif", Font.BOLD, 18));
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(romanNumerals[i]);
int textHeight = fm.getHeight();
g.drawString(romanNumerals[i], x - textWidth / 2, y + textHeight / 2);
}
// Анимация шестерёнок
for (Gear gear : gears) {
gear.draw(g);
}
// Получение текущего времени
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) % 12;
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
// Угол для стрелок
double hourAngle = Math.toRadians(hour * 30 + minute * 0.5); // 30° за час + 0.5° за минуту
double minuteAngle = Math.toRadians(minute * 6); // 6° за минуту
double secondAngle = Math.toRadians(second * 6); // 6° за секунду
// Отрисовка стрелок часов
g.setColor(new Color(32, 178, 170));
g.drawLine(350, 300, (int) (350 + 60 * Math.cos(hourAngle - Math.PI / 2)), (int) (300 + 60 * Math.sin(hourAngle - Math.PI / 2)));
g.drawLine(350, 300, (int) (350 + 90 * Math.cos(minuteAngle - Math.PI / 2)), (int) (300 + 90 * Math.sin(minuteAngle - Math.PI / 2)));
g.setColor(new Color(255, 69, 0));
g.drawLine(350, 300, (int) (350 + 100 * Math.cos(secondAngle - Math.PI / 2)), (int) (300 + 100 * Math.sin(secondAngle - Math.PI / 2)));
}
@Override
public void actionPerformed(ActionEvent e) {
step++;
for (Gear gear : gears) {
gear.update();
}
if (step % 500 == 0) { // Рестарт времени и деревьев каждые 50 секунд
step = 0;
// Пересаживаем деревья
Random random = new Random();
for (Tree tree : trees) {
tree.reset(random.nextInt(50) + 50);
}
}
repaint(); // Перерисовка панели
}
public static void main(String[] args) {
JFrame frame = new JFrame("Vintage Pocket Watch with Time Flow and Nature");
VintagePocketWatch watch = new VintagePocketWatch();
frame.add(watch);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Tree {
private int x, baseY, maxHeight;
private int growthRate; // Скорость роста дерева
public Tree(int x, int y, int maxHeight) {
this.x = x;
this.baseY = y;
this.maxHeight = maxHeight;
this.growthRate = maxHeight / 100; // Разделите на шаги для роста
}
public void draw(Graphics g, int step) {
int currentHeight = Math.min(maxHeight, step * growthRate * 2); // Рост
int witherHeight = maxHeight - Math.min(maxHeight, (step - 250) * growthRate * 2); // Увядание
int height = (step < 250) ? currentHeight : witherHeight;
g.setColor(new Color(34, 139, 34)); // Цвет для деревьев
g.fillRect(x, baseY - height, 5, height);
g.setColor(new Color(139, 69, 19)); // Цвет ствола
g.fillRect(x + 2, baseY, 1, height / 5);
}
public void reset(int newMaxHeight) {
this.maxHeight = newMaxHeight;
this.growthRate = maxHeight / 100;
}
}
class Gear {
private int x, y, radius, teeth;
private double angle;
private boolean clockwise;
public Gear(int x, int y, int radius, int teeth, boolean clockwise) {
this.x = x;
this.y = y;
this.radius = radius;
this.teeth = teeth;
this.clockwise = clockwise;
this.angle = 0;
}
public void update() {
angle += clockwise ? Math.toRadians(5) : Math.toRadians(-5);
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(119, 136, 153)); // светло-серый
g2d.setStroke(new BasicStroke(2));
for (int i = 0; i < teeth; i++) {
double toothAngle = angle + i * (2 * Math.PI / teeth);
int toothX = (int) (x + (radius + 5) * Math.cos(toothAngle));
int toothY = (int) (y + (radius + 5) * Math.sin(toothAngle));
g2d.drawLine(x, y, toothX, toothY);
}
// Нарисовать тело шестеренки
g2d.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
Объяснение исправлений:
Добавлены все необходимые import выражения для библиотек javax.swing и java.awt.
Описание конструктора VintagePocketWatch теперь обеспечивает правильную настройку панели и инициализацию объектов.
Убедитесь, что файл находится в правильной структуре пакетов, если используете пакет comp_grafic.
Возможное устранение отсутствия импорта класса Calendar.
Этот код должен быть работоспособным, если он находится в подходящей файловой структуре и окружении. Убедитесь, что все внешние зависимости на месте и пакетная структура соответствует вышеописанной.