2017-04-01 85 views
1

我想要有3個可調整大小的水平JPanels。它工作正常,但我不能設置第一個JSlitPane的位置:sp.setDividerLocation(.3);不起作用。在JSplitPane上設置分隔符位置

public class JSplitPanelProva extends JFrame { 

     public JSplitPanelProva() { 
      this.setLayout(new BorderLayout()); 

      JPanel leftPanel = new JPanel(); 
      leftPanel.setBackground(Color.BLUE); 
      JPanel centerPanel = new JPanel(); 
      centerPanel.setBackground(Color.CYAN); 
      JPanel rightPanel = new JPanel(); 
      rightPanel.setBackground(Color.GREEN); 

      JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel); 
      JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel); 

      sp.setOneTouchExpandable(true); 
      sp2.setOneTouchExpandable(true); 


      this.add(sp2, BorderLayout.CENTER); 

      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

      this.setSize(1000, 600); 
      this.setVisible(true); 

      sp.setDividerLocation(.3); 
      sp2.setDividerLocation(.6); 
     } 

     /** 
     * @param args the command line arguments 
     */ 
     public static void main(String[] args) { 
      new JSplitPanelProva(); 

     } 

    } 

我得到這個: enter image description here 有人能幫助我嗎? 謝謝。

回答

1

setDividerLocation(double proportionalLocation)方法的文檔說:

如果拆分窗格沒有正確地實現和在屏幕上,這種方法 不會有任何影響(新的分隔條位置將成爲(目前的規模* proportionalLocation)這是0)。

你能做什麼,而不是使用setDividerLocation(int location)方法是這樣的:

sp.setDividerLocation(300); 
sp2.setDividerLocation(600); 
2

變化:

 sp.setDividerLocation(.3); 
     sp2.setDividerLocation(.6); 

要:

sp2.setDividerLocation(.6); 
    ActionListener splitListener = new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      sp.setDividerLocation(.3); 
     } 
    }; 
    Timer t = new Timer(200, splitListener); 
    t.setRepeats(false); 
    t.start(); 

它將按預期工作。延遲爲GUI重新計算大小提供了時間。

2

它看起來像三件事情需要發生:

  1. 分隔條的位置不能設置直到幀是可見的,需要
  2. 設置在第二分割窗格的位置將第一
  3. 完成需要被添加到的端部上 Event Dispatch Thread (EDT)

下面的代碼將完成所有3

  • 設置第一分割窗格的位置:

    this.setVisible(true); 
    
    sp2.setDividerLocation(.6); 
    
    SwingUtilities.invokeLater(new Runnable() 
    { 
        public void run() 
        { 
         sp.setDividerLocation(.3); 
        } 
    }); 
    

    注意:所有Swing組件都應該在EDT上創建。因此,您還應該使用以下內容創建相框:

    EventQueue.invokeLater(new Runnable() 
    { 
        public void run() 
        { 
         new JSplitPaneProva(); 
        } 
    });