簡體   English   中英

Java-在調整大小時重新驗證JFrame

[英]Java - Revalidating a JFrame while being resized

我試圖在單擊按鈕時調整JFrame的大小,代碼運行良好(但我不知道這是否是實現此目標的最佳方法)。

但是問題是:在調整大小時,JFrame會慢慢重新驗證。 GIF可以解釋到底發生了什么:

GIF問題圖片

這段代碼是:

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()但是它們根本沒有解決問題。

我能做什么?

提前致謝。

發生這種情況是因為您從非回轉螺紋調整了回轉零件的尺寸。 這將導致窗口的大小與組件的實際移動不同步。 通過使內部代碼在計時器上運行,tat每隔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(); 

上面的代碼是打開屏幕時如何執行此操作的示例,您需要執行相同的邏輯以關閉屏幕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM