gpt4 book ai didi

java - 为什么 .validate() 不会更新此代码中的 contentPane?

转载 作者:行者123 更新时间:2023-12-01 15:41:42 24 4
gpt4 key购买 nike

我在使用 contentPane 时遇到问题。这是有问题的代码:

public void graph() {
JFrame frame = new JFrame("Graph");
Graph[] graphs = new Graph[timeSlices];
int k = 0;

for (TreeMap<MyPoint, BigDecimal> prevU : prevUs) {
graphs[k] = new Graph(prevU);
k++;
}

// The KeyList handles switching between graphs.
frame.addKeyListener(new KeyList(frame.getContentPane(), graphs));

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(810, 500);
frame.setVisible(true);
}

private class KeyList extends KeyAdapter {
private Container contentPane;
private Graph[] graphs;
private int index;

public KeyList(Container contentPane, Graph[] graphs) {
this.contentPane = contentPane;
this.graphs = graphs;
this.index = 0;

this.contentPane.add(this.graphs[0]);
}

public void keyPressed(KeyEvent e) {
// Go back a time step
if (e.getKeyCode() == KeyEvent.VK_LEFT && index > 0) {
contentPane.remove(graphs[index]);
contentPane.add(graphs[--index]);
contentPane.validate();
System.out.println(index);
}
// Go forward a time step
else if (e.getKeyCode() == KeyEvent.VK_RIGHT && index < timeSlices - 1) {
contentPane.remove(graphs[index]);
contentPane.add(graphs[++index]);
contentPane.validate();
System.out.println(index);
}
// Exit if Esc is hit
else if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
System.exit(0);
}
}

图表只是一个组件,很简单。当我点击向右箭头时,我想用数组中的下一个图形替换当前显示的图形,当我点击向左箭头时,我想用数组中的上一个图形替换当前显示的图形。

奇怪的是,当我击中右侧时,它工作得很好。然而,当我向左点击时,图表并没有改变。索引发生了变化,因此我知道代码正在被访问,但 GUI 没有改变。

现在就做好准备吧。当我注释掉右键的验证行时,左边的验证行大约有一半的时间可以工作。那里发生了什么事?如果您想自己运行并查看(仅一个文件),那么这是其余的代码:http://pastebin.com/qWxWrypK 。我当前使用的起始参数是 T=1、dt=.01、L=1、h=.05。

我正在研究它,我认为这可能是因为 JFrame 的 contentPane 实际上是一个 JPanel,但这种思路没有得到任何结果......

感谢您的帮助

编辑:

所以我仍在研究它。这是另一件奇怪的事情。如果我将 KeyList 类中的索引设置为 timeSlices-1 (基本上获取图形数组中的最后一个图形),然后我点击左侧,它就可以了!但是,现在右派却没有了!数组或其他东西一定发生了一些奇怪的事情,因为索引变化得很好。嗯。

编辑:

阵列出现问题。由于某种原因,图表只能使用一次。也许它在移除时被破坏了?或者类似的东西......

最佳答案

不要尝试将面板删除/添加到容器中,而是使用 CardLayout就是为此目的而设计的。

另外,不要使用 KeyListener。相反,您应该使用 Key Bindings 。然后,您只需将下一个/上一个键绑定(bind)到卡片布局的下一个/上一个方法即可。

关于java - 为什么 .validate() 不会更新此代码中的 contentPane?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7937167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com