JTable Header & column Headers

i want to add a table Header(Level 1 Students)
and a columns Headers(Name ID Section#)
How can i do that ?
Thanks a lot
This is my code:
import java.awt.*;
import java.applet.*;
import java.applet.Applet;
import java.awt.image.*;
import javax.swing.*;
import java.util.*;
class DrawingCanvas extends Canvas{
Applet app;
Image img;
public void init(Applet app)
     setBackground(new Color(165, 215, 220));
     img = app.getImage(app.getCodeBase(), "cloud.gif");
public void paint(Graphics g)
public class Table_Button extends JApplet {
     DrawingCanvas canvas;
     // a separate JPanel is associated with each JButton
JPanel button1_JPanel, button2_JPanel, button3_JPanel, button4_JPanel,button5_JPanel,button6_JPanel,button7_JPanel;
JPanel button8_JPanel;
JPanel topic;     //For Topic name
JPanel JButtons; // for all the JButtons
JPanel tables_JButtons_JPanel;
JTable table;
JButton button1,button2,button3,button4,button5,button6,button7;
JButton show_button8;
public void init(){
canvas = new DrawingCanvas();
//Controls JButtons
     button1 = new JButton("button1");
button2 = new JButton("button2");
button3 = new JButton("button3");
button4 = new JButton("button4");
button5= new JButton("button5");
button6= new JButton("button6");
button7= new JButton ("button7");
//button8 JButton
show_button8= new JButton("Show button8");
button1.setBackground(new Color(111, 178, 230));
button2.setBackground(new Color(111, 178, 230));
button3.setBackground(new Color(111, 178, 230));
button4.setBackground(new Color(111, 178, 230));
button5.setBackground(new Color(111, 178, 230));
button6.setBackground(new Color(111, 178, 230));
button7.setBackground(new Color(111, 178, 230));
show_button8.setBackground(new Color(111, 178, 230));
/*Topic Name*/
topic = new JPanel();
topic.setLayout(new BorderLayout());
topic.add(new JLabel(" Topic Name ",JLabel.CENTER));
All Controls
     button1_JPanel = new JPanel();
button1_JPanel.setLayout(new BorderLayout());
button2_JPanel = new JPanel();
button2_JPanel.setLayout(new BorderLayout());
button3_JPanel = new JPanel();
button3_JPanel.setLayout(new BorderLayout());
button4_JPanel = new JPanel();
button4_JPanel.setLayout(new BorderLayout());
button5_JPanel = new JPanel();
button5_JPanel.setLayout(new BorderLayout());
button6_JPanel = new JPanel();
button6_JPanel.setLayout(new BorderLayout());
button7_JPanel = new JPanel();
button7_JPanel.setLayout(new BorderLayout());
button8_JPanel = new JPanel();
button8_JPanel.setLayout(new BorderLayout());
// all JButtons JPanel
JButtons = new JPanel();
JButtons.setLayout(new FlowLayout());
JButtons.setBackground(new Color(228, 241, 250));
//How to set the table header(title) to (Level 1 Students)
// How to set the table columns headers to (Name ID Section)
     table = new JTable( 5, 3 );
     tables_JButtons_JPanel = new JPanel();
tables_JButtons_JPanel.setLayout(new BorderLayout());
// Display the JPanels..
     this.setLayout(new BorderLayout());     
add("Center",canvas); // here i want to add some images and drawings
}// end inti()

JTable Tutorial didn't specify how to add columns names when using the constructor:
JTable(int numberofRows,int numberofColumns) Well then use another constructor. For example:
DefaultTableModel model = new DefaultTableModel(...);
JTable table = new JTable( model );Also, I forgot to mention don't use AWT components in a Swing application. Canvas is an AWT component. Use JPanel instead.

Similar Messages

  • Resize column width for JTable without column headers?

    I find that for me to resize columns of a JTable by using
    mouse dragging, I MUST have column headers and then drag
    column headers to resize them. Is my understanding correct?
    Actually, I need to have a table without header columns.
    How can I use mouse to resize column width by dragging?
    The background for this request is that I am putting a
    complex table as another table's column header and I hope to
    be able to resizing the complex table by mouse dragging.
    Thanks very much,

    I think you have mistake there. Try
    <style type="text/css">
    table.apexir_WORKSHEET_DATA td {
    white-space:nowrap !important;
    td[headers="DESCR"] {
    width:300px !important;
    max-width:300px !important;
    #apexir_DESCR {
    max-width:300px !important;
    </style>And you can try add
    table.apexir_WORKSHEET_DATA {
    width: 100% !important;
    table-layout: fixed !important;
    My Blog: http://dbswh.webhop.net/htmldb/f?p=BLOG:HOME:0
    Twitter: http://www.twitter.com/jariolai

  • JTable without column headers?

    I want a JTable without the column headers.
    How can i do this?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
        public Test() {
         String[] head = {"","",""};
         String[][] data = {{"0-0","0-1","0-2"},
         JTable myTable = new JTable(data,head);
         Container content = getContentPane();
         content.add(new JScrollPane(myTable), BorderLayout.CENTER);
        public static void main(String[] args) { new Test(); }

  • JTable -showing column headers and displaying multi-line strings

    This is two questions really.
    #1 - Does anyone know why my column headers aren't showing in my jtable using the model below?
    #2 - Does anyone know how I can display, mulitple line strings in a jtable? Currently my newline character ('\n') is just being displayed as a character.
    any help very much appreciated,
    private class TaskHistoryTableModel extends AbstractTableModel {
    private List taskHistory = new ArrayList();
    public Object getValueAt(int row, int col) {
    if (col == 0) {
    return ((TaskHistoryItem) taskHistory.get(row)).getText();
    } else {
    return ((TaskHistoryItem) taskHistory.get(row)).getDate().getTime();
    public int getRowCount() {
    return taskHistory == null ? 0 : taskHistory.size();
    public int getColumnCount() {
    return 2;
    /** Getter for property taskHistory.
    * @return Value of property taskHistory.
    public List getTaskHistory() {
    return taskHistory;
    /** Setter for property taskHistory.
    * @param taskHistory New value of property taskHistory.
    public void setTaskHistory(List taskHistory) {
    this.taskHistory = taskHistory;
    public String getColumnName (int col) {
    return col == 0 ? "Text" : "Entered At";
    public boolean isCellEditable(int row, int col) {
    return false;

    fixed my own problem - make your mulit-line string into html format e.g.
    this string will appear on two lines in a jtable
    "<html><p>A much more interesting entry</p> <p>on multiple lines</p></html>"

  • JTable update, column headers

    I am trying to write my own tablemodel which does not change the specified
    column widths when updating. So far everthing works fine, only the column
    headers are not repainted. Does anybody know what is missing?
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class UpdateTable
    { static String headers[]= {"Baum", "Blatt", "Frucht","H�usigkeit"};;
      static String data[][]= {
         {"Eiche", "gez�hnt","Eichel","ein"},
         {"Buche", "glatt", "Buchecker","ein"},
         {"Tanne", "Nadel", "Zapfen","ein"},
         {"Pappel", "wechselst�ndig","Kapsel","zwei"},
      static MyTableModel tblModel;
      static JTable table;
      public UpdateTable()
      { JFrame frame = new JFrame("UpdateTable");
        Container contentPane = frame.getContentPane();
        tblModel = new MyTableModel(data, headers)
        { // Make read-only
          public boolean isCellEditable(int x, int y)
          { return false;
        table = new JTable(tblModel);
          // Set selection to first row
        ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.addListSelectionListener (new ListSelectionListener()
        { public void valueChanged(javax.swing.event.ListSelectionEvent e)
            if (e.getValueIsAdjusting()) return;
          // Add to screen so scrollable
        JScrollPane scrollPane = new JScrollPane (table);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(500, 100);
      public static void main(String args[])
      { new UpdateTable();
        { Thread.sleep(3000);
        catch (InterruptedException e)
        { System.out.println ("Fehler: "+ e.toString());
        String headers_neu[] = {"Arbre", "Feuille", "Fruit", "Maisonette"};
        headers = headers_neu;
        data[0][0]= "Eberesche";
        tblModel.setDataVector(data, headers);
    //    table.revalidate(); // is of no use.
    // The table model
    class MyTableModel extends AbstractTableModel
      private int cols, rows;
      private String[] columnNames;
      private String[][] data;
      public MyTableModel(int cols, int rows)
      { this.cols = cols;
        this.rows = rows;
      public MyTableModel(String[][] data, String[] columnNames)
      { setDataVector(data, columnNames);
      public String getColumnName(int col)
      { return columnNames[col].toString();
      public int getColumnCount()
      { return cols;
      public int getRowCount()
      { return rows;
      public Object getValueAt(int row, int col)
      { return data[row][col];
      public void setDataVector(String[][] data, String[] columnNames)
      { this.cols = data[0].length;
        this.rows = data.length;
        this.data= data;
        this.columnNames= columnNames;
    //    Firing the event will change column widths as usual.
    //    fireTableChanged(new TableModelEvent(this,TableModelEvent.HEADER_ROW););

    // fireTableChanged(new TableModelEvent(this,TableModelEvent.HEADER_ROW););
    You have to fire a table changed event.
    The table neverasks the model if things have changed. The model always notifys the table of changes.
    No event fired no table repaint.
    Instead of fireTableChanged(...) you have the option of fireTableDataChanged() (if only the data has changed, not the nomber of columns or the type of columns) and fireTableStructureChanged() (if there have been columns changed).
    If fireTableStructureChanged happens (and HEADER_ROW event is the same thing), the table removes the columns and creates new onew. That's why column sizes are lost.
    If you really want the table not to manage columns, you have to do it yourself:
    Implement your own TableColumnModel and pass it to the table constructor. When adding/removing columns you can ask what was the size of the previous columns where and set the new columns to that size.
    Call setAutoCreateColumnsFromModel(false) in your table constructor so that the table will not remove/create new columns itself when a tableStructureChanged event happens.

  • JTable - make column headers clickable

    Hi all
    I have a JTable, and now I want to sort by column. I've actually got the column sorting working using menu items, but how can I make my column header clickable, and where do I add an actionListener to?

        public void addMouseListenerToHeaderInTable(JTable table) {
            final JTable tableView = table;
            MouseAdapter listMouseListener = new MouseAdapter() {
                        public void mouseClicked(MouseEvent e) {
                            TableColumnModel columnModel = tableView.getColumnModel();
                            int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                            int column = tableView.convertColumnIndexToModel(viewColumn);
                            if (e.getClickCount() == 1 && column != -1) {
                                int shiftPressed = e.getModifiers() & InputEvent.SHIFT_MASK;
                                boolean ascending = (shiftPressed == 0);
                                // sort
            JTableHeader th = tableView.getTableHeader();

  • User editable column headers

    Is it possible to allow my JTable's column headers to be editable by the user who runs my application? Maybe its so obvious that I'm overlooking it, but I couldn't find anything in the tutorials about how to do this.

    nice day,
    [same answer as|http://www.java-forums.org/awt-swing/31497-custom-jxtable-header-focus-traversal.html]

  • JTable column headers not displaying using custom table model

    I'm attempting to use a custom table model (by extending AbstractTableModel) to display the contents of a data set in a JTable. The table is displaying the data itself correctly but there are no column headers appearing. I have overridden getColumnName of the table model to return the correct header and have tried playing with the ColumnModel for the table but have not been able to get the headers to display (at all).
    Any ideas?

    Class PublicationTableModel:
    public class PublicationTableModel extends AbstractTableModel
        PublicationManager pubManager;
        /** Creates a new instance of PublicationTableModel */
        public PublicationTableModel(PublicationManager pm)
            pubManager = pm;
        public int getColumnCount()
            return GUISettings.getDisplayedFieldCount();
        public int getRowCount()
            return pubManager.getPublicationCount();
        public Class getColumnClass(int columnIndex)
            Object o = getValueAt(0, columnIndex);
            if (o != null) return o.getClass();
            return (new String()).getClass();
        public String getColumnName(int columnIndex)
            System.out.println("asked for column name "+columnIndex+" --> "+GUISettings.getColumnName(columnIndex));
            return GUISettings.getColumnName(columnIndex);
        public Publication getPublicationAt(int rowIndex)
            return pubManager.getPublicationAt(rowIndex);
        public Object getValueAt(int rowIndex, int columnIndex)
            Publication pub = (Publication)pubManager.getPublicationAt(rowIndex);
            String columnName = getColumnName(columnIndex);
            if (columnName.equals("Address"))
                if (pub instanceof Address) return ((Address)pub).getAddress();
                else return null;
            else if (columnName.equals("Annotation"))
                if (pub instanceof Annotation) return ((Annotation)pub).getAnnotation();
                else return null;
           else if (columnName.equals("Title"))
                return pub.getTitle();
            else if (columnName.equals("Key"))
                return pub.getKey();
            return null;
        public boolean isCellEditable(int rowIndex, int colIndex)
            return false;
        public void setValueAt(Object vValue, int rowIndex, int colIndex)
        }Class GUISettings:
    public class GUISettings {
        private static Vector fields = new Vector();
        private static Vector classes = new Vector();
        /** Creates a new instance of GUISettings */
        public GUISettings() {
        public static void setFields(Vector f)
        public static int getDisplayedFieldCount()
            return fields.size();
        public static String getColumnName(int columnIndex)
            return (String)fields.elementAt(columnIndex);
        public static Vector getFields()
            return fields;
    }GUISettings.setFields has been called before table is displayed.

  • Cant see jtable column headers

    I have my jtable in a container and i am displaying that container in a jframe. I cant see the table column headers. I cant use a jscrollpane and need to make the table headers visible. I can see the table fine with all its information in it. When I do a System.out.println(TableModel.getColumnName(int)); i get the correct column header name so I know that the column headers are existing. I would appreciate any help that you can give

    the last answer did not help me out. I reposted this with more information, such as i am placing my table in a container and not in a scrollpane. I added the code below and it still did not work
    content.add(jt.getTableHeader(), BorderLayout.NORTH);
    content.add(jt, BorderLayout.CENTER);
    I can still only see the table. I pasted code below where I create my table and repaint it. I have it set up where my table is in a JPanel. I have is set up so that I can move it around and resize it with the mouse. This all works and I can see the table but there are no headers.
    public FigTable(DefaultTableModel inTableModel, LEditor inLEditor)
              super(50, 50, 350, 200);
              fEditor = inLEditor;
              content = fEditor.getGEFPanel().getDrawingPanel();
    public void importTable(DefaultTableModel inTableModel)
              jt = new JTable(inTableModel);
              tRows = jt.getRowCount();
              tColumns = jt.getColumnCount();
              content.add(jt, BorderLayout.CENTER);
              content.add(jt.getTableHeader(), BorderLayout.NORTH);
    public void paint(Graphics g)
              jt.setBounds(_x, y, w, _h);
              if (_h >= tRows && tRows != 0)
              jt.setRowHeight(_h / tRows);
              if (isSelected())
              if (_filled && (getFillColor() != null))
              if (getLineColor() != null)

  • JTable column headers missing

    I created a JTable using:
    JTable table = new JTable(v,cN);
    where v is my vector that holds the data and cN is a vector to hold the column names as below:
    Vector cN = new Vector();
         cN.add("Registry Keys");
         cN.add("Program Name");
         cN.add("Key Type");
         cN.add("Leave");It displays the table fine with the data and as I add or remove entries in the cN vector it adds and removes columns - but doesn't display column headers? Any help appreciated.

    Are you using a scrollpane? If not, you have to get the Table Header component and place it appropriately.

  • JTable Column Headers

    I want to create a JTable so that the table doesn't have any column headers. Right now I am using my own implementation of the AbstractTableModel Class for use with the tables, but if I leave out the public String getColumnName(int col) method, it makes the headers A, B, C, ... and if I set the column headers up with a blank String, it leaves an obvious thin empty header at the top. Any suggestions on how I can completely leave the column headers off?

    call the method on JTable
    that will do the trick;

  • JTable auto size columns/headers

    How do I autoresize a JTable column/headers so that each column/header is the minium size necessary.
    I've tried setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); and that doesn't
    seem to work.

    You need to calculate the width of the text and set the preferred size of each column.
    If seen solutions posted in the forum (but no I don't know the exact posting) so you can search the forum to find them.

  • JTable: Easy groupable column headers with hideable columns

    Hi All,
    I have a requirement to make a JTable which displays
    columns with 2 values - a current value and an old one.
    The old value can be hidden or shown by user preference.
    The values are not editable. The 2 values have a single
    I've been mucking about with GroupableTableHeader and
    HideableTableColumnModel and all that. This way of
    solving the problem requires siginificant coding.
    Then I had an idea - just use the TableCellRenderer to
    make it look like 2 columns ! This fits my requirements
    and is much simpler.
    So for anyone who has the same requirement, here is
    some sample code. I think you'll all agree that in my
    specific case it is a very good way of providing the needed
    Here is the sample code:
    import javax.swing.*;
    import javax.swing.border.AbstractBorder;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    public class DoubleColumnTable extends JTable {
        private boolean secondValueVisible = true;
        public DoubleColumnTable() {
            setModel(new AbstractTableModel() {
                public String getColumnName(int column) {
                    return column + "";
                public int getColumnCount() {
                    return 5;
                public int getRowCount() {
                    return 5;
                public Object getValueAt(int rowIndex, int columnIndex) {
                    return new Integer[]{new Integer(rowIndex), new Integer(columnIndex + 10)};
            setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                    Integer[] twoValues = (Integer[])value;
                    JPanel panel = new JPanel();
                    if (secondValueVisible) {
                        panel.setLayout(new GridLayout(0, 2));
                        JLabel firstLabel = new JLabel(twoValues[0].toString(), JLabel.CENTER);
                        JLabel secondLabel = new JLabel(twoValues[1].toString(), JLabel.CENTER);
                        secondLabel.setBorder(new LeftBorder());
                    } else {
                        panel.setLayout(new GridLayout(0, 1));
                        JLabel firstLabel = new JLabel(twoValues[0].toString(), JLabel.CENTER);
                    return panel;
        private void toggle() {
            secondValueVisible = !secondValueVisible;
        class LeftBorder extends AbstractBorder {
            public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
                g.drawLine(x, y, x, height);
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setSize(300, 300);
            frame.setLocation(300, 200);
            Container contentPane = frame.getContentPane();
            final DoubleColumnTable table = new DoubleColumnTable();
            contentPane.add("North", new JButton(new AbstractAction("Toggle") {
                public void actionPerformed(ActionEvent e) {
            contentPane.add("Center", new JScrollPane(table));
    }Message was edited by:
    Message was edited by:
    Message was edited by:

    This should read
    "I have a table with column headers and a row headers using a single column from a second table."

  • Jtable stop mouse hover over column headers

    i have a jatable and when i move the mouse over the column headers
    it does the hover effect and highlights the column header
    in this particular table i don't want any sorting or column moving, so i want to disable this effect
    i have looked through the JTableHeader api's but i am not sure which one to use to turn it off. i tried .setFocusable(false) but that didn't seem to work
    any suggestions ?
    thanks in advance

    by default, JTable does not have the hover effect, highlights of the column header, and sorting. you must have implemented these in your codes.
    as for the column moving, you may try this:

  • Fixed jtable column headers

    Does anyone have an example of fixing column headers for a JTable. Basically I want the column headers to be displayed when scrolling down the table.

    check the examples provided in "How to use table" -
    The tables have fixed column header when u scroll down..

Maybe you are looking for

  • Can not sync photos with iPad or iPhone after upgrade to lion

    I upgraded to lion and now i get an error message saying could not sync photos with Ipad as they can not be viewed on the ipad.  I lost everything when i upgraded and had to reload all my files using a new user. Now i cant sync my photos with my ipad

  • Context handling

    Hi, I have a scenario where I am sending an XML file and I have to map it to standard matmas IDoc and post it to ECC. In the target IDoc structure, we have one segment E1MLGNM for warehouse number and it has one child E1MLGTM for storage type for tha

  • Adding maps to a book=phantom feature?

    So. After an hour or three looking through archives here and researching the web it seems you cannot add a map to any book other than the apple template with theme "photo essay" or "journal" wich cannot be accessed when using custom page sizes. The o

  • TS3694 keep getting error code 1015 help please

    as title says i keep getting this error code while tryin to restore (1015)

  • Mac Mini, meet my TV (TV connectivity issue)

    Hey all, Im using a mac mini with a 23 inch Cinema HD display. I recently bought a 42 inch Toshiba LCD TV that has a regular old VGA pin connector input for PC display. So, I went ahead and bought a DVI-to-VGA AND DVI splitter. Problem is, both monit