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));
     this.app=app;
     img = app.getImage(app.getCodeBase(), "cloud.gif");
public void paint(Graphics g)
     g.drawImage(img,50,50,this);
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();
canvas.init(this);
//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
/*JButtons*/
     button1_JPanel = new JPanel();
button1_JPanel.setLayout(new BorderLayout());
button1_JPanel.add(button1);
button2_JPanel = new JPanel();
button2_JPanel.setLayout(new BorderLayout());
button2_JPanel.add(button2);
button3_JPanel = new JPanel();
button3_JPanel.setLayout(new BorderLayout());
button3_JPanel.add(button3);
button4_JPanel = new JPanel();
button4_JPanel.setLayout(new BorderLayout());
button4_JPanel.add(button4);
button5_JPanel = new JPanel();
button5_JPanel.setLayout(new BorderLayout());
button5_JPanel.add(button5);
button6_JPanel = new JPanel();
button6_JPanel.setLayout(new BorderLayout());
button6_JPanel.add(button6);
button7_JPanel = new JPanel();
button7_JPanel.setLayout(new BorderLayout());
button7_JPanel.add(button7);
button8_JPanel = new JPanel();
button8_JPanel.setLayout(new BorderLayout());
button8_JPanel.add(show_button8);
// all JButtons JPanel
JButtons = new JPanel();
JButtons.setLayout(new FlowLayout());
JButtons.setBackground(new Color(228, 241, 250));
JButtons.add(button1_JPanel);
JButtons.add(button2_JPanel);
JButtons.add(button3_JPanel);
JButtons.add(button4_JPanel);
JButtons.add(button5_JPanel);
JButtons.add(button6_JPanel);
JButtons.add(button7_JPanel);
JButtons.add(button8_JPanel);
//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());
tables_JButtons_JPanel.add("North",table);
tables_JButtons_JPanel.add("South",JButtons);
// Display the JPanels..
     this.setLayout(new BorderLayout());     
add("North",topic);
add("Center",canvas); // here i want to add some images and drawings
add("South",tables_JButtons_JPanel);
}// 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?

    Hi,
    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,
    David

    Hi,
    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 {
    width:10px;
    max-width:300px !important;
    </style>And you can try add
    table.apexir_WORKSHEET_DATA {
    width: 100% !important;
    table-layout: fixed !important;
    }Regards,
    Jari
    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?
    Cheers?

    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"},
                       {"1-0","1-1","1-2"},
                       {"2-0","2-1","2-2"}};
         JTable myTable = new JTable(data,head);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container content = getContentPane();
         content.add(new JScrollPane(myTable), BorderLayout.CENTER);
         setSize(200,200);
         show();
        public static void main(String[] args) { new Test(); }
    }

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

    Hi,
    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,
    Tom
    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");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        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);
        table.getColumnModel().getColumn(1).setPreferredWidth(200);
        table.getColumnModel().getColumn(3).setPreferredWidth(20);
          // Set selection to first row
        ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        selectionModel.addListSelectionListener (new ListSelectionListener()
        { public void valueChanged(javax.swing.event.ListSelectionEvent e)
            if (e.getValueIsAdjusting()) return;
                System.out.println(table.getSelectedRow());
          // Add to screen so scrollable
        JScrollPane scrollPane = new JScrollPane (table);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(500, 100);
        frame.setVisible(true);
      public static void main(String args[])
      { new UpdateTable();
        try
        { 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.
        table.repaint();
    // 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;
            tableView.setColumnSelectionAllowed(false);
            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();
            th.addMouseListener(listMouseListener);
        }

  • 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

    Hi,
    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?
    Cheers

    Class PublicationTableModel:
    public class PublicationTableModel extends AbstractTableModel
        PublicationManager pubManager;
        /** Creates a new instance of PublicationTableModel */
        public PublicationTableModel(PublicationManager pm)
            super();
            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;
            etc
           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)
            fields=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.
    Cheers,
    garsher

  • 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);
              setLineColor(Color.blue);
              setFillColor(ColorMenu.kColorOfNoFill);
              fEditor = inLEditor;
              content = fEditor.getGEFPanel().getDrawingPanel();
              importTable(inTableModel);
              fEditor.init();
              fEditor.inval();
    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())
                   drawHandles(g);
              if (_filled && (getFillColor() != null))
                   jt.setBackground(getFillColor());
              if (getLineColor() != null)
                   jt.setGridColor(getLineColor());
                   jt.setBorder(BorderFactory.createLineBorder(getLineColor()));
         }

  • 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("Drive");
         cN.add("Location");
         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
    table.setTableHeader(null);
    that will do the trick;
    cheers
    krishna

  • 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.
    Thanks

    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
    heading.
    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
    functionality.
    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() {
            super();
            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.setBackground(Color.lightGray);
                        secondLabel.setOpaque(true);
                        secondLabel.setBorder(new LeftBorder());
                        panel.add(firstLabel);
                        panel.add(secondLabel);
                    } else {
                        panel.setLayout(new GridLayout(0, 1));
                        JLabel firstLabel = new JLabel(twoValues[0].toString(), JLabel.CENTER);
                        panel.add(firstLabel);
                    return panel;
        private void toggle() {
            secondValueVisible = !secondValueVisible;
            repaint();
        class LeftBorder extends AbstractBorder {
            public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
                g.setColor(Color.gray);
                g.drawLine(x, y, x, height);
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setSize(300, 300);
            frame.setLocation(300, 200);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container contentPane = frame.getContentPane();
            final DoubleColumnTable table = new DoubleColumnTable();
            contentPane.add("North", new JButton(new AbstractAction("Toggle") {
                public void actionPerformed(ActionEvent e) {
                    table.toggle();
            contentPane.add("Center", new JScrollPane(table));
            frame.setVisible(true);
    }Message was edited by:
    NY_Consultant
    Message was edited by:
    NY_Consultant
    Message was edited by:
    NY_Consultant

    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
    alex

    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:
    setReorderingAllowed(false);

  • 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" -
    "http://java.sun.com/docs/books/tutorial/uiswing/components/table.html"
    The tables have fixed column header when u scroll down..

Maybe you are looking for

  • Serializing a class that implements the Singleton pattern

    Hello, I am relatively new to Java and especially to serialization so the answer to this question might be obvious, but I could not make it work event though I have read the documentation and the article "Using XML Encoder" that was linked from the d

  • DAQmx Error: Non-buffered hardware-timed operations are not supported for this d evice and Channel Type.

    Hello, I am new to NI and to data acuasition cards in general. I am trying to put an application togather that would play large audio file using NI9263. And i am getting the following error. DAQmx Error: Non-buffered hardware-timed operations are not

  • Exporting photograph issue

    I am exporting jpegs with size set to "Original Size" and Image Quality set to 12. There is one field I don't understand - DPI. I currently export at the default value, 72dpi. I heard that in order to print something, it should be 300 dpi so I tried

  • How to install an app

    Using Yosemite (10.10.1), how do I install an app that was downloaded, not from the Apple Store? I've got a dmg file in the downloads folder. I can dbl-click that to start the app, but what I want is for the app to show up in the Launchpad. I looked

  • Diffrent languages in form builder

    Hi Is there a function in the form builder can test for the actor’s portal language and then display labels etc. in the correct language? I thought that I could make a property for each label entry. To this property I could attach text strings for ea