如何换行使用GridBagLayout将JTextPane中的文本换行为布局

时间:2014-05-21 12:55:57

标签: java swing jtextpane gridbaglayout linewrap

我使用带有GridBagLayout的Jpane。在GridBags中我放了一个JTextPane组件。 但是当我调整JFrame的大小时,我无法在JTextPane中包装我的文本。 这是我的代码......

package problems;


import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.*;

public class ScrollbarTest {

private JFrame frame;
private JPanel panel;
private JScrollPane [] scrollpane = new JScrollPane[4];
private JTextPane [] textPane = new JTextPane[4];
private JScrollPane scrollbar;


ScrollbarTest() {
    //initialize jtextarea
    for(int i=0;i<textPane.length;i++) {

        textPane[i]=new JTextPane();            
        textPane[i].setText("xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx | ");
        scrollpane[i] = new JScrollPane(textPane[i]); 
    }

    panel     = new JPanel();
    frame     = new JFrame();

    createList(panel);
    scrollbar = new JScrollPane(panel);

    frame.add(scrollbar);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setSize(new Dimension(400,400));          
} //constructor

//method to easily add components to GridBags
static void addComponent(JPanel panel, 
                         GridBagLayout gbl, 
                         Component c,
                         int x, int y,
                         int width, int height,
                         double weightx, double weighty) {

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridx = x; gbc.gridy = y;
    gbc.gridwidth = width; gbc.gridheight = height;
    gbc.weightx = weightx; gbc.weighty = weighty;
    gbl.setConstraints( c, gbc );
    panel.add( c ); 
}//addComponent

public void createList(JPanel panel) {
    //setting layout: "GridBagLayout"
    GridBagLayout gbl = new GridBagLayout();        
    panel.setLayout(gbl);                        

    //put created components to the gridbags of gridbaglayout
    //                                            x  y  w  h  wx wy
    addComponent( panel, gbl, scrollpane[0]     , 0, 1, 1, 1, 1 ,0  );
    addComponent( panel, gbl, scrollpane[1]     , 0, 2, 1, 1, 1 ,0  );
    addComponent( panel, gbl, scrollpane[2]     , 1, 1, 1, 1, 1 ,0  );
    addComponent( panel, gbl, scrollpane[3]     , 1, 2, 1, 1, 1 ,0  );
} //createList

public static void main (String[] args) {
    new ScrollbarTest();        
} //main

} //end of class

问题出在哪里?

非常感谢提前

1 个答案:

答案 0 :(得分:2)

您在JTextArea上缺少setLineWrap

for(int i=0;i<textArea.length;i++) {
        textArea[i]=new JTextArea();
        textArea[i].setLineWrap(true);
        textArea[i].setText("xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx | ");
    }

修改

  

在JTextPane的情况下,您将创建一个没有的滚动窗格   水平滚动策略并将您的JtextPane设置为其viewPort