2014-02-16 34 views
2

我有以下的小程序:創建水平包裝和垂直滾動面板

import java.awt.BorderLayout; 
import java.awt.Component; 
import java.awt.FlowLayout; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 

public class ScrollPanePlay extends JFrame 
{ 
    public static void main(String[] args) 
    { 
    ScrollPanePlay frame = new ScrollPanePlay(); 
    frame.setVisible(true); 
    } 

    public ScrollPanePlay() 
    { 
    setDefaultCloseOperation(DISPOSE_ON_CLOSE); 

    JPanel panel = new JPanel(this); 
    panel.setLayout(new FlowLayout(FlowLayout.LEFT)); 
    panel.add(new JLabel("one")); 
    panel.add(new JLabel("two")); 
    panel.add(new JLabel("three")); 
    panel.add(new JLabel("four")); 
    panel.add(new JLabel("five")); 

    JScrollPane scrollPane = new JScrollPane(panel); 
    add(panel, BorderLayout.CENTER); // <== add either panel or scrollpane 
    pack(); 
    } 

} 

如果我添加面板,然後在面板包裝的標籤時,由窗口窄,如預期的FlowLayout。

如果我將面板添加到滾動窗格並將滾動窗格添加到框架,那麼標籤不會換行,因爲scrollPane報告足夠的寬度(我猜)可容納所有標籤,並允許用戶滾動去看他們。

我想滾動的行爲,但只適用於垂直 - 我想用戶選擇他想看到的寬度,並讓滾動條只出現垂直滾動。我怎樣才能做到這一點?

我試着擴展JScrollPane,並從getScrollableTracksViewportWidth()返回true,但是,正如我所料,這不會做我想做的事情,因爲它是我希望事物跟蹤的框架寬度,而不是視口。我試着擴展JPanel並重寫getWidth來返回框架的寬度,但仍然將所有標籤保留在水平行中,即它們退出包裝。有沒有什麼會做到這一點沒有自定義佈局管理器?對我來說,我們需要的是對視口寬度進行編程控制。

+2

這可能是'FlowLayout'本身的問題,請試着看看['WrapLayout'](http://tips4java.wordpress.com/2008/11/06/wrap-layout/)而不是 – MadProgrammer

+0

I不要讓你的目標,因爲一邊不要忘記改變,增加滾動增量 – mKorbel

回答

0

這是一個視口問題。在JScrollPane中,JPanel不會調整大小以適應JScrollPane大小(這就是ScrollPanes存在的原因)。

您可以使用可滾動面板而不是JPanel,並將其設置爲適合最大寬度(在本例中,它適合JScrollPane)。

喜歡的東西:

ScrollablePanel panel = new ScrollablePanel(new BorderLayout()); 
panel.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.FIT); 

檢查這個answer多了幾分一般的答案和鏈接到的.class。