ボタンを押したときにLocalDateTimeオブジェクトの月をインクリメントするアプリケーションを作成しようとしています。ボタンの押下に基づいてJFrameコンポーネントを変更するJPanel
月名を表示するLocalDateTimeオブジェクトとJLabelは、JFrameを拡張するMainクラスに格納されます。
ActionListenerを持つJButtonは、押したときにLocalDateTimeオブジェクトの月を1だけインクリメントし、JPanelを拡張するPanel1という別のクラスに格納されます。
Panel1クラスがJFrameに追加されました。ボタンを押したときにLocalDateTimeオブジェクトに加えられた変更をJLabelが反映するようにするにはどうすればよいですか?
メインクラス:
import javax.swing.*;
import java.awt.*;
import java.time.LocalDateTime;
public class Main extends JFrame {
private LocalDateTime currentTime = LocalDateTime.now();
private JLabel monthLabel;
public Main() {
super();
setLayout(new BorderLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
monthLabel = new JLabel(currentTime.getMonth().name());
add(monthLabel, BorderLayout.NORTH);
add(new Panel1(currentTime), BorderLayout.SOUTH);
pack();
setVisible(true);
}
public static void main(String args[]) {
Main main = new Main();
}
}
パネル1クラス:私はJLabelのはLocalDateTimeをオブジェクトに加えられた変更を反映するように、ボタンがあるときにそれを作るために何をすべき
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDateTime;
public class Panel1 extends JPanel implements ActionListener {
private LocalDateTime time;
private JButton incrementMonth;
public Panel1(LocalDateTime time) {
this.time = time;
incrementMonth = new JButton(">");
incrementMonth.addActionListener(this);
add(incrementMonth);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == incrementMonth) {
time = time.plusMonths(1);
}
}
}