使用 ParagraphAttribute 控制行之间的空间SpaceBelow
。您可以使用 4 行或更少的代码来完成此操作(请参见下面的示例)。您将需要使用 aJTextPane
来使用这些 ParagraphAttributes(但JTextPane
和 JTextArea 非常相似,您应该不会注意到差异)。
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class LineSpacingExample extends Box{
JTextPane modifiedTA;
//Modify this to whatever spacing you want between the rows.
static final float spaceBelow = 5.0f;
//Font height - automatically calculated by code below
int fontHeight = 0;
public LineSpacingExample(){
super(BoxLayout.X_AXIS);
//Demonstrating that the spacing is predictable
final JPanel leftBox = new CustomBox();
add(leftBox);
//Sets the amount of space below a row (only code you need to add)
DefaultStyledDocument pd = new DefaultStyledDocument();
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setSpaceBelow(sas, spaceBelow);
pd.setParagraphAttributes(0, pd.getLength(), sas, false);
modifiedTA= new JTextPane(pd);
add(modifiedTA);
//Calculates the font height in pixels
fontHeight = modifiedTA.getFontMetrics(modifiedTA.getFont()).getHeight();
}
/**
* @param args
*/
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new LineSpacingExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//EXTRA! Paints the left hand side box - to show that the spacing is predictable in pixels
public class CustomBox extends JPanel{
public CustomBox() {
super();
setOpaque(true);
setBackground(Color.orange);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int height = getSize().height;
int drawLocation = 2; //To account for padding on the TextPane
int row = 1;
while(drawLocation < height){
//Drawing the text row background
g.setColor(Color.blue);
g.fillRect(0, drawLocation, 50, fontHeight);
//Drawing the text row number
g.setColor(Color.white);
g.drawString(Integer.toString(row++), 0, drawLocation+14);
drawLocation += fontHeight;
//Drawing the space row
g.setColor(Color.green);
g.fillRect(0, drawLocation, 50, (int)spaceBelow);
drawLocation += spaceBelow;
}
}
};
}