cerulean

JTextArea->JTextPane 解决文字对齐方式的问题

引子只是个小问题,JTextArea多行文本,想设置文字的对齐方式为居中对齐,却发现死活没有合适有效的方法,又试了JTextField和JLabel,都不理想。搜了一溜够看到JTextPane的解决方法,其实真是有点儿大材小用了。JTextPane里可以设置style,对齐方式、字体字号、颜色等等,并且还可以设置style的作用范围,挺方便的。另外,想把文字区域背景设为透明的也是在API中找了一通,才发现敢情就是setOpacity,呃,对这个单词实在是太不敏感了。。。。

把在coderanch上搜的例子贴在这里吧,以防以后忘了:
import java.awt.*;  
import javax.swing.*;  
import javax.swing.text.*;  
   
public class Styling  
{  
    
public Styling()  
    
{  
        String text 
= "To refer to locations within the sequence, the " +  
                      
"coordinates used are the location between two " +  
                      
"characters.\nAs the diagram below shows, a location " +  
                      
"in a text document can be referred to as a position, " +  
                      
"or an offset. This position is zero-based.";  
   
        SimpleAttributeSet aSet 
= new SimpleAttributeSet();   
        StyleConstants.setForeground(aSet, Color.blue);  
        StyleConstants.setBackground(aSet, Color.orange);  
        StyleConstants.setFontFamily(aSet, 
"lucida bright italic");  
        StyleConstants.setFontSize(aSet, 
18);  
   
        SimpleAttributeSet bSet 
= new SimpleAttributeSet();  
        StyleConstants.setAlignment(bSet, StyleConstants.ALIGN_CENTER);  
        StyleConstants.setUnderline(bSet, 
true);  
        StyleConstants.setFontFamily(bSet, 
"lucida typewriter bold");  
        StyleConstants.setFontSize(bSet, 
24);  
   
        JTextPane textPane 
= new JTextPane();  
        textPane.setText(text);  
        StyledDocument doc 
= textPane.getStyledDocument();  
        doc.setCharacterAttributes(
105, doc.getLength()-105, aSet, false);  
        doc.setParagraphAttributes(
0104, bSet, false);  
   
        JFrame f 
= new JFrame();  
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        f.add(
new JScrollPane(textPane));  
        f.setSize(
400,400);  
        f.setLocation(
200,200);  
        f.setVisible(
true);  
    }
  
   
    
public static void main(String[] args)  
    
{  
        
new Styling();  
    }
  
}
  

posted on 2010-03-10 17:20 cerulean 阅读(7801) 评论(1)  编辑  收藏 所属分类: Java

评论

# re: JTextArea->JTextPane 解决文字对齐方式的问题 2013-11-25 19:44

非常好!!!!非常感谢!!!!!!  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2010年3月>
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

统计

常用链接

留言簿(3)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜