0

Alright so I'm creating a JTable with fake stocks and corresponding numbers equal to their value. It currently looks like this:
Current table

As you can see, everything is properly spaced and its code is relatively simple:

table = new JTable(data, columnNames);
table.setModel(new DefaultTableModel(
    new Object[][] {
        {"Webnet", "11"},
        {"Clone Corp", "12"},
        {"City Bank", "15"},
        {"Herbmart", "14"},
        {"Digital Systems", "17"},
        {"National Airlines", "10"},
        {"State Power", "16"},
        {"Parkland", "13"},
    },
    new String[] {
        "Stock", "Price"
    }
));
table.setBorder(new MatteBorder(2, 2, 2, 2, (Color) Color.GRAY));

All that does is set the columns and rows and the border. Very simple. However, as you can see, with both of the columns the same width, there's a lot of unnecessary whitespace in the rows with numbers which would not become large enough to require that. How can I make those smaller without changing the other row's size?

Andreas
  • 154,647
  • 11
  • 152
  • 247
larry
  • 13
  • 1
  • There's a lot that goes into answer that type of question, including the font metrics, rendering pipeline and DIP of the output and the variable nature of the data. While it "might" possible to simply use a "magic number", these will come back to byte you very quickly. A "better" solution might be to query the table renderers themselves and then use the "maximum" desirable size as a bases for the column size, maybe something like [this for example](https://stackoverflow.com/questions/15014950/jtable-horizontal-scrollbar-based-on-width-of-one-column/15015445#15015445) – MadProgrammer Dec 30 '18 at 03:36
  • What does the title have to do with the question? – Andreas Dec 30 '18 at 04:31
  • Also, try putting the table in a JScrollPane – MadProgrammer Dec 30 '18 at 05:39

1 Answers1

0

You can set the width of a column like this:

table.getColumn("Price").setMaxWidth(30);
Prasad Karunagoda
  • 2,048
  • 2
  • 12
  • 16