[英]Altering JFrame component based on button press from contained JPanel
我正在嘗試創建一個應用程序,當按下按鈕時,該應用程序將在LocalDateTime對象中增加月份。
顯示月份名稱的LocalDateTime對象和JLabel存儲在擴展JFrame的Main類中。
具有ActionListener的JButton,在按下該按鈕時,將LocalDateTime對象的月份增加1,該按鈕存儲在稱為Panel1的單獨類中,該類擴展了JPanel。
Panel1類已添加到JFrame。 我應該怎么做才能使JLabel在按下按鈕時反映對LocalDateTime對象所做的更改?
主類:
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();
}
}
Panel1類別:
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);
}
}
}
如果需要觀察者模式,則可以在回轉組件上使用PropertyChangeListener。 您的Panel1應該在屬性上觸發一個事件
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) {
LocalDateTime oldValue = time;
time = time.plusMonths(1);
this.firePropertyChange("month", oldValue.getMonth().name(), time.getMonth().name());
}
}
}
在您的Main類中的以下代碼中可以識別出“ month”屬性:
super();
setLayout(new BorderLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
monthLabel = new JLabel(currentTime.getMonth().name());
add(monthLabel, BorderLayout.NORTH);
Panel1 panel1 = new Panel1(currentTime);
panel1.addPropertyChangeListener("month", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
monthLabel.setText(evt.getNewValue().toString());
}
});
add(panel1, BorderLayout.SOUTH);
pack();
setVisible(true);
我更喜歡這種解決方案,而不是將擺動組件鏈接在一起或使其靜止。
我應該怎么做才能使JLabel在按下按鈕時反映對LocalDateTime對象所做的更改?
內容如下:
聲明monthLabel
為protected static
。
protected static JLabel monthLabel;
這樣,它將對包中的其他類可見。
添加該行以更改actionPerformed()
方法中的文本。
public void actionPerformed(ActionEvent e) { if (e.getSource() == incrementMonth) { time = time.plusMonths(1); Main.monthLabel.setText(time.getMonth().name()); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.