刷新JPanel
我需要在 JPanel 上显示不同的绘图。 我已将图形文件放入数组中,但是当我使用按钮更改它时,JPanel 仅显示第一个图形,而不会更改为下一个图形...
我已调用 panel.revalidate(),但它不起作用。
这是我使用但不起作用的代码段。 JPanel 显示是静态的。
String[] a = {"image1.txt","image2.txt","image3.txt"};
List<String> files = Arrays.asList(a);
public void actionPerformed(ActionEvent e) {
if (e.getSource() == answer1){
fileNumber++;
//call other class for painting (files=array files, fileNumber=index of the array)
draw = new drawingPanel(files,fileNumber);
panel.add(draw);
}
panel.revalidate();
panel.repaint();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试保留对 DrawingPanel 的引用并调用 remove() 在现有的绘图面板上,然后重新添加它。 根据 JPanel JavaDoc,布局默认情况下是 FlowLayout - 这不会按照您的预期替换图像,但会将下一个绘图面板放置在上一个绘图面板的右侧。 (调整窗口大小时会发生什么?)
顺便问一下,如何处理超过数组中最后一个图像的情况?
You might try keeping a reference to your drawingPanel and calling remove() on the existing drawingPanel before re-adding it. According to the JPanel JavaDoc, the layout is FlowLayout by default - which will not replace the image like you are intending, but will instead place the next drawingPanel to the right of the previous one. (what happens when you resize the window?)
By the way, how do you handle the case where you get past the last image in the array?
您一次只显示一张图纸吗? 如果是这样,您可能想尝试使用 CardLayout,这样您就可以轻松地在绘图之间切换。 请参阅 http://java.sun.com/docs/books /tutorial/uiswing/layout/card.html 为例。
前几天我遇到了类似的问题,试图根据用户选择的 JTabbedPane 选项卡在 UI 上动态显示不同的按钮。 CardLayout 就是让事情变得简单的东西。
Are you only displaying one drawing at a time? If so, you may want to try using a CardLayout, so you can switch between drawings easily. See http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html for an example.
I had a similar issue the other day attempting to dynamically display different buttons on my UI depending which tab of a JTabbedPane the user picked. CardLayout was just the thing to make things easy.