Java6学习笔记21——利用Swing创建表单

时间:2023-01-28 10:56:12

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;

public class TableDemo extends JFrame {
    String columns[] = {
        "Decimal","Binary","English","Sanskrit","Ancient Greek"
        };
    Object cells[][] = {
        { new Integer(1),"1","one","eka","en" },
        { new Integer(2),"10","two","dva","duo" },
        { new Integer(3),"11","three","tri","tri" },
        { new Integer(4),"100","four","catur","tetra" },
        { new Integer(5),"101","five","panca","pente" },
        { new Integer(6),"110","six","sas","hex" },
        { new Integer(7),"111","seven","hepta","septem" },
        { new Integer(8),"1000","eight","asta","octo" },
        { new Integer(9),"1001","nine","nava","ennea" },
        { new Integer(10),"1010","ten","daca","deca" },
        };
    public static void main(String arg[]) {
        new TableDemo();
    }
    public TableDemo() {
        int height;
        int width;
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        } );
        setLocation(150,150);
        Container pane = getContentPane();
        pane.setLayout(null);
        Insets insets = pane.getInsets();

        JTable table = new JTable(cells,columns);
        table.setPreferredScrollableViewportSize(new Dimension(500,70));
        table.setFillsViewportHeight(true);
        JScrollPane scrollpane = new JScrollPane(table);

        Dimension dim = scrollpane.getPreferredSize();
        int x = insets.left + 20;
        int y = insets.top + 20;
        scrollpane.setBounds(x,y,dim.width,dim.height);
        pane.add(scrollpane);

        width = x + dim.width + 20 + insets.left;
        height = y + dim.height + 40 + insets.bottom;

        setSize(width,height);
        setVisible(true);
    }
}