JTextPane滚动

时间:2014-08-06 00:49:52

标签: java user-interface scroll jscrollpane jtextpane

我知道有关此主题的问题也有类似的问题,但经过几个小时的研究后,我找不到任何解决方案。

我的问题是为什么我的JTextPane上没有显示滚动条。以下是我的代码:

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import java.awt.BorderLayout;

import javax.swing.JTextPane;

public class OtherNotesWindow extends JFrame{

JTextPane page;
JPanel panel;


public OtherNotesWindow() {
    super("Other Notes Window");
    init();
    page.setFocusable(true);
    this.setSize(400,400);
    this.setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocation(400,400);
}

public void init(){
    panel = new JPanel();
    page = new JTextPane();
    JScrollPane scroll = new JScrollPane(page, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scroll.setViewportView(page);
    panel.add(scroll);
    this.add(page);
}
}

我不知道为什么没有垂直和水平的滚动条都没有显示出来。谁能告诉我为什么?

提前感谢任何回复的人。 :)

2 个答案:

答案 0 :(得分:0)

this.add(page)应为this.add(panel)

答案 1 :(得分:0)

仔细查看您的代码......

// Create a  panel...
panel = new JPanel();
// Create a scroll pane
page = new JTextPane();
// Create a scroll pane with page as the view
JScrollPane scroll = new JScrollPane(page, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// A little redudent as you did this when you created the scoll pane, but what ever
scroll.setViewportView(page);
// Add the scroll pane to the panel
panel.add(scroll);
// Add the page to this...wait what??!
this.add(page);

最后一行是你撤消,它是从page删除JScrollPane而只是添加到JFrame ...没有滚动窗格或任何内容......

您需要将其更改为......

this.add(panel);

this.add(scroll);

请注意,JPanel默认使用FlowLayout,可能不符合您的要求