Here is some old code I had lying around that may help:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class ScrollingScrollPane extends JScrollPane implements ActionListener
{
private int scrollOffset;
private Timer timer;
private boolean firstTime = true;
private int locationY;
public ScrollingScrollPane(JComponent component, int delay, int scrollOffset)
{
super(component);
this.scrollOffset = scrollOffset;
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
component.setVisible( false );
component.setSize( component.getPreferredSize() );
getViewport().setBackground( component.getBackground() );
getViewport().setLayout( null );
timer = new Timer(delay, this);
}
public void startScrolling()
{
locationY = getViewport().getExtentSize().height;
JComponent component = (JComponent)getViewport().getView();
component.setVisible( true );
component.setLocation(0, locationY);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
JComponent component = (JComponent)getViewport().getView();
locationY -= scrollOffset;
Dimension d = getViewport().getExtentSize();
component.setBounds(0, locationY, d.width, d.height);
// component.setLocation(0, locationY);
// component.setSize( getViewport().getExtentSize() );
// System.out.println(locationY);
if (component.getPreferredSize().height + locationY < 0)
timer.stop();
}
public static void main(String[] args)
{
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, 0, center, false);
SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setFontSize(keyWord, 16);
StyleConstants.setBold(keyWord, true);
SimpleAttributeSet red = new SimpleAttributeSet();
StyleConstants.setForeground(red, Color.RED);
try
{
doc.insertString(doc.getLength(), "In a Galaxy", keyWord );
doc.insertString(doc.getLength(), "
", null );
doc.insertString(doc.getLength(), "
far", red );
doc.insertString(doc.getLength(), "
", null );
doc.insertString(doc.getLength(), "
far", red );
doc.insertString(doc.getLength(), "
", null );
doc.insertString(doc.getLength(), "
away", red );
doc.insertString(doc.getLength(), "
", null );
doc.insertString(doc.getLength(), "
...", null );
}
catch(Exception e) {}
ScrollingScrollPane scrollPane = new ScrollingScrollPane(textPane, 50, 1);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add( scrollPane );
// frame.setResizable( false );
frame.setSize(300, 300);
frame.setVisible(true);
scrollPane.startScrolling();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…