简体   繁体   English

JTable拉伸到ScrollPane的大小

[英]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: 以下组件后来添加到JFrame中,但是当我拉伸框架以填充scrollPane时,它不会拉伸JTable:

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()? 难道不只是在调用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 :/ 编辑:仅修复了代码格式,但必须添加一些文本以提交:/

Isn't there simply a default layout that would be instantiated in the case of calling super()? 难道不只是在调用super()时会实例化的默认布局吗?

There is and it is a FlowLayout (you can look at the JPanel constructor javadoc or source to see that for yourself). 有一个,它是一个FlowLayout(您可以查看JPanel构造函数javadoc或源代码来亲自查看)。 FlowLayout gives the components its preferred size and does not stretch it. FlowLayout为组件提供其首选的大小,并且不会拉伸它。

Instead of a GridLayout you could also use a BorderLayout and add to the CENTER. 除了GridLayout,您还可以使用BorderLayout并将其添加到CENTER。

try adding 尝试添加

table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF ) table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)

in your snippet before adding the JTable instance to the scroll pane. 在将JTable实例添加到滚动窗格之前,请在您的代码段中单击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM