JTable调整列宽

JTable调整列宽_第1张图片

 案例实现:JTable调整列宽_第2张图片

 

package com.aynu.layout;

import javax.swing.*;
import javax.swing.table.TableColumn;

public class SimpleTable {

    JFrame jf = new JFrame("简单表格");

    //创建一维数组,存储标题
    Object[] titles = {"姓名","年龄","性别"};

    //创建二维数组,存储数据
    Object[][] data = {
            {"关羽",29,"男"},
            {"貂蝉",26,"女"},
            {"赵云",27,"男"},
            {"小乔",29,"女"},
            {"唐僧",35,"男"}

    };


    public void init(){
        //组装视图
        JTable jTable = new JTable(data,titles);

        //TODO 设置选择模式
       // jTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);    //默认没有限制
        // jTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);    //只能选择单个连续范围
         jTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);    //只能单选




        //TODO 设置列宽
        TableColumn column_1 = jTable.getColumn(titles[0]);
        column_1.setMinWidth(40);

        TableColumn column_3 = jTable.getColumn(titles[2]);
        column_3.setMaxWidth(50);


        jf.add(new JScrollPane(jTable));

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);


    }

    public static void main(String[] args) {
        new SimpleTable().init();
    }
}

你可能感兴趣的:(java,开发语言)