我目前正在用 Java 编写日历。日历本身可以很好地填写,月份和年份显示在其下方网格上方的 JComboBoxes 中。Grid 本身充满了空的 JLabels 或 JButtons(一个月中的几天)。JComboBoxes 链接到 ActionListeners,它检测用户更改信息(由 System.out.print 语句确认)。但是,发生这种情况后,我找不到“重绘”JPanel 的方法。被调用的方法完全创建了一个新的 JPanel 并添加了新的 JLabels/JButtons,但在此之后 JFrame 上的任何内容都不会更新。我尝试在整个 JPanel(包括 JComboBoxes 和 BorderLayout 中它下方的网格)、只有网格的 JPanel 和 JFrame 上使用重绘和重新验证,但没有任何反应。
// This code is within the build() method that builds the GUI.
// This method adds the centerPanel into the mainPanel
yearChoice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int i = yearChoice.getSelectedIndex();
if (i >= 0) {
yy = Integer.parseInt(yearChoice.getSelectedItem()
.toString());
//System.out.println("Year=" + yy);
compute();
}
}
});
private void compute(){
elements = new int[6][7];
// OMITTED is the code that determines whether a cell in the array should be an empty
// JLabel or a JButton. This code is based on the Calendar, and does work properly,
// but I can't figure out how to get the new Month/Year to show up on a new Panel
centerPanel = new JPanel(new GridLayout(7, 7));
JLabel sunday = new JLabel("S"),
monday = new JLabel("M"),
tuesday = new JLabel("T"),
wednesday = new JLabel("W"),
thursday = new JLabel("Th"),
friday = new JLabel("F"),
saturday = new JLabel("S");
centerPanel.add(sunday);
centerPanel.add(monday);
centerPanel.add(tuesday);
centerPanel.add(wednesday);
centerPanel.add(thursday);
centerPanel.add(friday);
centerPanel.add(saturday);
for(int i = 0; i < 6; i++){
for(int j = 0; j < 7; j++){
if(elements[i][j] == -1){
centerPanel.add(new JLabel(" "));
}else{
centerPanel.add(new JButton("" + elements[i][j]));
}
}
}
// Here is where I attempt to repaint the centerPanel for the JPanel, but it
// doesn't work
}