Set Column Width of JTable by Percentage

后端 未结 5 1898
傲寒
傲寒 2020-12-31 20:53

I need to assign a fixed width to a few columns of a JTable and then an equal width to all the other columns.

Suppose a JTable has 5 column

5条回答
  •  醉酒成梦
    2020-12-31 21:29

    I need to assign a fixed width to a few columns of a JTable and then an equal width to all the other columns.

    Let the table's resize mode do the work for you. Set the resize mode to all columns and set the min/max values of the fixed columns:

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    
    public class TableLayout extends JPanel
    {
        public TableLayout()
        {
            setLayout( new BorderLayout() );
    
            JTable table = new JTable(5, 7);
            add( new JScrollPane( table ) );
    
            table.setAutoResizeMode( JTable.AUTO_RESIZE_ALL_COLUMNS );
            TableColumn columnA = table.getColumn("A");
            columnA.setMinWidth(100);
            columnA.setMaxWidth(100);
            TableColumn columnC = table.getColumn("C");
            columnC.setMinWidth(50);
            columnC.setMaxWidth(50);
        }
    
        private static void createAndShowUI()
        {
            JFrame frame = new JFrame("TableLayout");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new TableLayout() );
            frame.setSize(600, 200);
            frame.setLocationByPlatform( true );
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowUI();
                }
            });
        }
    }
    

提交回复
热议问题