更換的控制權使用ParagraphAttribute SpaceBelow
你行之間的空間。您可以使用4行代碼或更少的代碼(請參閱下面的示例)。您將需要使用JTextPane
來使用這些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;
}
}
};
}
你可以發表一些代碼嗎? – linski