Bober02
Bober02

Reputation: 15351

JTable Stretching to the size of ScrollPane

The following component is later added to the JFrame, but it does does not stretch the JTable as I stretch the frame to fill up the scrollPane:

public class TableView extends JPanel {

  public TableView(TableModel model) {

    JTable table = new JTable(model) {
        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            TradeTableModel model = (TradeTableModel) getModel();
            if ((Boolean) model.getValueAt(row, model.findColumn("Select"))) {
                Side s = (Side) model.getValueAt(row, model.findColumn("Side"));
                if (s == Side.BUY)
                    c.setBackground(Color.BLUE);
                else
                    c.setBackground(Color.red);
            } else {
                c.setBackground(Color.white);
            }
            return c;
        }
    };
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);
    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);
  }

}

I added:

super(new GridLayout(1, 0));

and it fixed the problem. But why is the layout required? Isn't there simply a default layout that would be instantiated in the case of calling super()? I simply want to know what stops the table to stretch to the size of the scroll pane in the first version

Edit: fixed only code format, but must add some text to submit :/

Upvotes: 0

Views: 2437

Answers (2)

Walter Laan
Walter Laan

Reputation: 2976

Isn't there simply a default layout that would be instantiated in the case of calling super()?

There is and it is a FlowLayout (you can look at the JPanel constructor javadoc or source to see that for yourself). FlowLayout gives the components its preferred size and does not stretch it.

Instead of a GridLayout you could also use a BorderLayout and add to the CENTER.

Upvotes: 2

sakthisundar
sakthisundar

Reputation: 3288

try adding

table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF )

in your snippet before adding the JTable instance to the scroll pane.

Upvotes: 1

Related Questions