【发布时间】:2011-10-29 05:22:15
【问题描述】:
我在使用 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);
}
}
Graph 只是一个组件,很简单。当我点击右箭头时,我想将当前显示的 Graph 替换为数组中的下一个,当我点击左箭头时,我想将 Graph 替换为数组中的前一个。
奇怪的是,当我右击时,它工作得很好。但是,当我向左击时,图表不会改变。索引发生了变化,因此我知道正在访问代码,但 GUI 没有改变。
现在为此做好准备。当我注释掉右键的验证行时,左键将工作大约一半的时间。那里发生了什么?如果您想亲自运行并查看(只有一个文件),这是其余代码:http://pastebin.com/qWxWrypK。我目前使用的起始参数是 T=1, dt=.01, L=1, h=.05。
我正在研究它,我认为这可能是因为 JFrame 的 contentPane 确实是 JPanel,但这种思路没有得到任何地方......
感谢您的帮助
编辑:
所以我仍在使用它。这是另一个奇怪的事情。如果我将 KeyList 类中的索引设置为 timeSlices-1(基本上是在 graphs 数组中获取最后一个 Graph),然后我点击左键,它就可以工作了!但是,现在权利没有!数组或其他东西必须发生一些奇怪的事情,因为索引变化得很好。嗯。
编辑:
数组出了点问题。由于某种原因,图表只能使用一次。也许它在移除时被破坏?或者类似的东西......
【问题讨论】:
-
将运行程序的参数值添加到您的帖子中。没有它们,我什至无法启动您的程序。
-
对不起。忘了我是这样做的(我一开始就把它们硬编码了)。
标签: java swing jframe containers validation