Java:动态更改JTable标头高度

时间:2019-04-03 16:12:13

标签: java header jtable height

运行以下代码将生成此表。

enter image description here

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class TableHeaderTest extends JFrame 
{

    public TableHeaderTest()
    {
        JButton jb = new JButton("Change Header");
        JTextField jt = new JTextField(30);
        //headers for the table
        String[] columns = new String[] {
            "Id", "Name", "Hourly Rate", "Part Time"
        };

        //actual data for the table in a 2d array
        Object[][] data = new Object[][] {
            {1, "John ReallyLongLastName ", 40.0, false },
            {2, "Rambo", 70.0, false },
            {3, "Zorro", 60.0, true },
        };
        //create table with data
        JTable table = new JTable(data, columns);

        jb.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent arg0) 
            {
                JTableHeader th = table.getTableHeader();
                TableColumnModel tcm = th.getColumnModel();
                TableColumn tc = tcm.getColumn(1);
                tc.setHeaderValue( jt.getText());
                table.getTableHeader().invalidate();
                table.getTableHeader().repaint();
            }

        });

        //add the table to the frame
        JPanel pane = new JPanel();
        GridLayout gl = new GridLayout(1,2);
        pane.setLayout(gl);
        pane.add(jb);
        pane.add(jt);

        this.add(pane, BorderLayout.NORTH);
        this.add(new JScrollPane(table), BorderLayout.CENTER);

        this.setTitle("Table Example");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
        this.pack();
        setSize(400,200);
        this.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TableHeaderTest();
            }
        });
    }   
}

enter image description here

在文本字段中输入“ Long Names Go Here”,然后单击“更改标题”按钮。

是否可以动态调整列标题的高度(而不是宽度)?

enter image description here

由于标题标签是通过文本字段输入的,因此其长度可以变化。关键是宽度不应该改变,而只是标头高度。

0 个答案:

没有答案