构造JTextArea组件.docVIP

  • 7
  • 0
  • 约1.1万字
  • 约 11页
  • 2018-03-04 发布于河南
  • 举报
构造JTextArea组件

构造JTextArea组件 9-4-1:构造JTextArea组件: 我们可以发现到JTextArea的构造函数和JTextField及JPasswordField的构造函数是相同雷同,而JTextArea多了一个字段的参数 值是因为JTextArea是二维的输入组件,在构造时不仅要设置字段长度也要设置行数。我们来看下面这个范例: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTextArea1{ public static void main(String[] args){ JFrame f=new JFrame(JTextArea1); Container contentPane=f.getContentPane(); contentPane.setLayout(new BorderLayout()); JPanel p1=new JPanel(); p1.setLayout(new GridBagLayout()); GridBagConstraints gbc=new GridBagConstraints(); gbc.anchor=GridBagConstraints.WEST; gbc.insets=new Insets(2,2,2,2); p1.setBorder(BorderFactory.createTitledBorder(构造一般的JTextArea)); JLabel l1=new JLabel(一:); JLabel l2=new JLabel(二:); JLabel l3=new JLabel(三:); JLabel l4=new JLabel(四:); JTextArea t1=new JTextArea(); JTextArea t2=new JTextArea(2,8); JTextArea t3=new JTextArea(JTextArea3); JTextArea t4=new JTextArea(JTextArea4,5,10); t1.setText(JTextArea1);//setText()方法会将原来的内容清除 t2.append(JTextArea2);//append()方法会将设置的字符串接在原来JTextArea内容文字之后. t4.setLineWrap(true);//设置换行 gbc.gridy=1; gbc.gridx=0; p1.add(l1,gbc); gbc.gridx=1; p1.add(t1,gbc); gbc.gridy=2; gbc.gridx=0; p1.add(l2,gbc); gbc.gridx=1; p1.add(t2,gbc); gbc.gridy=3; gbc.gridx=0; p1.add(l3,gbc); gbc.gridx=1; p1.add(t3,gbc); gbc.gridy=4; gbc.gridx=0; p1.add(l4,gbc); gbc.gridx=1; p1.add(t4,gbc); contentPane.add(p1); f.pack(); f.show(); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } } 在JTextArea中我们可以使用setTabSize()方法设置[Tab]键的跳离距离,或是setFont()方法设置字体。当我们输入的文字超过 JTextArea的右边界及下边界时,会看不到接下来打的内容,那该怎么办呢?你可以使用JScrollPane使JTextArea具备滚动的能力, 或是搭配setLineWrap()方法就能让文字自动换行。JTextArea还提供一个setWrapStyleWord()方法,可以???换行的时候不会造成断 字的现象,这在Word或使用OutLook写信时都可以看到这个效果。例如我们在行尾中输入“自动换行”四个字,但此行最多只能在容 纳两个字,因此JTextArea会将此四个字均移到下一行,不会造成“自动”在上行,换行在下行的情形。这在处理英文输入上较为 重要,因为setWrapStyleWord()是利用空白当作是一个字输入的结果。我们来看下面的范例: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTextArea2{ public static voi

文档评论(0)

1亿VIP精品文档

相关文档