我有一个JFrame,它包含JScrollPane.JScrollPane本身包含一个派生自JPanel的类.我使用JPanel类在其上绘制Image和一些其他基元.遗憾的是,即使JPanel扩展到JSrollPane大小,也不会出现JScrollPane的滚动条.
我创建了一些运行的测试代码:
这是主要类:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
class ScrolledPane extends JFrame{
private JScrollPane scrollPane; 
public ScrolledPane()
{
    setTitle( "Scrolling Pane Application" );
    setSize( 300, 200 );
    setBackground( Color.gray );
    TestPanel testPanel = new TestPanel();
    testPanel.setLayout( new BorderLayout() );
    scrollPane = new JScrollPane(testPanel);
    this.getContentPane().add(scrollPane, BorderLayout.CENTER);
}
public static void main( String args[] )
{
    // Create an instance of the test application
    ScrolledPane mainFrame  = new ScrolledPane();
    mainFrame.setVisible( true );
}
}
这是从JPanel派生的类的代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics; 
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
public class TestPanel extends JPanel {
private Image groundPlan;
public TestPanel(){
    super();
    this.setBackground(Color.green);
    this.setLayout(new BorderLayout());
    this.groundPlan = Toolkit.getDefaultToolkit().getImage("D:\\EclipseWorkspace\\img.png");
}
public void paint(Graphics graphics) {
    super.paint(graphics);
    if(groundPlan != null) {
        graphics.drawImage(groundPlan, 0, 0, this);
    }
}
}
有趣的是,如果我只是将带有和Image的JLabel插入JScrollpane而不是JPanel,则会出现Scrollbars.这里是这个选项的代码:
public ScrolledPane() //Frame <- Scrollpane <- label <- image 
{
    setTitle( "Scrolling Pane Application" );
    setSize( 300, 200 );
    setBackground( Color.gray );
    JPanel topPanel = new JPanel();
    topPanel.setLayout( new BorderLayout() );
    Icon image = new ImageIcon("D:\\EclipseWorkspace\\img.png");
    JLabel label = new JLabel( image );
    scrollPane = new JScrollPane();
    scrollPane.getViewport().add( label );
    this.getContentPane().add(scrollPane, BorderLayout.CENTER);
}
如果我在JScrollPane中使用JPanel,如果你能说出如何使滚动条出现,我会恭喜你.
关心并感谢Marc