I have a following piece of code which uses JTextArea to display some text,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.DefaultCaret;
public class TextPane extends JFrame{
public static TextPane instance;
//private static JTextPane pane = new JTextPane(); //Uncomment to see alignment issue
private static JTextArea pane = new JTextArea(); // alignment works fine
private static JScrollPane scroll = new JScrollPane();
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TextPane.getInstance().init();
}
});
}
private static TextPane getInstance() {
if(null == instance){
instance = new TextPane();
}
return instance;
}
private void init() {
pane.setFont(new Font("Courier new", Font.PLAIN, 12));
pane.setLayout(new BorderLayout());
pane.setFocusCycleRoot(true);
pane.setFocusTraversalKeysEnabled(false);
pane.setBackground(Color.black);
pane.setForeground(Color.white);
pane.setCaretColor(Color.green);
pane.setDragEnabled(false);
pane.setText("IOC_CONFUG_MMM.lag hkess.lag\t\t papdifs.lag\r\nMemSys.lag.txt\t eol.lag1\t\t papdifs.lag2\r\nopp.lag\t\t eol.lag2\t\t papm_by.lag1\r\n");
DefaultCaret caret = (DefaultCaret) pane.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
scroll.setViewportView(pane);
add(scroll);
setTitle("Test");
setSize(800 , 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);
}
}
There was an issue in alignment of the setText string initially however after i add font as Courier New i got it resolved(if i remove setFont alignment will not work.)
recently due to some requirements i changed from JtextArea to JTextPane , now with same piece of code the text doesn't align properly in JTextPane but if i change it to JTextArea alignment works fine.
I couldn't understand this behaviour. How can i achieve the alignment in JTextPane. please help.
The JTextPane
(or the editor kit you are using implicitly) has a different default behavior regarding tab placement which stems from the fact that it is intended to contain far more complex content than a JTextArea
. You can create your desired simple fixed-width font tab placement manually and set it explicitly. Just insert the following lines right before invoking setText(…);
on your pane
:
int w=pane.getFontMetrics(pane.getFont()).charWidth(' ');
TabStop[] stops={ new TabStop(0), new TabStop(w*8), new TabStop(w*16),
new TabStop(w*24), new TabStop(w*32), new TabStop(w*40), new TabStop(w*48),
new TabStop(w*56), new TabStop(w*64), new TabStop(w*72), new TabStop(w*80) };
MutableAttributeSet attrs=new SimpleAttributeSet();
StyleConstants.setTabSet(attrs, new TabSet(stops) );
pane.setParagraphAttributes(attrs, false);