小虫玩電腦
2009-04-09
如何讓設定 FlowLayout 的 JPanel 有 ScrollBar
因為 JDK 的
bug
,設定 FlowLayout 的 JPanel 沒辦法在 JScrollPane 裡面正確呈現出 ScrollBar,因此要自己實作
Scrollable
來達到這個效果。
import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Rectangle; import javax.swing.JPanel; import javax.swing.Scrollable; import javax.swing.SwingConstants; public class ScrollableFlowPanel extends JPanel implements Scrollable { public void setBounds(int x, int y, int width, int height) { super.setBounds(x, y, getParent().getWidth(), height); } public Dimension getPreferredSize() { return new Dimension(getWidth(), getPreferredHeight()); } public Dimension getPreferredScrollableViewportSize() { return super.getPreferredSize(); } public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { int hundredth = (orientation == SwingConstants.VERTICAL ? getParent() .getHeight() : getParent().getWidth()) / 100; return (hundredth == 0 ? 1 : hundredth); } public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return orientation == SwingConstants.VERTICAL ? getParent().getHeight() : getParent().getWidth(); } public boolean getScrollableTracksViewportWidth() { return true; } public boolean getScrollableTracksViewportHeight() { return false; } private int getPreferredHeight() { int rv = 0; for (int k = 0, count = getComponentCount(); k < count; k++) { Component comp = getComponent(k); Rectangle r = comp.getBounds(); int height = r.y + r.height; if (height > rv) rv = height; } rv += ((FlowLayout) getLayout()).getVgap(); return rv; } }
測試
import java.awt.*; import javax.swing.*; public class TestScrollableFlowPanel extends JFrame { public static void main( String[] args ) { Runnable doEDT = new Runnable() { public void run() { new TestScrollableFlowPanel(); } }; SwingUtilities.invokeLater( doEDT ); } public TestScrollableFlowPanel() { try { jbInit(); } catch ( Exception e ) { e.printStackTrace(); } this.setSize( 300, 300 ); this.setDefaultCloseOperation( EXIT_ON_CLOSE ); this.setVisible( true ); } private void jbInit() throws Exception { ScrollableFlowPanel panel = new ScrollableFlowPanel(); for ( int k = 0; k < 120; k++ ) panel.add( new JButton( "Button" + k ) ); JScrollPane scroll = new JScrollPane( panel ); this.getContentPane().setLayout( new BorderLayout() ); this.getContentPane().add( scroll, BorderLayout.CENTER ); } }
這問是困擾了我兩天, sun 竟然這麼久都不修復,唉。
沒有留言:
張貼留言
‹
›
首頁
查看網路版
沒有留言:
張貼留言