Java 刷新 JPanel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/670274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refresh JPanel
提问by Jessy
I need to display different drawings on a JPanel. I have put the drawing files into an array, but when I changed it using a button, the JPanel only displays first drawing and doesn't change to the next drawing...
我需要在 JPanel 上显示不同的图纸。我已将绘图文件放入一个数组中,但是当我使用按钮更改它时,JPanel 仅显示第一张绘图而不会更改为下一张绘图...
I have called panel.revalidate(), but it doesnt work.
我已经调用了 panel.revalidate(),但它不起作用。
This is the segment of the code that I used but not working. The JPanel display was static.
这是我使用但不起作用的代码段。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();
}
采纳答案by mpontillo
You might try keeping a reference to your drawingPanel and calling remove()on the existing drawingPanel before re-adding it. According to the JPanelJavaDoc, the layout is FlowLayoutby 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?)
您可以尝试保留对您的绘图面板的引用,并在重新添加之前在现有的绘图面板上调用remove()。根据JPanelJavaDoc,默认情况下布局是FlowLayout- 它不会像您想要的那样替换图像,而是将下一个绘图面板放置在前一个绘图面板的右侧。(调整窗口大小时会发生什么?)
By the way, how do you handle the case where you get past the last image in the array?
顺便说一句,您如何处理超过数组中最后一个图像的情况?
回答by ssakl
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.htmlfor an example.
您一次只显示一张图吗?如果是这样,您可能想尝试使用 CardLayout,这样您就可以轻松地在绘图之间切换。有关示例,请参见http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html。
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.
前几天我遇到了类似的问题,试图根据用户选择的 JTabbedPane 的哪个选项卡在我的 UI 上动态显示不同的按钮。CardLayout 只是为了让事情变得简单。