Data visibility in JTable columns

I am unable to see the "full" cell data in a JTable. When I click on the cell, the cursor lets me move left and right inside the cell. And that's the only way to see the full data inside the cell. Is there some way to set the minimum width of a cell or the spacing between the vertical lines so the full data is visible? Right now, in the JTable all cells are of equal width and height. Thanks for any responses. -- Murthy

Something similar to this should help. This is for a 5 column table, so you would obviously not hard code it, but instead ask the table model for the number of columns.
This sample code is from the Java Tutorial in the "How to use JTables" page. http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
TableColumn column = null;
for (int i = 0; i < 5; i++) {
    column = table.getColumnModel().getColumn(i);
    if (i == 2) {
        column.setPreferredWidth(100); //sport column is bigger
    } else {
        column.setPreferredWidth(50);
}

Similar Messages

  • How display numeric datas in a JTable column on the right side?

    Hallo !
    I have a JTable using the AbstractTableModel.
    How can I display the numeric values on the right side of the column?
    Wolfgang

    It works, if I overwrite the TabModel-method "getColumnClass". But I cannot use this, because in german I have a "," in a double an not a "." as comma. So I get an Exception if the table tries to format 123,34 as a double.
    But I think there must be a possibility to format strings in a column. On the left side, in the center, on the right side. Do you know something to position Strings in a JTableColumn ?
    Wolfgang

  • How Can I set up a JTable columns?

    Dear All,
    How can I set up my JTable columns to have the amount the user specifies?
    for example when the user types in 50 in JTextField 1 I want the JTables columns to then set to 50.
    How can this be done?
    Thanks
    lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

    As you can see I have tried this, but no success.
    If I am doing something wrong please accept my apology, and address me in the right direction.
    Thanks
    Lol
    import javax.swing.*;
    import javax.swing.table.TableModel;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class si1 extends javax.swing.JFrame implements ActionListener {
        JTextField name = new JTextField(15);
        JTextField name1 = new JTextField(15);
        public si1() {
            super("DataBase Loader");
            setSize(1025,740);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel pane = new JPanel();
            JPanel pane1 = new JPanel();
            JPanel pane2 = new JPanel();
            JPanel pane3 = new JPanel();
            JPanel pane4 = new JPanel();
            pane.setLayout(new GridLayout(20,1));
            pane1.setLayout(new BorderLayout());
            int j=10;
            String[][] data = new String[j][2];
            for (int k=0; k<j; k++){
               String[] row = {"",""};
               data[k] = row;
            String[] columnNames = {"First Name", "Last Name"};
            JTable perstab = new JTable(data, columnNames);
         ((DefaultTableModel)perstab.getModel()).setColumnCount(Integer.parseInt(name.getText()));
            perstab.setGridColor(Color.yellow);
            perstab.setPreferredScrollableViewportSize(new Dimension(500,500));
            JScrollPane scrollPane = new JScrollPane(perstab);
            pane1.add(new JPanel(), BorderLayout.EAST);
            JButton btn = new JButton("What are the names?");
            btn.addActionListener(this);
            btn.putClientProperty("DATABASE", perstab);
            pane1.add(new JPanel().add(btn), BorderLayout.SOUTH);
            pane2.add(name);
            pane3.add(name1);
            pane.add(pane2);
            pane.add(pane3);
            pane1.add(pane, BorderLayout.WEST);
            pane4.add(scrollPane);
            pane1.add(pane4, BorderLayout.CENTER);
            setContentPane(pane1);
            show();
        public static void main(String[] args) {
            si1 frame = new si1();
            frame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable)((JButton)e.getSource()).getClientProperty("DATABASE");
            TableModel model = table.getModel();
            int count = model.getRowCount();
            String[] firstnames = new String[count];
            String[] lastnames = new String[count];
            for (int i=0; i < count; i++) {
               firstnames[i] = (String)model.getValueAt(i, 0);
                System.out.println("first name at row " + i + ": " + firstnames);
    lastnames[i] = (String)model.getValueAt(i, 1);
    System.out.println("lastname name at row " + i + ": " + lastnames[i]);

  • Problem retrieving data from a JTable.

    Hi All,
    I've just searched to 45th page of this forum but I heven't found a topic containing infos that can help me.
    Well, my problem is: I have to retrieve data from a JTable. I use getValue() method but it seems to work well on all cells of a row but the last cell. I use the TAB to move focus on the row and when it is on the last cell, using TAB, the focus jumps on the next row & 1st column.
    Using TAB moving on system, I can retrieve all data but data on the last cell data.
    I add another info hoping someone has a solution for my problem: If the focus goes back on the last cell of a row just edited, in this case the data retrieving work as well.
    Thank you for your attention!
    Bye.

    I don't understand your question. I don't understand what using Tab and getValueAt(...) have to do with one another. If you want data from a cell then just use getValueAt(...).
    If you want to know what cell currently has focus you use
    getSelectedRow()
    getSelectedColumn()

  • How to catch selected text in JTable Column

    Hi there,
    I am learning JTable. Need help for How to get the selected text from the JTable Column which is set to be editable.
    for example in JTextFiled you have method on getSelectedText(), is there any method for tracking the selected text.
    Thanks in advance
    Minal

    Here's an example of the model I used in my JTable. Not the "getValueAt" method & "getRecordAt" method. You will have to have a Record object - but it only contains the attributes of an inserted record (with appropriate getters & setters). Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

  • Return to the cell after data validation in JTable

    Hi,
    I am implementing an editable JTable. I want the focus or selection return to the current editing cell when the user inputing a wrong format data. I can catch the validation error and pop up a error message to user. But I can not return the focus or selection to the editing cell.
    If anyone has already solved this problem, please give me your solution.
    Thank you!
    I have tried:
    1.
    In tableChanged(TableModelEvent e) method:
    int row = e.getFirstRow();
    int column = e.getColumn();
    Object data = newJTable.getValueAt(row, column);
    if(!validation(data)) // return true if validation OK
    editFailed = true;//class variable
    previousRow = row;//class variable
    previousCol = column;//class variable
    Add a focus listener to the table and implement the focus listener's focusLost method with:
    if(validationFailed)
    table.editCellAt(previousRow, previousCol);
    This does move the focus to the editing cells if you want to continue to edit the table.
    Problems are
    If you move the focus out of the table, the wrong date will be in the table or not edited.
    The selection color was shown on the next cell where you pointed your mouse to after you leave the editing cells.
    2. I have also tried to use:
    in the above focusLost method
    table.clearSelection();
    table.editCellAt(previousRow, previousCol);
    table.setRowSelectionInterval(previousRow, previousRow);
    table.setColumnSelectionInterval(previousCol, previousRow);
    But it did not change the selection.
    Shaolong

    This is the fix for the above problem.
    Basically we need to handle both mouse/keyboard actions on our own.
    This code returns the control to errorCell..
    /* TableCellValidator class */
    /* The class basically validates the input entry in a cell and */
    /* pops up a JOptionPane if its an invalid input */
    /* And an OK is clicked on the JOptionPane, the control returns back */
    /* to the same cell */
    /* Basic Idea: The controls Arrow/Tab/mouse clicks are handled by our */
    /* ----------- custom table. Its has been slightly tricky to handle */
    /* mouse clicks, since when you click the next cell, the */
    /* editingrow/editingcol advances. Hence the */
    /* previousrow/previouscol has been captured in the */
    /* setValueAt method. */
    /* To capture Table/Arrow/Numeric Arrow, The keyStrokes(TAB etc)*/
    /* assigned different AbstractionActions to execute like */
    /* validateBeforeTabbingToNextCell */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableCellValidator {
    * Constructor.
    * Basically instantiates the class and sets up the
    * JFrame object and the table.
    public TableCellValidator() {
    JFrame f = new JFrame("JTable test");
    f.getContentPane().add(new JScrollPane(createTable()), "Center");
    f.pack();
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    * A method which created our custom table.
    * The JTable methods processMouseEvent
    * and setValueAt are overridden to handle
    * Mouseclicks.
    * The Tables ActionMap is fed with different
    * AbstractAction classes eg: (validateBeforeTabbingToNextCell)
    * (Scroll down below for the innerclass
    * validateBeforeTabbingToNextCell).
    * So basically when TAB is pressed the stuff present
    * in the validateBeforeTabbingToNextCell's actionPerformed(..)
    * method is performed.
    * So we need to handle all the stuff a TAB does.
    * ie. if a TAB hits the end of the row, we need to increment
    * it to the next Row (if the validation is successful)
    * in the current row etc..
    * @return JTable
    * @see validateBeforeTabbingToNextCell
    * @see validateBeforeShiftTabbingToNextCell
    * @see validateBeforeMovingToNextCell
    * @see validateBeforeMovingDownToCell
    * @see validateBeforeMovingUpToCell
    * @see validateBeforeMovingLeftToCell
    private JTable createTable() {
    JTable table = new JTable(createModel()){
    private int previousRow =0;
    private int previousCol =0;
    * Processes mouse events occurring on this component by
    * dispatching them to any registered
    * <code>MouseListener</code> objects.
    * <p>
    * This method is not called unless mouse events are
    * enabled for this component. Mouse events are enabled
    * when one of the following occurs:
    * <p><ul>
    * <li>A <code>MouseListener</code> object is registered
    * via <code>addMouseListener</code>.
    * </ul>
    * <p>Note that if the event parameter is <code>null</code>
    * the behavior is unspecified and may result in an
    * exception.
    * @param e the mouse event
    * @see java.awt.event.MouseEvent
    * @see java.awt.event.MouseListener
    * @see #addMouseListener
    * @see #enableEvents
    * @since JDK1.1
    protected void processMouseEvent(MouseEvent e) {
    boolean canMoveFocus = true;
    int currentRowAndColumn[] = getCurrentRowAndColumn(this); //we pull the current row and column
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    if ( e.getID() == MouseEvent.MOUSE_PRESSED || e.getID() == MouseEvent.MOUSE_CLICKED) {
    stopCurrentCellBeingEdited(this); //stop the cellbeing edited to grab its value
    final String value = (String)getModel().getValueAt(row,column);
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    JOptionPane.showMessageDialog(null,"Alpha value ="+ value ,"Invalid entry!",JOptionPane.WARNING_MESSAGE);
    changeSelection(previousRow,previousCol, true, true);
    editCellAt(previousRow, previousCol);
    requestFocus(); // or t.getEditorCompo
    if ( canMoveFocus ) {
    super.processMouseEvent(e);
    * The method setValueAt of the JTable is overridden
    * to save the previousRow/previousCol to enable us to
    * get back to the error cell when a Mouse is clicked.
    * This is circumvent the problem, when a mouse is clicked in
    * a different cell, the control goes to that cell and
    * when you ask for getEditingRow , it returns the row that
    * the current mouse click occurred. But we need a way
    * to stop at the previous cell(ie. the cell that we were editing
    * before the mouse click occurred) when an invalid data has
    * been entered and return the focus to that cell
    * @param aValue
    * @param row
    * @param col
    public void setValueAt(Object aValue,int row, int col) {     
    this.previousRow = row;
    this.previousCol = col;
    super.setValueAt(aValue,row,col);
    /* These are the various KeyStrokes like
    ENTER,SHIFT-TAB,TAB,Arrow Keys,Numeric Arrow keys being assigned an Abstract action (key string ) in to the
    inputMap first . Then an Action is assigned in the ActionMap object
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0) ,"validateBeforeTabbingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1) ,"validateBeforeShiftTabbingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0) ,"validateBeforeMovingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT,0) ,"validateBeforeMovingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0) ,"validateBeforeMovingUpToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP,0) ,"validateBeforeMovingUpToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0) ,"validateBeforeMovingLeftToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT,0) ,"validateBeforeMovingLeftToCell");
    table.getActionMap().put("validateBeforeTabbingToNextCell",
    new validateBeforeTabbingToNextCell());
    table.getActionMap().put("validateBeforeShiftTabbingToNextCell",
    new validateBeforeShiftTabbingToNextCell());
    table.getActionMap().put("validateBeforeMovingToNextCell",
    new validateBeforeMovingToNextCell());
    table.getActionMap().put("validateBeforeMovingDownToCell",
    new validateBeforeMovingDownToCell());
    table.getActionMap().put("validateBeforeMovingUpToCell",
    new validateBeforeMovingUpToCell());
    table.getActionMap().put("validateBeforeMovingLeftToCell",
    new validateBeforeMovingLeftToCell());
    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    return table;
    * A table model is created here for 5 rows/5 columns.
    * And the isCellEditable is overridden to return true,
    * indicating that the cell can be edited.
    * So fine tuned control can be done here by saying,
    * the user can be allowed to edit Row 1,3 or 5 only.
    * or column 1 only etc..
    * @return DefaultTableModel
    private DefaultTableModel createModel() {
    DefaultTableModel model = new DefaultTableModel(5, 5) {
    public boolean isCellEditable(int row, int column) {
    return true;
    return model;
    * This method basically returns the currentRow/currentCol value
    * If the current Row/Col is being edited then
    * it returns the getEditingRow/getEditingColumn
    * If its not being edited,
    * it return the getAnchorSelectionIndex of the JTables
    * ListSelectionModel.
    * If the column or row is -1, then it return 0.
    * The first element in the int[] array is the row
    * The second element in the int[] array is the column
    * @param t input a JTable
    * @return int[]
    * @see ListSelectionModel
    * @see JTable
    private int[] getCurrentRowAndColumn(JTable t){
    int[] currentRowAndColum = new int[2];
    int row, column;
    if (t.isEditing()) {
    row = t.getEditingRow();
    column = t.getEditingColumn();
    } else {
    row = t.getSelectionModel().getAnchorSelectionIndex();
    if (row == -1) {
    if (t.getRowCount() == 0) {
    //actually this should never happen.. we need to return an exception
    return null;
    column =t.getColumnModel().getSelectionModel().getAnchorSelectionIndex();
    if (column == -1) {
    if (t.getColumnCount() == 0) {
    //actually this should never happen.. we need to return an exception
    return null;
    column = 0;
    currentRowAndColum[0]=row;
    currentRowAndColum[1]=column;
    return currentRowAndColum;
    * Tbis basically a wrapper method for CellEditors,
    * stopCellEditing method.
    * We need to do this because,
    * for instance we have entered a value in Cell[0,0] as 3
    * and when we press TAB or mouse click or any other relevant
    * navigation keys,
    * ** IF the cell is BEING EDITED,
    * when we do a getValueAt(cellrow,cellcol) at the TableModel
    * level , it would return "null". To overcome this problem,
    * we tell the cellEditor to stop what its doing. and then
    * when you do a getValueAt[cellrow,cellcol] it would
    * return us the current cells value
    * @param t Input a JTable
    * @see CellEditor
    private void stopCurrentCellBeingEdited(JTable t){
    CellEditor ce = t.getCellEditor(); /*this not the ideal way to do..
    since there is no way the CellEditor could be null.
    But a nullpointer arises when trying to work with mouse.. rather than just
    keyboard" */
    if (ce!=null) {
    ce.stopCellEditing();
    * The following Action class handles when a
    * RIGHT ARROW or NUMERIC RIGHT ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to the
    * next Cell.. else take it back to the currentCell
    class validateBeforeMovingToNextCell extends AbstractAction {
    * The following Action class handles when a
    * DOWN ARROW or NUMERIC DOWN ARROW is pressed.
    * There is just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to
    * down by one Cell.. else take it back to the currentCell
    * @param e
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column++;
    if (column >= t.getColumnCount())
    column = column-1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * DOWN ARROW or NUMERIC DOWN ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to the
    * down by Cell.. else take it back to the currentCell
    class validateBeforeMovingDownToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    row++;
    if (row >= t.getRowCount())
    row = row - 1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * UP ARROW or NUMERIC UP ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeMovingUpToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    row--;
    if (row <0)
    row = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * LEFT ARROW or NUMERIC LEFT ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeMovingLeftToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column--;
    if (column <0)
    column = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a TAB is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeTabbingToNextCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column++;
    int rows = t.getRowCount(), columns = t.getColumnCount();
    while (row < rows) {
    while (column < columns) {
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    column++;
    row++;
    column = 0;
    row = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a SHIFT TAB is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeShiftTabbingToNextCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column--;
    int rows = t.getRowCount(), columns = t.getColumnCount();
    while ((row < rows) && (row >= 0)) {
    while ((column < columns) && (column >= 0)) {
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    column--;
    row--;
    column = columns - 1;
    row = rows - 1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    public static void main(String[] args) {
    new TableCellValidator();

  • Export JTable Column headers to Excel document

    Hello all!!! I am having a small problem while trying to export some data from a jTable to an excel document.
    I have a jTable and I use a custom TableModel with this:
    private String[] columnNames = {"First", "Second", "Third", "Forth"};as names for each column of the table.
    The thing I am trying to do is to export exactly the same "headers" from the columns of the jTable to the excel spreadsheet using Jakarta POI. Unfortunately I don't know how to do it and I haven't found anything yet on this forum. Can anyone help me with this?
    In simple words I want to know how I can have the same headers from my jTable columns, with the headers from the excel doument I will create.
    Many thanks in advanve!!!
    Kostas

    Thank you for your reply first of all. The problem is how to get the heading text and how to put it to the excel's first row OR to excels "headings" (if it is possible...). [in other words replace A,B,C,D from the excel document with the headers I get from the jTable...] .
    I hope now you can see what I am looking for... If there is no solution to this please tell me what are the alternatives. (B) could be a good example.
    Thanks you very much!!
    Kostas

  • Custom JTable column (JCheckBox) not included in row selection.

    I am trying to use JCheckBox (for display only data) as one of my JTable columns. I have written custom cell renderer for the same. Every thing is working fine except that when I select a row, the new custom JCheckBox column is not included in selection. Here is the code that I am using.
        protected class CheckBoxColumnRenderer extends DefaultTableCellRenderer {
            JCheckBox ckb = new JCheckBox();
            public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
                if (value instanceof Boolean) { // Boolean
                  ckb.setSelected(((Boolean) value));
                  ckb.setHorizontalAlignment(JLabel.CENTER);
                  ckb.setBackground(super.getBackground());
                  if (isSelected || hasFocus) {
                      ckb.setBackground(table.getSelectionBackground());
                return ckb;
        }How can I include the custom cell in the row selection.
    regards,
    nirvan.

    they have lots of dependencies and it is not always easy to strip out an SSCCE without a considerable effort.Exactly. And is the cause of the problem the dependencies or something else. The only way to know for sure is to strip out the code and simplify the problem, that way you truly understand what the problem is.
    The majority of time this can be done with minimal effort as in this case.
    Some times we are sure that the problem is with certain part of the code Is the problem the code or the way the code is invoked? How do we know the TableModel is created properly or that the column class is overwritten correctly when we can't see it?
    someone having a third look at it may actually find the enhancement required with ease.Exactly, but we need to see the big picture.
    So are you sure that I should post an SSCCE with every possible question where coding is involved ?In the majority of cases a SSCCE is easily created in 5-10 minutes, so if you want the fastest help then yes.
    Just twice this past week I was ready to ask a question on the forum and was preparing a SSCCE to post and sure enough both times the creation of the SSCCE caused me to look at the problem differently and I solved it. I would much rather solve a problem on my own then post a question and wait for hours (days) hoping someone else knows the answer.

  • Count the displayed date rows on a column.

    Hi,
    I am trying to have a table with the following information and try to give a total count (of the dates visible) at the bottom of the table for the date columns. (not counting the rows)
    (E.g.- Under the Sent column there are 5 dates displayed and there are 6 numbers associated. On the received column there are 3 dates displayed for 6 numbers)
    Could you please advice me how to accomplish this. Thank you in advance.
    Rob.
    Name SENum SentReceived
    John      1234     12/22/06     
         5678     12/13/06     
         6565     12/19/06     1/6/07
         5656 - -
    Jane     9866 12/18/06     1/5/07
    Jim     5657 12/18/06 12/14/06           
    Total:           5      3

    I ma not sue what you want but
    here is some idea at sql plus
    SQL> compute count of ename on deptno
    SQL> compute count of sal on deptno
    SQL> select deptno,ename,sal from emp order by deptno
      2  ;
        DEPTNO ENAME                                                     SAL
            10 CLARK                                                    2450
               KING                                                     5000
               MILLER                                                   1300
    count                                                       3          3
            20 SMITH                                                     880
               ADAMS                                                    1100
               FORD                                                     3000
               SCOTT                                                    3000
               JONES                                                    2975
    count                                                       5          5
            30 ALLEN                                                    1600
               BLAKE                                                    2850
               MARTIN                                                   1250
               JAMES                                                    1045
               TURNER                                                   1500
               WARD                                                     1250
    count                                                       6          6
               DEV                                                      5000
    count                                                       1          1

  • User cannot resize jTables� columns

    Hello,
    Using NetBeans IDE 3.5.1, I built a jTable, controlled by a
    JScrollpane.
    My problem is that the user cannot resize the jTables� columns.
    Maximum details:
    1.     jtablewidth is set to a fixed value according to internal data:
    JTable1.setPreferredSize( new Dimension(tableWidth, i_TableHeight));
    2.     columnwidth is set according to internal data:
    Col = JTable1.getColumnModel().getColumn(i);
    Col.setWidth(width);
    Col.setResizable(true);
    Col.setMinWidth(width);
    3.     jTable header details:
    JTableHeader anHeader = JTable1.getTableHeader();
    anHeader.setReorderingAllowed(false);
    anHeader.setResizingAllowed(true);
    4.     JTable1.getTableHeader().setResizingAllowed(true);.
    5.     Initial declerations:
    a.     JTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
         JTable1.setColumnSelectionAllowed(true);
         JTable1.setDragEnabled(true);
         JTable1.setPreferredScrollableViewportSize(new
    java.awt.Dimension(650, 500));
         JTable1.setPreferredSize(new java.awt.Dimension(1200, 409));
         JTable1.setRequestFocusEnabled(false);
    b.     JScrollPane1.setMaximumSize(new java.awt.Dimension(750, 412));
         JScrollPane1.setPreferredSize(new java.awt.Dimension(750,
    412));
         JScrollPane1.setViewportView(JTable1);
         JScrollPane1.setAutoScolls(false);
    c.     Jtable.autoCreateColumnsFromModel (true);
    Thanks alot,
    Itay

    Columns resizing works by default. You don't need to do anything special.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Easier way to set post-constructor JTable column names?

    I have a class that extends JTable. It also has a pair of inner classes that extend DefaultTableCellRenderer and AbstractTableModel so I can dynamicaly adjust the number of rows and their contents. That's not the problem - that part works fine. The problem is the column headers. My table doesn't currently have any but I want to add them.
    The column quantity is constant at 3 and should always be the same 3 Strings. It would be nice if I could use the JTable constructors that take a Vector or Object[] of column names from the start in my new class' constructor. But I don't think I can because at that point I don't know how many rows there will be or what they'll contain. Trying to set rowData to null just caused runtime exceptions.
    So the alternative seems to be to call setColumnModel() within the constructor, passing it a DefaultTableColumnModel. Which then requires I call addColumn() three times. Each time passing it a new TableColumn object. Each of which requires that I separately call setHeaderValue() after I construct it to set the header name. Am I right in that is the only way to do it? It just seems overly complex.

    I'll post a streamlined version of my class in case that will help...
    public class TotalsTable extends JTable
       private static int NUM_COLUMNS = 3;
       static final public String columnNames[] = {
             "Col Name 1", "Col Name 2", "Col Name 3"};
       protected Vector data = null;
       private TotalsModel tableModel;
       public TotalsTable()
          tableModel = new TotalsModel();
          setModel(tableModel);
          TableCellRenderer renderer = new TotalsCellRenderer();
          setDefaultRenderer(Object.class, renderer);
       public void updateTable(Vector pData)
          data = pData;
          tableModel.update();
       class TotalsCellRenderer extends DefaultTableCellRenderer
          public Component getTableCellRendererComponent
             (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
             super.getTableCellRendererComponent(table, value, isSelected,
                                                 hasFocus, row, column);
             if (column == 0) {
                setForeground(Color.blue);
             else {
                setForeground(Color.black);
             return this;
       class TotalsModel extends AbstractTableModel
          public TotalsModel()
             super();
          protected void update()
             fireTableStructureChanged();
           * Retrieves number of columns
           * (Necessary for AbstractTableModel implementation)
          public synchronized int getColumnCount()
             return NUM_COLUMNS;
          public synchronized int getRowCount()
             if (playerData == null)
                System.out.println("No rows found in table");
                return 0;
             else
                return playerData.size();
           * Returns cell information of a record at location row,column
           * (Necessary for AbstractTableModel implementation)
          public synchronized Object getValueAt(int row, int column)
             try
                MyObject p = (MyObject) data.elementAt(row);
                switch (column)
                   case 0:
                      return p.getName();
                   case 1:
                      return ("" + p.getDataItem2());
                   case 2:
                      return ("" + p.getDataItem3());
                   default:
                      System.out.println("getValueAt() Error: Invalid column");
             catch (Exception e)
                System.out.println("Exception in getValueAt(): " +
                                   e.getMessage());
             return "";
          public String getColumnName(int col)
             if (col < NUM_COLUMNS)
                return columnNames[col];
             else
                return "";
          public Class getColumnClass(int c)
             return getValueAt(0, c).getClass();
    }

  • Data visibility in OBIEE Dashboards

    HI,
    I have a data visibility requirement and criteria is as shown below.
    we have employee hierarchy table and it is flattened data with columns below
    emp name, emp num, GM name, GM num, Manager name, Manager Num.
    Hierarchy is GM<Manager<Employee(lowest)
    GM can see only his and HIS managers data, manager can see only his and subordinates. employee(subordinate) can see his data only.
    How can I achive this?
    Please explain it to me in detail.
    thanks
    Jay.

    Jay,
    If you are using 10g then in security manager>groups you can create different groups for each set of users like GM would come under GM group, managers would come under managers group and so forth.
    Then in the group permissions filter you could add a custom filter based on your requirement. In this case if the data at the backend has some id specifying the hierarchy level filter based on that.
    Hope I made it clear.
    Cheers
    Rem

  • Help with JTable column width

    Hi,
    I'm trying to resize my JTable columns with this code, but it's not working. What I am doing wrong?
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
    TableColumn tc = table.getColumnModel().getColumn(i);
    int width = (i == 0)? 10 : table.getWidth()/2 - 10; // three columns
    tc.setPreferredWidth(width);
    Thanks,
    Andr�

    Now my problem is that using either of these methods
    is they don't carry the user's selected column width
    through updates.It sounds like the change event your table model is firing is causing the entire table to be rebuilt. I would guess that you are firing fireTableStructureChanged() which would cause the entire table to be rebuilt (columns, cell values, etc.) Just fire a change event for the minimum necessary. If you can't identify what data in your table has changed (to fire cell or row change events), but the structure (columns) of the table hasn't changed, just fire fireTableDataChanged(). This will cause the cells to be redrawn with the new values, but shouldn't cause the columns to be rebuilt and resized.

  • Setting size of JTable columns

    Hi everybody,
    Can anyone help me ?
    How can I set a column widths of a JTable, but also allow the user to resize them ?
    I tried with a code like
    TableColumnModel tableColumnModel = table.getColumnModel();
    for (int i=0; i < columnsSizes.length; i++) {
       if (columnsSizes[i] > 0) {
            tableColumnModel.getColumn(i).setPreferredWidth(preferedSizeArray);
    But it doesn't work :(
    When i do [ define the minWidth and maxWidth ]
    TableColumnModel tableColumnModel = table.getColumnModel();
    for (int i=0; i < columnsSizes.length; i++) {
        if (columnsSizes[i] > 0) {
            tableColumnModel.getColumn(i).setMinWidth(preferedSizeArray);
    tableColumnModel.getColumn(i).setMaxWidth(preferedSizeArray[i]);
    Columns's sizes are exactly what i want but ... the colums are no more resizable.
    So,
    if anyone can help me and tell me how can i set a predefined size for some colums and also allow the user to resize them ... that would be kind from him.
    Thanks

    Hi guys,
    It's me again ... but I tried your tricks and they don't work :(
    Look this example :
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    public class JTableResizing extends JFrame implements ActionListener {
        private JScrollPane scpnl = new JScrollPane();
        private JButton btnClose = new JButton();
        Object[][] data={   new Object[]{"Hi", "everybody", "this is ", "a row"},
                            new Object[]{"and ", "this ", "is the second", "row"},
                            new Object[]{"of a", "very ","usefull","jtable"}
        Object[] columnNames={"Column1", "Column2", "Column3", "Column4"};
        TableModel dataModel=new DefaultTableModel(data, columnNames);
        private JTable jTable = new JTable(dataModel);
        public JTableResizing() {
            try {
                /* We don't care about this code !! just see the code below !
                 * It has been made really quick [and dirty :D]
                this.setSize(new Dimension(530, 400));
                this.getContentPane().setLayout(new GridBagLayout());
                btnClose.setText("close");
                btnClose.addActionListener(this);
                scpnl.getViewport().add(jTable, null);
                this.getContentPane().add(scpnl,    new GridBagConstraints(0, 0, 1, 1, 1.0, 0.5,
                                                                        GridBagConstraints.CENTER,
                                                                        GridBagConstraints.BOTH,
                                                                        new Insets(50, 50, 50, 50),
                                                                        0, 0));
                this.getContentPane().add(btnClose, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
                                                                        GridBagConstraints.CENTER,
                                                                        GridBagConstraints.NONE,
                                                                        new Insets(0, 0, 20, 0),
                                                                        0, 0));
                /* is this really necessary ??? I really don't think so */
                JTableHeader headers = jTable.getTableHeader();
                if (headers != null) {
                    headers.setResizingAllowed(true);
                 * Start watching the code from here.
                 * I created a JTable [jTable] with n columns. Now, I want to fix
                 * a size for some columns and the question is how ?? 
                 * Maybe the easiest way is to create a method !!
                 setColumnsSizes(jTable, new int[]{0, 100, 0, 50});
            } catch(Exception e) {
                e.printStackTrace();
        /* I know, the code is not the best but I don't care !! This is a quick
         * and dirty sample code to make you understand my problem ...*/
        public static void setColumnsSizes(JTable jTable, int[] columnsSizes) {
            /* look the array supplied above.  columnsSizes =  int[]{0,100,0,50}
             * but any array can be supplied !!
             * This one means that the second and the fourth columns should take
             * resectively a width of 100 and 50 and the two others columns
             * the first one and the third one, fill as much as possible depending on
             * the available space in the scrollpane.
             * Also, when I resize the frame, the scrollpane is resized
             * (look the gridbagconstraints above, and also here columns with
             * no prefered size must be
            /* Which mode should I suplpy ? I need an autoresize only for columns
               where no prefered size has been defined and I don't think it exists */
            jTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            TableColumnModel tableColumnModel = jTable.getColumnModel();
            for (int i=0; i < columnsSizes.length; i++) {
                if (columnsSizes[i] > 0) {
                    /* If I define a minimum width, the colum will be resizeable but,
                       we will be unable to resize it under his minSize. This can be
                       a good behaviour !*/
                    tableColumnModel.getColumn(i).setMinWidth(columnsSizes);
    /* If I define a prefered width, I'm not sure it will be the
    width of the column.
    I mean, when I define a prefered size on a column, other
    columns are resized depending of the autoResizeMode !*/
    tableColumnModel.getColumn(i).setPreferredWidth(columnsSizes[i]);
    /* if I define a maxWidth (next line code) the column will be fixed */
    // tableColumnModel.getColumn(i).setMaxWidth(columnsSizes[i]);
    public static void main(String[] args) {
    JTableResizing jTableResizing = new JTableResizing();
    jTableResizing.setLocationRelativeTo(null);
    jTableResizing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jTableResizing.setVisible(true);
    * method performed when clicking on button close
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    Copy, paste and run it and you'll understand the problem.
    Also, try to read comments I added (I think they are understandable, although I know they are full of grammar mistakes, but this is another question ... )
    Thanks for your help.
    And may the force be with you

  • Multi-colored JTable column heading?  How?

    Hi,
    I'm looking for a way to have JTable column heading text
    that can be displayed in multiple colors, so one string
    in one column header, might have each letter a different
    color.
    My application requires highlighting some of the letters
    of a word as red, while others are normal text (black).
    I've been using multi-line strings to simulate vertical
    naming for my column header, for example:
    PPP
    I I I
    N N N
    1 2 3
    for PIN1, PIN2, PIN3. The column data has a binary
    one or zero for each pin, grouped together in one JTable
    column. In my application, if there is an error, I want to
    color just the text representing, say PIN2 red and leave
    the surrounding PIN1 and PIN3 black.
    What approach should I take for doing this with JTable?
    Thanks!
    John Roberts
    [email protected]

    You should override the default cell renderer used by Java
    - JTable.getTableHeader().setDefaultRenderer(yourRenderer)
    Extend yourRenderer from JLabel and use HTML tags to change the color.
    - setText on JLabel with the HTML code like "<HTML> <BODY> <FONT COLOR="red"> A </FONT> <FONT COLOR="green"> B </FONT></BODY> </HTML>"

Maybe you are looking for

  • Small CF card reader that works with the iPad Camera Kit?

    I'm looking for a small (not much bigger than a CF card) CF Card reader that works with the iPad Camera kit (USB piece) - Anyone know of one? All the ones I see people suggesting are big and bulky (made for a desktop). I know there are many smaller o

  • My laptop continually tries to connect to HP3050 wireless even if I am not near the printer.

    HP3050 wireless printer Samsung Laptop with Win 7 SP1 My laptop every minute or two runs a program in the background. I see an egg next to the mouse pointer. I used Process Explorer to establish that it is trying to connect to HP3050 wirelessly. This

  • Portal does not start after RI installation

    Hi, we installed the EP 6 with the RI. The installation went through all steps without problems. At the end, when the portal should come up, the server does not start. The only message I receive in the trace log is: arguments   :     arg[00] : C:\usr

  • Playback stops after about 15 - 20 frames

    This is a problem that I also have in cs4.  I hit the space bar, after about 15 - 20 frames it stops.  Looking at the task manager CPU utilization goes from about 4% to 100% and then playback stops. System is an intel dual core running at 2.13 I thin

  • Lightroom 2.7 suddenly won't allow importing

    I've been using a legally purchased copy of Lightroom 2 for a couple of years now with no problems, until one day a couple months ago the program won't allow the import of any new photos. The error message I get says simply "Some import operations co