JEdi​​torPane里面的JScrollPane没有显示滚动条

时间:2014-01-17 14:29:49

标签: java swing jeditorpane jscrollbar

我正在尝试在JScrollPane中嵌入一个网页,该网页位于一个JFrame内部的矩形JEditorPane中,就像在HTML中一样,你有一个网页,然后在网页的某个地方有一个小矩形,其中有一个iframe另一个网页。我使用setBounds定义矩形的原因是因为矩形小于实际窗口,因为窗口中还有其他元素。

        JEditorPane web = new JEditorPane();
    web.setEditable(false);  

    try {
      web.setPage("http://www.example.com");
    }catch (IOException e) {
      web.setContentType("text/html");
      web.setText("<html>Could not load</html>");
    } 
    final JScrollPane scrollPane = new JScrollPane(web);     
    getContentPane().add(scrollPane);
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
           public void run() { 
               scrollPane.getVerticalScrollBar().setValue(0);
           }
        });
    scrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(250, 145));
    scrollPane.setMinimumSize(new Dimension(10, 10));
    rweb = new Rectangle(20, 20, 1150, 600);
    web.setBounds(rweb);
    window.add(web);

2 个答案:

答案 0 :(得分:3)

我简化了你的代码。以下作品。

你有许多额外的陈述会让事情变得复杂,例如两次添加web(一次是滚动,一次是JFrame)。

另一个例子是scrollPane.getVerticalScrollBar().setValue(0);。默认情况下,滚动条从零开始。

import java.awt.Dimension;
import java.io.IOException;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

public class webPane extends JFrame {

    public static void main(String args[])
    {
         webPane e = new  webPane();
         e.setVisible(true);         
    }


    public webPane() {

        JEditorPane web = new JEditorPane();
        web.setEditable(false);

        try {
            web.setPage("http://www.cnn.com");
        } catch (IOException e) {
            web.setContentType("text/html");
            web.setText("<html>Could not load</html>");
        }

        final JScrollPane scrollPane = new JScrollPane(web);
        getContentPane().add(scrollPane);
        this.setBounds( 0, 0, 200, 200);

    }

}

答案 1 :(得分:2)

您为什么使用setBounds()?这会使您的JEditorPane大小绝对,即不可调整大小,JScrollPane只有在可调整大小时才有效。删除setBounds()

此外,您要将JEditorPane添加到您的窗口而不是JScrollBar,因此您正在跳过JScrollBar的功能。

enter image description here

所以只需更改最后一行就可以解决问题

//rweb = new Rectangle(20, 20, 1150, 600);
//web.setBounds(rweb);
window.add(scrollPane);