[英]Java Swing: JTextArea columns question
How do I put the text in specific columns with jTextArea? 如何使用jTextArea将文本放在特定的列中?
private javax.swing.JTextArea jTextArea1;
jTextArea1.setColumns(4);
jTextArea1.insert(price, 0); //column 1
jTextArea1.insert(cost, 0); //column 2
jTextArea1.insert(quantity, 0); //column etc..
jTextArea1.insert(itemName, 0);
jTextArea1.insert("\n", 0);
There are situations when the (mighty) JTable is too much. 在某些情况下,(强大的)JTable太多了。
If you just want a JLabel/ JTextArea like component with some columns use a HTML-Table in a JTextPane or in a JEditorPane: 如果您只想要类似JLabel / JTextArea的组件并带有一些列,请在JTextPane或JEditorPane中使用HTML-Table:
import java.awt.Font;
import javax.swing.JDialog;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.text.html.HTMLDocument;
public class ColumnsInJTextPane
{
public ColumnsInJTextPane()
{
double price = 124.75;
int quantity = 3;
String itemName = " iPad";
JTextPane t = new JTextPane();
t.setContentType( "text/html" );
StringBuilder text = new StringBuilder( 150 );
text.append( "<html><body>" );
text.append( "<table border='0' style='margin:4px 2px 12px 6px' width='100%'>" );
text.append( "<tr>" + "<td width='30' align='left' valign='top' style='margin-right:8px'>" );
text.append( price );
text.append( "</td>" );
text.append( "<td align='left' valign='top' style='margin-right:8px'>" );
text.append( itemName );
text.append( "</td>" );
text.append( "<td width='20' align='left' valign='top' style='margin-right:8px'>" );
text.append( quantity );
text.append( "</td>" + "</tr>" );
text.append( "<tr>" + "<td>" );
text.append( price * 4 );
text.append( "</td>" );
text.append( "<td>" );
text.append( (((Boolean) itemName.equals( itemName )).toString().concat( itemName )) );
text.append( "</td>" );
text.append( "<td>" );
text.append( quantity / 2 );
text.append( "</td>" + "</tr>" );
text.append( "</table>" );
text.append( "</body></html>" );
t.setText( text.toString() );
//to get a consistent (body) appearance use the font from the Label using a CSS rule (instead of the value in javax.swing.text.html.default.css)
Font font = UIManager.getFont( "Label.font" );
String bodyRule =
"body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize() + "pt; }";
((HTMLDocument) t.getDocument()).getStyleSheet().addRule( bodyRule );
JDialog d = new JDialog();
d.add( t );
d.pack();
d.setVisible( true );
}
public static void main( String[] args )
{
new ColumnsInJTextPane();
}
}
There are some tweaks and tricks in this example which demonstrate how evil HTML really is ;-) 此示例中有一些调整和技巧,它们证明了HTML到底是多么邪恶;-)
列指的是一个字符,因此,如果columns = 4,则表示宽度为4个字符。
The best approach is to use a JTable. 最好的方法是使用JTable。
But if you really want to use a text cmponent you can use a JTextPane and play with tabs. 但是,如果您真的想使用文本cmponent,则可以使用JTextPane并使用选项卡播放。 See my example in JTextPane Tab Size . 请参阅“ JTextPane选项卡大小”中的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.