Noob Programmer
Noob Programmer

Reputation: 11

Aligning Text In JtextArea in java

I need to add items in a JtextArea and with its Description and a Price but i have a problem in aligning it. i want an output of this is like

Description          Price
Coffe                $50.00
Bread                $30.00
Egg                  $10.00

but my Program makes like

Description           Price
Coffe           $50
Bread                 $30
Egg                 $20

Anyone pls help me how to Align it?....

txtArea.append( "\n" + desc+"         " + price + "         " + quanty);

Upvotes: 1

Views: 714

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

HTML In a JTextPane rather than JTextArea one could use HTML:

<html><table><tr><th>Description</th><th>....<tr><td>...

With CSS styles the most beautiful, requiring some effort.

String.format With a fixed-size font (monospaced) in a JTextArea one can do:

txtArea.setFont(new Font("monospaced", Font.PLAIN, 12));
txtArea.append(String.format("%-30s %15s %10d\n", desc, price, quanty));
  • %-30s left aligned string
  • %15s right aligned string
  • %10d right aligned integer

Upvotes: 3

Related Questions