刷新JPanel

发布于 2024-07-15 18:06:28 字数 637 浏览 4 评论 0 原文

我需要在 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();
}

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...

I have called panel.revalidate(), but it doesnt work.

This is the segment of the code that I used but not working.
The JPanel display was static.

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

明月夜 2024-07-22 18:06:28

您可以尝试保留对 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?

千纸鹤 2024-07-22 18:06:28

您一次只显示一张图纸吗? 如果是这样,您可能想尝试使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文