Java - 在调整大小时重新验证JFrame

时间:2016-02-09 12:24:33

标签: java swing jframe

我正在尝试在按钮点击时调整JFrame的大小,代码运行良好(但我不知道这是否是实现此目的的最佳方式)。

但问题是: 调整大小时,JFrame会慢慢重新验证。 GIF可以解释究竟发生了什么:

GIF Picture of the problem

这段代码是:

chatButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new Thread (new Runnable() {
                    public void run(){
                        int width = frame.getWidth();
                        int height = frame.getHeight();
                        int buttonWidth = chatButton.getWidth();
                        if (frame.getWidth() < 1150) {  
                            while (frame.getWidth() < 1150) {
                                width = frame.getWidth();
                                frame.setSize(width + 2 , height);
                                chatButton.setLocation(width - buttonWidth , 0);
                                frame.invalidate();
                                frame.validate();
                            }
                        } else {
                            while (frame.getWidth() > 897) {
                                width = frame.getWidth();
                                frame.setSize(width - 2 , height);
                                chatButton.setLocation(width - buttonWidth , 0);
                                frame.invalidate();
                                frame.validate();
                            }
                        }   
                    }
                }).start(); 
            }
        });

我把它放在Runnable中,因为在调整大小结束之前它没有重新验证。

我也尝试了repaint()revalidate(),但他们根本没有解决问题。

我该怎么办?

提前致谢。

1 个答案:

答案 0 :(得分:0)

这是因为您从非摆动螺纹调整摆动组件的尺寸。这将导致窗口的大小与组件的实际移动不同步。通过使内部代码在计时器上运行每隔50毫秒启动一次,您可以在没有抖动的情况下获得平滑打开。

timer = new Timer(50, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int width = frame.getWidth();
        int height = frame.getHeight();
        int buttonWidth = chatButton.getWidth();
        if(frame.getWidth() < 1150) {
            width = frame.getWidth();
            frame.setSize(width + 2 , height);
            chatButton.setLocation(width - buttonWidth , 0);
            frame.invalidate();
            frame.validate();
         } else {
            ((Timer)e.getSource()).cancel()
         } 
     });
timer.setInitialDelay(0);
timer.start(); 

以上代码是打开屏幕时如何执行此操作的示例,您需要使用相同的逻辑进行关闭。

相关问题