我目前正在用 Java 编写日历。日历本身填写得非常好,月份和年份显示在其下方网格上方的 JComboBox 中。网格本身充满了空的 JLabels 或 JButton(针对一个月中的几天)。 JComboBox 链接到 ActionListener,后者检测用户更改信息(由 System.out.print 语句确认)。但是,发生这种情况后我找不到“重绘”JPanel 的方法。被调用的方法完全创建了一个新的 JPanel 并添加了新的 JLabels/JButtons,但在此发生后 JFrame 上的任何内容都没有更新。我尝试在整个 JPanel(包括 JComboBox 和 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
}
最佳答案
The method being called completely creates a new JPanel and adds in the new JLabels/JButtons, but nothing on the JFrame is updated after this happens. I have attempted using both the repaint and revalidate on the whole JPanel (which includes the JComboBoxes and the grid below it in a BorderLayout), the JPanel with only the grid, and the JFrame, but nothing happens. Does anyone have any ideas what is wrong?
您调用另一个
JPanel
来进行(重新)验证
和重新绘制
更新超出了屏幕上的可见矩形范围,请将
JPanel
放入JScrollPane
如果更新超出可见矩形,您可以调用 JFrame.pack(),但在这种情况下,JFrame 将更改其在屏幕上的尺寸
The method being called completely creates a new JPanel and adds in the new JLabels/JButtons, but nothing on the JFrame is updated after this happens.
为什么要重新创建 JPanel,创建一次并使用 setVisible(false/true)
不要重新创建 JPanel,将这些(两个或三个 JPanel)放入 CardLayout,然后任何更改都将仅在 View 之间切换
为了获得更好的帮助,请尽快发布 SSCCE ,短,可运行,可编译
关于java - 用户输入后重新绘制 JPanels(或 JFrames?)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13283970/