Java中的JPanel不是在JFrame中显示,可能并发问题? [英] Java, JPanel not displaying in JFrame, possible concurrency issue?

查看:160
本文介绍了Java中的JPanel不是在JFrame中显示,可能并发问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4幅是由所包含一个JPanel中Jbutton中的二维数组的向量。我试图把这些东西加到一个JFrame,这样循环时,他们会显示动画。

我有,当我手动增加它的作品的add方法,但是当我把它放在一个for循环,如果它没有被粉刷一帧保持空白。终端打印正确的索引号。

 公共无效addNewFrame()抛出InterruptedException的{
    对(INT I = 0; I&小于10;我++){
        如果(指数== 3){
            的System.out.println(索引);
            删除(model.getFrame(3));
            重新验证();
            重绘();
            索引= 0;
            添加(model.getFrame(指数),BorderLayout.CENTER);
            重新验证();
            重绘();
            视频下载(300);
        }其他{
            的System.out.println(索引);
            删除(model.getFrame(指数));
            重新验证();
            重绘();
            指数++;
            添加(model.getFrame(指数),BorderLayout.CENTER);
            重新验证();
            重绘();
            视频下载(300);
        }
    }

难道这是一个并发的问题?我应该添加按钮的二维数组的JPannel这是在它自己的线程中运行?


解决方案

  

循环何时会显示动画。


不要使用Thread.sleep()方法来试图控制动画。

动画应该使用摇摆定时器来完成。

此外,每当我看到code,它删除/添加它几乎总是错的组件。相反,你应该使用 CardLayout 。从上面还有教程对如何使用CardLayout的部分。

I have a Vector of 4 Frames that consist of a 2D array of JButtons that is contained within a JPanel. I am trying to add these to a JFrame so that they will display an animation when looped.

I have an add method that works when I increment it manually, however when I put it in a for loop the frame stays blank as if it has not been repainted. The terminal prints the correct index numbers.

public void addNewFrame() throws InterruptedException {
    for (int i = 0; i < 10; i++) {
        if (index == 3) {
            System.out.println(index);
            remove(model.getFrame(3));
            revalidate();
            repaint();
            index = 0;
            add(model.getFrame(index), BorderLayout.CENTER);
            revalidate();
            repaint();
            Thread.sleep(300);
        } else {
            System.out.println(index);
            remove(model.getFrame(index));
            revalidate();
            repaint();
            index++;
            add(model.getFrame(index), BorderLayout.CENTER);
            revalidate();
            repaint();
            Thread.sleep(300);
        }
    }

Could this be a concurrency issue? Should I be adding the 2D array of buttons to the JPannel which is running in it's own thread?

解决方案

they will display an animation when looped.

Don't use Thread.sleep() to attempt to control animation.

Animation should be done by using a Swing Timer.

Also, whenever I see code that does remove/add of a component it is almost always wrong. Instead you should be using a CardLayout. The tutorial from above also has a section on How to Use CardLayout.

这篇关于Java中的JPanel不是在JFrame中显示,可能并发问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆