Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a title to a JTable

Tags:

java

swing

jtable

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.setTitle(graphTitle); but i cant find anything on that lines. I dont mind if the title is on top or below the table. I was using JLabels but it just looks messy.

Can anyone help? Cheers in advance

like image 563
Josh Avatar asked Dec 02 '22 00:12

Josh


2 Answers

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

like image 195
Radu Murzea Avatar answered Dec 05 '22 09:12

Radu Murzea


You would have to add it when you instantiate your DefaultTableModel:

String data[][] = {{"Vinod","MCA","Computer"},
{"Deepak","PGDCA","History"},
{"Ranjan","M.SC.","Biology"},
{"Radha","BCA","Computer"}};

String col[] = {"Name","Course","Subject"};

DefaultTableModel model = new DefaultTableModel(data,col);
table = new JTable(model);

If it already exists, you can do something like this:

ChangeName(table,0,"Stu_name");
ChangeName(table,2,"Paper");

public void ChangeName(JTable table, int col_index, String col_name){
    table.getColumnModel().getColumn(col_index).setHeaderValue(col_name);
}

Courtesy of RoseIndia.net

Hope that helps.

like image 44
Carlos Avatar answered Dec 05 '22 08:12

Carlos