簡體   English   中英

Swing:限制部件的移動時,如何防止部件的閃爍和“振動”?

[英]Swing: How can I prevent flickering and “vibrating” of a component, when restricting its movement?

我需要限制JPanel內部組件(JInternalFrame)的移動。
更確切地說:組件在用戶拖動時只能沿一個軸移動。

我試圖通過添加一個組件偵聽器並在每次組件移動時重置一個軸的位置來實現。 但是它“振動”(在拖動過程中快速移動)。

我什至寫了一個自定義的布局管理器,並沒有幫助!

我想,問題是:組件實際移動之后,布局管理器和偵聽器都處理了移動事件,對嗎?

有什么建議么?

在傳遞事件之前,我應該(可以)攔截某個事件並對其進行修改嗎?

沒有需要攔截的“事件”。 一旦Swing處理了鼠標事件,它就會告訴組件移動-在這里您可以調整移動值。

move,setLocation和resize都只是setBounds的包裝。 擴展JInternalFrame,重寫setBounds()方法,並在調用super.setBounds()之前忽略x的新值(如果需要水平移動,則忽略y)。

import javax.swing.JInternalFrame;
public class VerticalOnlyFrame extends JInternalFrame {

    public void setBounds(int x, int y, int width, int height) {
            super.setBounds(getBounds().x, y, width, height);
    }

}

那應該可以解決您的示例,盡管查看JRE代碼setBounds()實際上是不推薦使用的reshape()方法的包裝,因此,如果您感覺很勇敢,請重寫reshape()。

您可能想要子類化InternalFrameUI。 我在BasicInteralFrameUI.BorderListener.mouseDragged(event) (版本1.129中的第885行BasicInteralFrameUI.BorderListener.mouseDragged(event)看到了對getDesktopManager().dragFrame(frame, newX, newY);

您可以擴展BasicInternalFrameUI以返回自定義DesktopManager (擴展為DefaultDesktopManager ),其中在dragFrame()測試框架的身份並調整軸。

編輯:

考慮一下,您是對的-它太復雜了。 由於內部框架的UI DesktopManager JDesktopPaneDesktopManager ,因此可以在此處進行設置。 這是一個POC:

public Demo() {
        JFrame frame = new JFrame();
        frame.setSize(300,300);
        JDesktopPane df = new JDesktopPane();
        DesktopManager dm = df.getDesktopManager();
        df.setDesktopManager(new DefaultDesktopManager(){
               public void dragFrame(JComponent f, int newX, int newY) {
                  super.dragFrame(f, newX, 5);
               }

        });
        JInternalFrame jif = new JInternalFrame("test ");
        jif.setLocation(5, 5);
        jif.setSize(150,100);
        jif.setVisible(true);
        df.add(jif);
        frame.setContentPane(df);
        frame.setVisible(true);
}

暫無
暫無

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

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