使JtextPane看起来像电子书

时间:2012-02-06 13:35:56

标签: java swing paging jtextpane

我有一个使用Netbeans的文本编辑器,我将文本加载到JtextPane。如果文字太大,你可以在水平滚动的帮助下阅读它。有没有办法将文本分成24行的页面,例如,这样每个页面都可见而不滚动,并使用下一页按钮来更改页面(像电子书一样)?

1 个答案:

答案 0 :(得分:1)

使用JTextArea更容易,因为您可以轻松指定每次滚动到新页面时要显示的行数。

基本解决方案是将文本区域添加到滚动窗格,然后隐藏滚动条。然后,您可以使用垂直滚动条的默认操作来为您滚动。下面的代码使用Action Map Action博客条目中的代码轻松创建可添加到JButton的Action:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class TextAreaScroll extends JPanel
{
    private JTextArea textArea;

    public TextAreaScroll()
    {
        setLayout( new BorderLayout() );

        textArea = new JTextArea(10, 80);
        textArea.setEditable( false );

        JScrollPane scrollPane = new JScrollPane( textArea );
        scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_NEVER );
        add(scrollPane);

        JButton load = new JButton("Load TextAreaScroll.java");
        load.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    FileReader reader = new FileReader( "TextAreaScroll.java" );
                    BufferedReader br = new BufferedReader(reader);
                    textArea.read( br, null );
                    br.close();
                }
                catch(Exception e2) { System.out.println(e2); }
            }
        });
        add(load, BorderLayout.NORTH);

        //  Add buttons to do the scrolling

        JScrollBar vertical = scrollPane.getVerticalScrollBar();

        Action nextPage = new ActionMapAction("Next Page", vertical, "positiveBlockIncrement");
        nextPage.putValue(AbstractAction.MNEMONIC_KEY, KeyEvent.VK_N);
        JButton nextButton = new JButton(nextPage);

        Action previousPage = new ActionMapAction("Previous Page", vertical, "negativeBlockIncrement");
        previousPage.putValue(AbstractAction.MNEMONIC_KEY, KeyEvent.VK_N);
        JButton previousButton = new JButton(previousPage);

        JPanel south = new JPanel();
        add(south, BorderLayout.SOUTH);
        south.add( previousButton );
        south.add( nextButton );
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TextAreaScroll());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}