Создать класс с кнопками, которые вызывают соответствующий метод - Java
Формулировка задачи:
Создать на языке Java класс, который описывает понятие реального мира согласно варианту задания. Класс должен иметь не менее 5 полей, описывающих свойства данного понятия и не менее 3 методов, которые описывают его поведение. Методы должны работать с полями, читать или записывать их; все поля должны быть задействованы в методах. Имена полей должны начинаться с существительного или прилагательного, методов - с глагола. Создать программу, которая создает окно с четырьмя кнопками. При нажатии на первую кнопку должен создаться объект нашего класса, при нажатии на каждую из других кнопок должен запускаться соответствующий метод нашего класса.
Вариант:
Дерево.
ПОМОГИТЕ ПОЖАЛУЙСТА. ОЧЕНЬ ПРОШУ!!!
Решение задачи: «Создать класс с кнопками, которые вызывают соответствующий метод»
textual
Листинг программы
package exp.dag;
import javax.swing.*;
import java.awt.*;
public class Tree {
private static Tree tree;
private double height, diameter, age, depth; // высота, диаметр ствола, возраст, глубина корней
private int countOfLeaves; // количество листьев
private int season = 1; // времена года
private Tree(double height, double diameter, double age, double depth, int countOfLeaves) {
this.height = height;
this.diameter = diameter;
this.age = age;
this.depth = depth;
this.countOfLeaves = countOfLeaves;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 100);
frame.setLocationRelativeTo(null);
JButton button1 = new JButton("Создание дерева");
JButton button2 = new JButton("Вырасти");
JButton button3 = new JButton("Питаться");
JButton button4 = new JButton("Контролировать листву");
button1.addActionListener(e -> tree = new Tree(2, .05, 1, .5, 30));
button2.addActionListener(e -> {
if (tree != null) tree.grow();
System.out.println(tree);
});
button3.addActionListener(e -> {
if (tree != null) tree.eat();
System.out.println(tree);
});
button4.addActionListener(e -> {
if (tree != null) tree.toControlFoliage();
System.out.println(tree);
});
frame.setLayout(new FlowLayout());
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.setVisible(true);
}
private void grow() { // расти
age += .1;
height += .01;
diameter += .0005;
season = (int) (age % 1 % .25);
}
private void eat() { // питаться
depth += .1;
grow();
grow();
toControlFoliage();
}
private void toControlFoliage() { // контролировать листву
if (season == 1 || season == 2 || season == 3) countOfLeaves += 100;
else countOfLeaves = countOfLeaves - 1000 > 0 ? countOfLeaves - 1000 : 0; // season == 4
}
@Override
public String toString() {
return "Tree{" +
"height=" + height +
", diameter=" + diameter +
", age=" + age +
", depth=" + depth +
", countOfLeaves=" + countOfLeaves +
", season=" + season +
'}';
}
}