0

然后我JTable将其添加到JPanel. 然后我将它添加JPanel到一个JFrame被调用的框架中。这frame可以正确显示该表,但是当我最大化窗口时,JPanel仍然保持较小的尺寸。当我最大化框架时,我想JPanel在整个框架中显示。这是我的代码:

import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

@SuppressWarnings("serial")
public class TestClass extends JPanel
{
    public TestClass()
    {
        Vector columnNames = new Vector();
        Vector data = new Vector();


            int columns =3;

            //  Get column names

            columnNames.addElement("Id");
            columnNames.addElement("Name");
            columnNames.addElement("Age");

            //  Get row data

            Vector row = new Vector(columns);
            row.addElement("1");
            row.addElement("Moshi");
            row.addElement("22");

            data.addElement( row );




        //  Create table with database data

        JTable table = new JTable(data, columnNames)
        {
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                    {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane( table );
        add(scrollPane);

    }

    public static void main(String[] args)
    {
        TestClass testClass  = new TestClass(); //**JPanel**
        JFrame frame = new JFrame();
        frame.setSize(500, 600);
        frame.getContentPane().add(testClass); //**add jpanel to frame**
        frame.setVisible(true);
    }
}
4

1 回答 1

1

使用布局管理器,它根据可用大小而不是JPanel's默认大小调整组件大小,默认大小FlowLayout只使用组件的首选大小,例如

setLayout(new GridLayout());
于 2013-09-03T23:03:04.137 回答