给JEditorPane添加滚动条

添加滚动条

由于比较的菜的缘故,在实现添加滚动条的时候,百度了许久都没能搞出来,很伤心。

所以,记录一下添加滚动条的方法基本方法和细节:

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class WindowTemp extends JFrame{
	JEditorPane ed;
	JScrollPane jsp;
	public WindowTemp() {
		//设置主界面的大小,以及布局方式
		this.setSize(new Dimension(700,500));
		this.setLayout(new BorderLayout());
		
		//给JEditorPane添加滚动条
		ed=new JEditorPane();
		jsp=new JScrollPane(ed);
		jsp.setPreferredSize(new Dimension(500,500));
		
		//设置垂直水平滚动条时刻显示
		jsp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		
		//添加板块进去,并设置位置位置
		this.add(jsp,BorderLayout.CENTER);
		
		//设置可见,关闭时退出程序
		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	public static void main(String[] args) {
		new WindowTemp();
	}

}

有个小细节:

为JEditorPane添加滚动条,需要先创建JEditorPane的对象,然后在创建JScrollPane对象的时候,把JEditorPane对象加进去。例如:

           ed=new JEditorPane();
           jsp=new JScrollPane(ed);

这样,你就为JEditorPane对象添加了滚动条了。

接着,this.add(jsp,BorderLayout.CENTER);则把带滚动条的JEditorPane对象添加进jframe里面了。这里需要注意的是:

添加的是JScrollPane对象,而不是JEditorPane对象。

ed是JEditorPane对象,jsp是JScrollPane对象。就是说:

如果你添加ed的话,显示的则是无滚动条的JEditorPane;而添加jsp的话,才会显示有滚动条的JEditorPane。

你可能感兴趣的:(笔记)