There are situations when the (mighty) JTable is too much.
If you just want a JLabel/ JTextArea like component with some columns use a HTML-Table in a JTextPane or in a JEditorPane:
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 ;-)
- the trimming of spaces is utilized
- the second column is growing/ shrinking with the JDialog size because of the omitted width in its td-Tag
- css margins have been thrown in for no special reason
- for a consistent appearance the font of the JLabel has to be fetched from the UIManager and set via CSS
- if you reduce the width of the JDialog the text in the second column is nicely word-wrapped
(ooh, wait! this is a nice feature of HTML)