Add a title to a JTable

前端 未结 4 1317
醉酒成梦
醉酒成梦 2021-01-19 07:48

I have a JTable which is created using a TableModel JTable t = new JTable(tableModel) I want to add a title to it. I was hoping for something like t.setTi

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-19 08:17

    Another option you could consider is enclosing the JTable in a JPanel and setting a TitledBorder to that JPanel.

    Like this:

    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    
    public class TableTitle
    {
        public TableTitle ()
        {
            JFrame frame = new JFrame ();
            frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
    
            JPanel panel = new JPanel ();
            panel.setBorder (BorderFactory.createTitledBorder (BorderFactory.createEtchedBorder (),
                                                                "Table Title",
                                                                TitledBorder.CENTER,
                                                                TitledBorder.TOP));
    
    
            JTable table = new JTable (3, 3);
    
            panel.add (table);
    
            frame.add (panel);
    
            frame.setLocationRelativeTo (null);
            frame.pack ();
            frame.setVisible (true);
        }
    
        public static void main (String[] args)
        {
            SwingUtilities.invokeLater (new Runnable ()
            {
                @Override public void run ()
                {
                    TableTitle t = new TableTitle ();
                }
            });
        }
    }
    

    It looks like this:

    screenshot1

提交回复
热议问题