JTable不会跨越JFrame的边界

时间:2014-10-11 00:11:23

标签: java swing layout-manager gridbaglayout

我无法使表格跨越JFrame边框。我尝试使用setMinimumSize,但它没有用。我错过了什么?

ADDED:我对将JScrollPane添加到表中感兴趣。我只是想知道如何使GridBagLayout将特定组件的大小调整为JFrame的边界。

public class Ost extends JFrame{
    OstBridge bridge;
    public Ost() {
        Container cp=this.getContentPane();
        GridBagConstraints c=new GridBagConstraints();
        cp.setLayout(new GridBagLayout());

        // Add button
        JButton b1=new JButton("Button");
        c.gridx=0;
        c.gridy=0;
        c.insets=new Insets(20,0,20,0);
        cp.add(b1,c);

        // Table data
        String[] columns={"Album","Url"};
        Object[][] data={
                {"test1","tes2"}
        };
        // Add Table
        JTable table=new JTable(data,columns);
        c.gridx=0;
        c.gridy=1;
        c.weightx=1;
        c.weighty=1;
        c.gridwidth=c.REMAINDER;
        table.setBackground(Color.RED);
        table.setMinimumSize(new Dimension(400,400));
        cp.add(table, c);

        // Show All
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(320, 240);
        this.setTitle("Test");
        this.setVisible(true);


    }

这就是我得到的:

http://fjjf.com.ve/i1.png

这就是我想要的:

http://fjjf.com.ve/i2.png

1 个答案:

答案 0 :(得分:1)

在表格的约束中,我应该使用GridBagConstraints.fill

    // Add Table
    JTable table=new JTable(data,columns);
    c.gridx=0;
    c.gridy=1;
    c.weightx=1;
    c.weighty=1;
    c.gridwidth=c.REMAINDER;

    c.fill=GridBagConstraints.HORIZONTAL; // this line solves the problem

    table.setBackground(Color.RED);
    table.setMinimumSize(new Dimension(400,400));
    cp.add(table, c);

希望这个答案可以帮助那些试图以第一的方式为我提供第一步的人! :)