Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: Общие вопросы > Как скрыть колонку в таблице?


Автор: Slanix 20.7.2004, 11:02
Подскажите, как можно спрятать колонку в JTable.

Автор: redrick 20.7.2004, 13:26
попробуйте так :

Код


/*.....
тут где  то ваша JTable table определена
.....*/

DefaultTableColumnModel dtcm = (DefaultTableColumnModel)(table.getTableHeader().getColumnModel());
dtcm.removeColumn(dtcm.getColumn( <номер удаляемой колонки> ))



ну а если нужно именно просто скрыть, а не удалять, то просто

Код


/*.....
тут где  то ваша JTable table определена
.....*/

DefaultTableColumnModel dtcm = (DefaultTableColumnModel)(table.getTableHeader().getColumnModel());
dtcm.getColumn( <номер скрываемой колонки> ).setWidth(0);
dtcm.getColumn( <номер скрываемой колонки> ).setResizeable(false);



сейчас прямо не могу проверить - но я вроде так делал и работало (хотя смахивает на хак какой то, может кто скажет как по-человечески это сделать)

Автор: DarkDS 20.7.2004, 14:08
Цитата(redrick @ 20.7.2004, 13:26)
попробуйте так :

Код

ну а если нужно именно просто скрыть, а не удалять, то просто

[CODE]

/*.....
тут где  то ваша JTable table определена
.....*/

DefaultTableColumnModel dtcm = (DefaultTableColumnModel)(table.getTableHeader().getColumnModel());
dtcm.getColumn( <номер скрываемой колонки> ).setWidth(0);
dtcm.getColumn( <номер скрываемой колонки> ).setResizeable(false);



сейчас прямо не могу проверить - но я вроде так делал и работало (хотя смахивает на хак какой то, может кто скажет как по-человечески это сделать)

Если у колонки будет название и выставлен быдет авторесайз у таблицы, то этот код не скроет колонки, а лишь сделает ее размером с заголовок....

Автор: Domestic Cat 20.7.2004, 19:31
По-моему самый лучий вариант - написать свою TableModel. Если вы хотите скрыть колонку
(скажем, при нажатии кнопки), то нужно будет просто отсортировывать
нужные данные из оригинального массива (вектора, итп) во временный, а
временный передавать как модель для JTable:

myTableModel = new MyTableModel(data, columnNames);
table.setModel(myTableModel);

Автор: redrick 21.7.2004, 00:23
2 DarkDS

спасибо, но лучшеб всё же исправили, если знаете как

2 Domestic Cat

а не затормозит всё? а то вдруг там динамика какая и эта колонка должна быстро появляться и исчезать. Создание объекта насколько я понимаю самая неприятная в этом плане вещь.(не считая загрузки класса)

Автор: Domestic Cat 21.7.2004, 01:08
Цитата
а не затормозит всё? а то вдруг там динамика какая и эта колонка должна быстро появляться и исчезать. Создание объекта насколько я понимаю самая неприятная в этом плане вещь.(не считая загрузки класса)


Зависит конечно от ситуации, но вряд ли предполагается что колонкой будут играться smile.gif
Скорее всего речь идет об установках для усера - чего он хочет видеть в тэйбле а чего нет.


Автор: Slanix 21.7.2004, 11:45
Цитата
Зависит конечно от ситуации, но вряд ли предполагается что колонкой будут играться
Скорее всего речь идет об установках для усера - чего он хочет видеть в тэйбле а чего нет.


Почти так, есть колонка в которой содержатся определенные даннае и ее пользователю видеть незачем, там служебная информация.

Автор: DarkDS 21.7.2004, 12:44
Цитата(redrick @ 21.7.2004, 00:23)
2 DarkDS

спасибо, но лучшеб всё же исправили, если знаете как

Самый простой способ - переопределить модель колонок.
Ближе к концу недели кину пример кода...

Автор: Domestic Cat 21.7.2004, 16:38
Вот как я делал когда сдавал SCJD:

ClientTableModel.java
Код

package suncertify.client;

import java.util.Vector;
import java.io.IOException;
import java.rmi.RemoteException;
import javax.swing.table.AbstractTableModel;

/**
* <p>This <code>JTable</code> model provides custom behavior
* for the model portion of the MVC design pattern.</p>
*/
public class ClientTableModel extends AbstractTableModel
{
   private int         columnCount;
   private int         rowCount;
   private String[][]  data;
   private Vector      originalData;
   private String[]    columnNames;
   
   /**
    * This constructor creates the <code>JTable</code> model.
    *
    * @param database <code>Vector</code> containing set of records
    * @param columnNames array containing names of record fields
    */
   public ClientTableModel(Vector database, String[] columnNames)
   {
       this.columnNames = columnNames;
       rowCount = database.size();
       columnCount = columnNames.length;
       data = new String[rowCount][columnCount];
       originalData = database;
       
       // Initialize two-dimensional array of data
       for(int i = 0; i < rowCount; i++)
       {  
           for(int j = 0; j < columnCount; j++)
           {
               data[i][j] = ((String[])originalData.get(i))[j].trim();
           }
       }
   }
   
   /**
    * Returns array associated with given record number.
    *
    * @param   rowIndex the row whose value to be queried
    * @return  array associated with given record number
    */
   public String[] getRecord(int rowIndex)
   {
       /*
        * Do not return reference to original record.
        * It can be changed by client.
        */
       String[] temp = new String[columnCount + 1];
       System.arraycopy((String[])originalData.get(rowIndex), 0, temp, 0, columnCount + 1);
       return temp;
   }
   
   /**
    * Returns the class of cell values in the column.
    *
    * @param   columnIndex the index of the column
    * @return  the class of the object values in the column
    */
   public Class getColumnClass(int columnIndex)
   {
       return getValueAt(0, columnIndex).getClass();
   }
   
   /**
    * Returns the number of columns in the model.
    *
    * @return the number of columns in the model
    */
   public int getColumnCount()
   {
       return columnCount;
   }
   
   /**
    * Returns the number of rows in the model.
    *
    * @return the number of rows in the model
    */
   public int getRowCount()
   {
       return rowCount;
   }
   
   /**
    * Returns the name of the column.
    *
    * @param   columnIndex the index of the column
    * @return  the name of the column
    */
   public String getColumnName(int columnIndex)
   {
       return columnNames[columnIndex];
   }
   
   /**
    * Returns the value for the cell.
    *
    * @param   rowIndex the index of the row
    * @param   columnIndex the index of the column
    * @return  the Value Object at the specified cell
    */
   public Object getValueAt(int rowIndex, int columnIndex)
   {
       return data[rowIndex][columnIndex];
   }
   
   /**
    * Returns true if the cell is editable. In present model table is not editable
    * and this metod always returns false.
    *
    * @param   rowIndex the index of the row
    * @param   columnIndex the index of the column
    * @return  false
    */
   public boolean isCellEditable(int rowIndex, int columnIndex)
   {
       return false;
   }
} //~ End of ClientTableModel



Client.java (не полностью)
Код

     // поля
     private Vector data;
     ....

     // constructor
       table = new JTable();
       setTableModelData();
....
    /**
    * Sets up the <code>JTable</code> model.
    */
   private void setTableModelData()
   {
       clientTableModel = new ClientTableModel(data, columnNames);
       table.setModel(clientTableModel);
       ...
   }

    ....
    /**
    * Searches database with given search criteria
    * (Name and Location in present version). Future functionality
    * enhancements are possible. Search mechanism allows searching for any
    * field (such as smoking/nonsmoking rooms, price, etc), and
    * field values does not have to match exactly.
    * If no records found it tells the user the status message.
    *
    * @param   criteria array of search criteria
    * @return  true if record was found
    */
   private boolean find(String[] criteria)
   {
       Vector foundRecords;
       try
       {
           foundRecords = database.findRecord(criteria);
       }
       catch (ConnectException ce)
       {
           statusLabel.setText(ERROR_COLOR +
                                   "Connection was lost. Please restart application." + END_TAG);
           return false;
       }
       catch(RemoteException re)
       {
           statusLabel.setText(ERROR_COLOR + "RMI error."
                               + " Please restart application" + END_TAG);
           return false;
       }
       catch(RecordNotFoundException re)
       {
           statusLabel.setText(ERROR_COLOR +
                               "No records have been found" + END_TAG);
           return false;
       }

       // Processing found records
       data = foundRecords;
       setTableModelData();
       return true;
   } //~ End of find




Добавлено @ 16:39
Здесь идея такая же.

Автор: redrick 21.7.2004, 22:46
а вот ещё вопрос про таблицу : можно ли в одной из строчек сделать cell шириной в 2 cell (как collspan в html) ?

Автор: Domestic Cat 22.7.2004, 00:04
http://www.senun.com/Left/Programming/Java_old/Examples_swing/JTableExamples7.html

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)