2012-02-06 53 views
0

我與Netbeans的文本編輯器,我打開一個文本JTextPane中。如果文字太大,你可以在水平滾動的幫助下閱讀它。有沒有辦法將文本分成24行的頁面,例如,每個頁面都可以看到而不需要滾動,並使用下一頁按鈕來改變頁面像電子書一樣)?讓JTextPane中看起來像電子書

+0

是的,這有可能,通知 - >通過你的手寫代碼,請不要使用內置JComponents -in調色板 – mKorbel 2012-02-06 16:37:53

回答

1

使用JTextArea更容易,因爲您可以輕鬆指定每次滾動到新頁面時要顯示的行數。

基本的解決方案是將文本區域添加到滾動窗格比則隱藏滾動條。然後,您可以使用垂直滾動條的默認操作來爲您進行滾動。下面的代碼使用代碼來自Action Map Action博客條目可以輕鬆地創建,你可以添加到一個JButton的操作:

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(); 
      } 
     }); 
    } 
} 
+0

簡單又好的+1 – mKorbel 2012-02-08 18:32:24

+0

當我顯示我選擇我想成爲一個JTextPane中做一些其他的事情的頁面。有沒有辦法做到這一點? – drew 2012-02-16 00:18:37

+0

我不知道你在問什麼,但我會在9天內回覆你,因爲這個問題對你來說並不重要。 – camickr 2012-02-16 04:30:32

相關問題