JTable - make first column not scrollable
I like to know using one JTable and JScrollPane to make it generically not scroll for the first column.
Do you set the viewport to start at the second column, if so how?
Thanks
Abraham
Heres a test to run with the renderers and editors for fixed table columns
See source for FixedColumnScrollPane
// import libraries required, no space
public class SimpleTable extends JFrame {
private static class MyTableCellRenderer extends DefaultTableCellRenderer {
public MyTableCellRenderer() {
super();
setOpaque(true);
noFocusBorder = new EmptyBorder(1, 2, 1, 2);
setBorder(noFocusBorder);
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col) {
JLabel renderer = (JLabel) super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, col);
String cellValue = value.toString();
renderer.setHorizontalAlignment(SwingConstants.LEFT);
renderer.setToolTipText(cellValue);
String headerValue = table.getColumnModel().getColumn(col).getHeaderValue().toString();
// Use header value for renderers when splitting table columns, dont check by column index
if (headerValue.length() == 0) {
renderer.setText("Row " + (row+1));
if (cellValue.startsWith("a")) {
renderer.setForeground(Color.blue);
} else if (cellValue.startsWith("b")) {
renderer.setForeground(Color.green);
} else if (cellValue.startsWith("c")) {
renderer.setForeground(Color.blue);
} else if (cellValue.startsWith("d")) {
renderer.setForeground(Color.magenta);
} else if (cellValue.startsWith("e")) {
renderer.setForeground(Color.ORANGE);
return this;
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private JComponent component = null;
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected,
int row, int col) {
this.component = new JTextField(value.toString());
return this.component;
public Object getCellEditorValue() {
if (component instanceof JTextComponent) {
String text = ((JTextComponent) component).getText();
return text;
return null;
public SimpleTable() {
super("Simple JTable Test");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableModel mainTableModel = new AbstractTableModel() {
private static final int ROWS = 1000;
String colValues[] = {"", "a", "b", "c", "d", "e"};
String data[][] = new String[ROWS][colValues.length];
String headers[] = {"", "Column 1", "Column 2", "Column 3", "Column 4", "Column 5"};
public int getColumnCount() {
return colValues.length;
public int getRowCount() {
return ROWS;
public String getColumnName(int col) {
return headers[col];
// Synthesize some entries using the data values & the row #
public Object getValueAt(int row, int col) {
String val = data[row][col];
if (val == null) {
val = colValues[col] + row;
data[row][col] = val;
return val;
public void setValueAt(Object value, int row, int col) {
data[row][col] = value.toString();
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
public boolean isCellEditable(int row, int col) {
return (col > 0);
JTable mainTable = new JTable(mainTableModel);
TableColumnModel mainColumnModel = mainTable.getColumnModel();
for (int i = 0; i < mainColumnModel.getColumnCount(); i++) {
TableColumn tableColumn = mainColumnModel.getColumn(i);
tableColumn.setCellRenderer(new MyTableCellRenderer());
tableColumn.setCellEditor(new MyTableCellEditor());
FixedColumnScrollPane fixedColumnScrollPane
= new FixedColumnScrollPane(mainTable, 1);
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
JLabel fixedLabel = new JLabel("Fixed Column Table");
fixedLabel.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 11));
getContentPane().add(fixedLabel);
getContentPane().add(fixedColumnScrollPane);
public static void main(String args[]) {
SimpleTable st = new SimpleTable();
st.setVisible(true);
}
Similar Messages
-
Making JTable columns 2- n scrollable, not the first column, how?
Id like for my JTable's first column to always be visible, and columns 2->n to be scrollable. The table also follows the sortable table model found from the swing examples...so if the user sorts any of the columns, all the other columns should sort accordingly.
is there anyway i can separate the first column with the others, so that i can put them in their own scrollpanes (first column just scrolls up/down, and 2->n can scroll either way)?I only glanced at the example at the posted link... if memory servers, the trick was to create one JTable but with two different TableModels. To link the two models, you can simply make the getValueAt method in the fixed model call the getValueAt method of the non-fixed model. It's a bit tricky for beginner, but doable.
;o)
V.V. -
JScrollPane scroll setting first column is not visible?
Hi All,
i am using jtable and jscrollpane. in this my first column of 70 pixal width and rest 125 pixal width.set focus is on 1 cell(1 row, 1 column) in table. but due to this scrollbar is slightly on right side whice coz first column not visible.(need to drag for visibility). i am trying to make it visible without dragging.
how to do this? HELP.
i tried with tableScroll.scrollRectToVisible(table.getCellRect(0,0,true )); & -1,-1
but it didnt worked.
Code is like this..........
table = new JTable(64,65){
table.setName("Table");
((DefaultTableModel)table.getModel()).setColumnIdentifiers(vectName.getColumnIdentifiers());
for(int i = 0;i<table.getRowCount();i++) {
table.setValueAt((i+1)+"",i,0);
table.setGridColor(Color.black);
table.setSelectionBackground(new Color(125,255,144));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setCellSelectionEnabled(true);
table.addKeyListener(listener);
table.addMouseListener(listener);
table.getSelectionModel().addListSelectionListener(this);
table.getColumnModel().addColumnModelListener(this);
table.getColumnModel().getColumn(0).setResizable(false);
table.getColumnModel().getColumn(0).setMinWidth(70);
table.getColumnModel().getColumn(0).setMaxWidth(70);
JScrollPane tableScroll = new JScrollPane(table);
Dimension minimumSize = new Dimension(100,25);
tableScroll.setMinimumSize(minimumSize);
add(tableScroll);Hi weebib ,
pls find some working code which shous my problame .
you can see its coming to column 'B'. but i want it to show from column 'A' .
sample working code : =
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.table.*;
import java.util.*;
public class myTable extends JFrame{
JTable table;
JScrollPane jsp;
JPanel p1;
int NO_OF_ROWS = 64;
int NO_OF_COLUMNS = 65;
Vector vColumnNames ;
myTable(){
Container con = getContentPane();
p1 = new JPanel();
table = new JTable(NO_OF_ROWS,NO_OF_COLUMNS){
public boolean isCellEditable(int row, int column) {
if(column == 0){
return false;
else{
return true;
setTableProperties();
jsp = new JScrollPane(table);
p1.add(jsp);
con.add(p1);
setSize(400,500);
show();
//System.out.println("Hello there");
public Vector getColumnIdentifiers(){
vColumnNames = new Vector();
for(int i=65;i<129;i++) {
vColumnNames.add(new String((char)i+""));// setting the alphabets for the column names //orig
return vColumnNames ;
public void setTableProperties(){
((DefaultTableModel)table.getModel()).setColumnIdentifiers(getColumnIdentifiers());
for(int i = 0;i<table.getRowCount();i++) {
table.setValueAt((i+1)+"",i,0);// Set the names of the row
table.setGridColor(Color.black);
table.setSelectionBackground( Color.RED);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setCellSelectionEnabled(true);
table.addMouseListener(new myMouseListener());
table.addKeyListener(new myKeyListener());
// table.getColumnModel().getColumn(0).setPreferredWidth(125);
// table.getColumnModel().getColumn(0).setResizable(false);
// table.getColumnModel().getColumn(0).setMinWidth(70);
// table.getColumnModel().getColumn(0).setMaxWidth(70);
for(int u =0 ;u<64;u++){
if(u==0){
table.getColumnModel().getColumn(u).setPreferredWidth(70);
else{
table.getColumnModel().getColumn(u).setPreferredWidth(200);
table.changeSelection(0,1,false,false);
static public void main(String[] args){
myTable test = new myTable();
test.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){System.exit(0);}
public class myMouseListener extends MouseAdapter{
public void mousePressed(MouseEvent me){
table.repaint();
public class myKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent ke){
if(table.getSelectedColumn() == 0){
ke.consume();
================
pls do reply back if i am doing something wrong.
== Gavin -
Our WPF application uses DataGrid.
One of request is that first column of DataGrid does not show row separator and also does not show Left column separator. So it looks like the first column does not belong to the DataGrid. However, when select a row, the cell of first column still get selected.
How do we make it? Thx!
JaneCHi Magnus,
Thanks for replying our question and provide your solution!
Your solution works by setting "HorizontalGridLinesBrush" and "VerticalGridLinesBrush" to {x:Null} in the DataGrid style and modify "CellStyle" in first column as following:
<DataGridTextColumn MinWidth="32"
Binding="{Binding CellName}"
CanUserReorder="False"
CanUserSort="False"
Header="Cell}"
IsReadOnly="true" >
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="IsEnabled" Value="False"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border BorderThickness="0" BorderBrush="{x:Null}"
Background="{Binding Background, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Margin="-1">
<Grid Background="{TemplateBinding Background}" VerticalAlignment="Center" Height="42">
<ContentPresenter VerticalAlignment="Center"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
We found another way to achieve it by using DataGridRowHeader. The good way to use DataGridRowHeader is that we do not need to make the first column ReadOnly (click on first column does not select whole row anymore). Select RowHeader in a row will select
whole row. Move scroll bar horizontally, the row header still keep in visible area.
<Style TargetType="{x:Type DataGridRowHeader}" x:Key="dataGridRowHeaderStyle">
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="Height" Value="42" />
<Setter Property="SeparatorBrush" Value="{x:Null}" />
<Setter Property="FontSize" Value="16" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridRowHeader}">
<Grid>
<Border x:Name="rowHeaderBorder"
BorderThickness="0"
Padding="3,0,3,0"
Background="{Binding Background, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
BorderBrush="{x:Null}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataGrid>
<DataGrid.RowHeaderStyle>
<Style TargetType="DataGridRowHeader" BasedOn="{StaticResource dataGridRowHeaderStyle}">
<Setter Property="Content" Value="{Binding CellName}" />
<Setter Property="Width" Value="35"/>
</Style>
</DataGrid.RowHeaderStyle>
</<DataGrid>
JaneC -
Making a single column horizontally scrollable for JTable
Hello Everyone and thank you for reading my post.
I have been trying for the last 3 days to make a single column horizontally scrollable on my JTable but for some reason I can not get it to work.
I simplyfied my example to 2 columns and 5 rows where
the rows in the first column have long text and it will have a horizontal scroll bar to scroll to the end of the text, similiar to split in Excel.
The second column it doesn't matter
Thanks again and have a great time,
AlFriend you use table cell renderer for your problem.
The solution would be like:
1. Write cell renderer that displays textfield contained in scrollpane.
2. Apply cell renderer to separate column where you require horizontal scroller. -
JTable containing checkbox column is not getting updated
My application has a JTable and the first column is made up of checkboxes I have added a mouse listener for this table and implementd mousePressed(MouseEvent) method also. So when the user presses the mouse on these checkboxes I will update my loca data structure. Now the problem is this, when the user presses and drags the mouse to some other place(out of the current cell) then the table is not getting updated(the cell is not changing its value). But my local data structure is getting updated as the event is already fired. Please suggest me a solution for this.
Thanks in advance
Varunthanks for your information. Actually I have seen this tutorial before but I think my case is little different. Sorry for not explaining it completely. My table has got a checkbox column header and another checkbox which is not part of the table. The second column in the table contains a user object. User can select rows by clicking on the checkbox header (select all rows/ deselect all rows), by clicking on individual cells or by clicking on the third checkbox provided for a specific purpose. So whenever the user does this "selection" operation I update one member variable in the user object which is in the second column. I tried putting my code in the setValueAt() method of my table model but couldn't make it work because of my lack of experience in swing or programming. So please tell me whether what you have suggested is valid or not. I added a mouse listener because there was a requirement to show some information to the user when he do a double click on one column of the table.
-
Disable first Column in jTable
Hello people my problem is I use jTable and in the table I need to disable first column so that the user is not able to change edit the values that are listed in this column. Please help me with some code samples if possible. Thanks in advance.
A custom table model makes this simple. You just override the isCellEditable method and return false when the column index is 0.
-
How can i make hidden column in JTable
hi, how can i make hidden column in JTable,
basically i have a ID field in JTable, i have to use this ID , but i also dont want to show this ID in JTable.
any idea how ??staiji its not working
i did this :
first :
TableColumnModel columnModel =
usersTable.getColumnModel();TableColumn column =
columnModel.getColumn(1);
usersTable.removeColumn(column);
then when i trying to get this :
Integer userId =
(Integer)usersTable.getValueAt(UserBrowser.this.usersTa
le.getSelectedRow(), 0);
it not give me ID column's value .
i have a column in JTable like :
ID | Username | First name | Last name
i want to hide ID column , but get this ID's value
when user clicks on JTable row.Hi, if you would read the documentation about JTable.getValueAt(...) you will find, that there is a significant difference between this method and the datamodels getValueAt(...) method. JTables getValueAt(...) method interprets column-index as index in its TableColumnModel - in your TableColumnModel there is no column any longer that holds ID values, therefore you were not able to get it by JTable.getValueAt(...). Do not use these methods for the purpose you want it for - you will also get the wrong values, if the user has repositioned columns - the column index is always interpreted as index in the currently used TableColumnModel and IS NOT A MODELINDEX.
greetings Marsian -
JTable Problem (table does not show rows and columns)
Hi All,
What the table is suppose to do.
- Load information from a database
- put all the values in the first column
- in the second column put combobox (cell editor with numbers 1-12)
- the 3rd column put another combobox for something else
- the 4th column uses checkbox as an edit
The number of rows of the table should be equal to the number of
record from
the database. If not given it default to 20 (poor but ok for this)
The number of columns is 4.
But the table does not show any rows or
column when I put it inside a
JScrollPane (Otherwise it works).
Please help,
thanks in advance.
public class SubjectTable extends JTable {
* Comment for <code>serialVersionUID</code>
private static final long serialVersionUID = 1L;
/** combo for the list of classes */
protected JComboBox classCombo;
/** combo for the list of subjects */
protected JComboBox subjectsCombo;
/** combo for the list of grade */
protected JComboBox gradeCombo;
boolean canResize = false;
boolean canReorder = false;
boolean canSelectRow = false;
boolean canSelectCell = true;
boolean canSelectColumn = true;
// the row height of the table
int rowHeight = 22;
// the height of the table
int height = 200;
// the width of the table
int width = 300;
// the size of the table
Dimension size;
* Parameterless constructor. Class the one of the other constructors
to
* create a table with the a new <code>SubjectTableModel</code>.
public SubjectTable() {
this(new SubjectTableModel());
* Copy constructor to create the table with the given
* <code>SubjectTableModel</code>
* @param tableModel -
* the <code>SubjectTableModel</code> with which to
initialise
* the table.
SubjectTable(SubjectTableModel tableModel) {
setModel(tableModel);
setupTable();
* Function to setup the table's functionality
private void setupTable() {
clear();
// set the row hieght
this.setRowHeight(this.rowHeight);
// set the font size to 12
//TODO this.setFont(Settings.getDefaultFont());
// disble reordering of columns
this.getTableHeader().setReorderingAllowed(this.canReorder);
// disble resing of columns
this.getTableHeader().setResizingAllowed(this.canResize);
// enable the horizontal scrollbar
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// disable row selection
setRowSelectionAllowed(this.canSelectRow);
// disable column selection
setColumnSelectionAllowed(this.canSelectColumn);
// enable cell selection
setCellSelectionEnabled(this.canSelectCell);
setPreferredScrollableViewportSize(getSize());
TableColumn columns = null;
int cols = getColumnCount();
for (int col = 0; col < cols; col++) {
columns = getColumnModel().getColumn(col);
switch (col) {
case 0:// subject name column
columns.setPreferredWidth(130);
break;
case 1:// grade column
columns.setPreferredWidth(60);
break;
case 2:// class room column
columns.setPreferredWidth(120);
break;
case 3:// select column
columns.setPreferredWidth(65);
break;
} // end switch
}// end for
// set up the cell editors
doGradeColumn();
doClassColumn();
//doSubjectColumn();
* Function to clear the table selection. This selection is different
to
* <code>javax.swing.JTable#clearSelection()</code>. It clears the
user
* input
public void clear() {
for (int row = 0; row < getRowCount(); row++) {
for (int col = 0; col < getColumnCount(); col++) {
if (getColumnName(getColumnCount() - 1).equals("Select")) {
setValueAt(new Boolean(false), row, getColumnCount() - 1);
}// if
}// for col
}// for row
* Function to set the cell renderer for the subjects column. It uses
a
* combobox as a cell editor in the teacher's subjects table.
public void doSubjectColumn() {
TableColumn nameColumn = getColumnModel().getColumn(0);
nameColumn.setCellEditor(new DefaultCellEditor(getSubjectsCombo()));
// set up the celll renderer
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for drop down list");
nameColumn.setCellRenderer(renderer);
// Set up tool tip for the sport column header.
TableCellRenderer headerRenderer = nameColumn.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer) headerRenderer)
.setToolTipText("Click the Name to see a list of choices");
}// end doSubjectsColumn----------------------------------------------
/** Function to set up the grade combo box. */
public void doGradeColumn() {
TableColumn gradeColumn = getColumnModel().getColumn(1);
gradeColumn.setCellEditor(new DefaultCellEditor(getGradeCombo()));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for drop down list");
gradeColumn.setCellRenderer(renderer);
// Set up tool tip for the sport column header.
TableCellRenderer headerRenderer = gradeColumn.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer) headerRenderer)
.setToolTipText("Click the Grade to see a list of choices");
}// end doGradeColumn-------------------------------------------------
* Function to setup the Class room Column of the subjects
public void doClassColumn() {
// set the column for the classroom
TableColumn classColumn = getColumnModel().getColumn(2);
classColumn.setCellEditor(new DefaultCellEditor(getClassCombo()));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for drop down list");
classColumn.setCellRenderer(renderer);
// Set up tool tip for the sport column header.
TableCellRenderer headerRenderer = classColumn.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer) headerRenderer)
.setToolTipText("Click the Class to see a list of choices");
}// end doClassColumn--------------------------------------------------
* Function to get the size of the table
* @return Returns the size.
public Dimension getSize() {
if (this.size == null) {
this.size = new Dimension(this.height, this.width);
return this.size;
* Function to set the size of the table
* @param dim
* The size to set.
public void setSize(Dimension dim) {
if (dim != null) {
this.size = dim;
return;
* Function to create/setup the class room comboBox. If the comboBox
is
* <code>null</code> a nwew one is created else the functon returns
the
* function that was returned initially.
* @return Returns the classCombo.
private JComboBox getClassCombo() {
if (this.classCombo == null) {
this.classCombo = new JComboBox();
// fill up the class name combo
ArrayList classRooms = new ArrayList();
try {
//TODO classRooms = Settings.getDatabase().getClassRooms();
for (int i = 0; i < 10; i++) {
String string = new String("Class");
string += i;
if (!classRooms.isEmpty()) {
classRooms.trimToSize();
for (int i = 0; i < classRooms.size(); i++) {
this.classCombo.addItem(classRooms.get(i));
} catch (Exception e) {
e.printStackTrace();
return this.classCombo;
* Function to create/setup the subjects comboBox. If the comboBox is
* <code>null</code> a nwew one is created else the functon returns
the
* function that was returned initially.
* @return Returns the subjectsCombo.
private JComboBox getSubjectsCombo() {
if (this.subjectsCombo == null) {
this.subjectsCombo = new JComboBox();
try {
ArrayList subjects = loadSubjectsFromDatabase();
if (!subjects.isEmpty()) {
Iterator iterator = subjects.iterator();
while (iterator.hasNext()) {
// create a new subject instance
//TODO Subject subct = new Subject();
// typecast to subject
//TODO subct = (Subject) iterator.next();
String name = (String) iterator.next();
// add this subject to the comboBox
//TODO this.subjectsCombo.addItem(subct.getName());
subjectsCombo.addItem(name);
}// end while
}// end if
else {
JOptionPane.showMessageDialog(SubjectTable.this,
"Subjects List Could Not Be Filled");
System.out.println("Subjects List Could Not Be Filled");
} catch (Exception e) {
e.printStackTrace();
return this.subjectsCombo;
* Function to load subjects from the <code>Database</code>
* @return Returns the subjects.
private ArrayList loadSubjectsFromDatabase() {
// list of all the subject that the school does
ArrayList subjects = new ArrayList();
try {
//TODO to be removed later on
for (int i = 0; i < 10; i++) {
String string = new String("Subject");
string += i;
subjects.add(i, string);
// set the school subjects
//TODO subjects = Settings.getDatabase().loadAllSubjects();
} catch (Exception e1) {
e1.printStackTrace();
return subjects;
* Function to create/setup the grade comboBox. If the comboBox is
* <code>null</code> a nwew one is created else the functon returns
the
* function that was returned initially.
* @return Returns the gradeCombo.
private JComboBox getGradeCombo() {
if (this.gradeCombo == null) {
this.gradeCombo = new JComboBox();
// fill with grade 1 to 12
for (int i = 12; i > 0; i--) {
this.gradeCombo.addItem(new Integer(i).toString());
return this.gradeCombo;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
System.out.println("Look and Feel has been set");
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
SubjectTableModel model = new SubjectTableModel();
int cols = model.getColumnCount();
int rows = model.getRowCount();
Object[][] subjects = new Object[rows][cols];
for (int row = 0; row < rows; row++) {
subjects[row][0] = new String("Subjectv ") + row;
}//for
model.setSubjectsList(subjects);
SubjectTable ttest = new SubjectTable(model);
JFrame frame = new JFrame("::Table Example");
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(ttest);
frame.getContentPane().add(scrollPane);
frame.pack();
frame.setVisible(true);
**************************************END
TABLE******************************
----------------------------THE TABLE
MODEL----------------------------------
* Created on 2005/03/21
* SubjectTableModel
package com.school.academic.ui;
import javax.swing.table.AbstractTableModel;
* Class extending the <code>AbstractTableModel</code> for use in
creating the
* <code>Subject</code>s table. In addition to the implemented methods
of
* <code>AbstractTableModel</code> The class creates a model that has
initial
* values - the values have their own <code>getter</code> and
* <code>setter</code> methods - but can still be used for values that
a user
* chooses.
* <p>
* @author Khusta
public class SubjectTableModel extends AbstractTableModel {
* Comment for <code>serialVersionUID</code>
private static final long serialVersionUID = 3257850978324461113L;
/** Column names for the subjects table */
String[] columnNames = { "Subject", "Grade", "Class Room",
"Select" };
/** Array of objects for the subjects table */
Object[][] subjectsList;
private int totalRows = 20;
protected int notEditable = 0;
* Parameterless constructor.
public SubjectTableModel() {
// TODO initialise the list
// add column to the default table model
this.subjectsList = new
Object[getTotalRows()][getColumnNames().length];
* Copy constructor with the <code>subjectList</code> to set
* @param subjects
public SubjectTableModel(Object[][] subjects) {
this(0, null, subjects, 0);
* Copy constructor with the initial number of row for the model
* @param rows -
* the initial rows of the model
* @param cols -
* the initial columns of the model
* @param subjects -
* the initial subjects for the model
* @param edit - the minimum number of columns that must be
uneditable
public SubjectTableModel(int rows, String[] cols, Object[][]
subjects, int edit) {
// set the initial rows
setTotalRows(rows);
// set the column names
setColumnNames(cols);
// set the subjectlist
setSubjectsList(subjects);
//set not editable index
setNotEditable(edit);
* Function to get the total number of columns in the table
* @return int -- the columns in the table
public int getColumnCount() {
if (this.subjectsList == null) {
return 0;
return getColumnNames().length;
* Function to get the total number of rows in the table
* @return int -- the rows in the table
public int getRowCount() {
if (this.subjectsList == null) {
return 0;
return this.subjectsList.length;
* Function to get the name of a column in the table.
* @param col --
* the column to be named
* @return String -- the column in the table
public String getColumnName(int col) {
if (getColumnNames()[col] != null) {
return getColumnNames()[col];
return new String("...");
* Function to get the value of the given row.
* @param row --
* the row of the object.
* @param col --
* the col of the object.
* @return Object -- the value at row, col.
public Object getValueAt(int row, int col) {
return getSubjectsList()[row][col];
* Function to return the data type of the given column.
* @param c --
* the column whose type must be determined.
* @return Class -- the type of the object in this col.
public Class getColumnClass(int c) {
if (getValueAt(0, c) != null) {
return getValueAt(0, c).getClass();
return new String().getClass();
* Function to put a value into a table cell.
* @param value --
* the object that will be put.
* @param row --
* the row that the object will be put.
* @param col --
* the col that the object will be put.
public void setValueAt(Object value, int row, int col) {
* TODO: Have a boolean value to determine whether to clear or
to set.
* if true clear else set.
if (value != null) {
if (getSubjectsList()[0][col] instanceof Integer
&& !(value instanceof Integer)) {
try {
getSubjectsList()[row][col] = new
Integer(value.toString());
fireTableCellUpdated(row, col);
} catch (NumberFormatException e) {
* JOptionPane .showMessageDialog( this., "The \""
+
* getColumnName(col) + "\" column accepts only
values
* between 1 - 12");
return;
System.out.println("Value = " + value.toString());
System.out.println("Column = " + col + " Row = " + row);
// column = Grade or column = Select
switch (col) {
case 2:
try {
// TODO
if (Boolean.getBoolean(value.toString()) == false
&& getValueAt(row, 0) != null
&& getValueAt(row, 1) != null
&& getValueAt(row, 2) != null) {
// subjectsList[row][col + 1] = new
Boolean(true);
System.out.println("2. false - Updated...");
* this.subjectListModel.add(row,
* this.subjectsList[row][0] + new String(" -
") +
* this.subjectsList[row][2]);
} catch (ArrayIndexOutOfBoundsException exception) {
exception.printStackTrace();
break;
case 3:
if (Boolean.getBoolean(value.toString()) == false
&& getValueAt(row, 0) != null
&& getValueAt(row, 1) != null
&& getValueAt(row, 2) != null) {
System.out.println("3. If - Added...");
getSubjectsList()[row][3] = new Boolean(true);
this.subjectListModel.addElement(this.subjectsList[row][0] +
* new String(" - ") + this.subjectsList[row][2]);
// subjectListModel.remove(row);
fireTableCellUpdated(row, col);
fireTableDataChanged();
// this.doDeleteSubject();
} else if (Boolean.getBoolean(value.toString()) ==
true
&& getValueAt(row, 0) != null
&& getValueAt(row, 1) != null
&& getValueAt(row, 2) != null) {
setValueAt("", row, col - 1);
setValueAt("", row, col - 2);
setValueAt("", row, col - 3);
System.out.println("3. Else - Cleared...");
// this.subjectListModel.remove(row);
break;
default:
break;
}// end switch
getSubjectsList()[row][col] = value;
fireTableCellUpdated(row, col);
fireTableDataChanged();
}// end if
}// end
* Function to enable edition for all the columns in the table
* @param row --
* the row that must be enabled.
* @param col --
* the col that must be enabled.
* @return boolean -- indicate whether this cell is editble or
not.
public boolean isCellEditable(int row, int col) {
if (row >= 0
&& (col >= 0 && col <= getNotEditable())) {
return false;
return true;
* Function to get the column names for the model
* @return Returns the columnNames.
public String[] getColumnNames() {
return this.columnNames;
* Function to set the column names for the model
* @param cols
* The columnNames to set.
public void setColumnNames(String[] cols) {
// if the column names are null the default columns are used
if (cols != null) {
this.columnNames = cols;
* Function to get the rows of subjects for the model
* @return Returns the subjectsList.
public Object[][] getSubjectsList() {
if (this.subjectsList == null) {
this.subjectsList = new
Object[getTotalRows()][getColumnNames().length];
return this.subjectsList;
* Function to set the subjects list for the model
* @param subjects
* The subjectsList to set.
public void setSubjectsList(Object[][] subjects) {
// if the subject list is null create a new one
// using default values
if (subjects == null) {
this.subjectsList = new
Object[getTotalRows()][getColumnNames().length];
return;
this.subjectsList = subjects;
* Function to get the total number of rows for the model. <b>NB:
</b> This
* is different to <code>
getRowCount()</code>.<code>totalRows</code>
* is the initial amount of rows that the model must have before
data can be
* added.
* @return Returns the totalRows.
* @see #setTotalRows(int)
public int getTotalRows() {
return this.totalRows;
* Function to set the total rows for the model.
* @param rows
* The totalRows to set.
* @see #getTotalRows()
public void setTotalRows(int rows) {
// if the rows are less than 0 the defaultRows are used
// set getTotalRows
if (rows > 0) {
this.totalRows = rows;
* Function to get the number of columns that is not editble
* @return Returns the notEditable.
public int getNotEditable() {
return this.notEditable;
* Function to set the number of columns that is not editable
* @param notEdit The notEditable to set.
public void setNotEditable(int notEdit) {
if (notEdit < 0) {
notEdit = 0;
this.notEditable = notEdit;
----------------------------END TABLE MODEL----------------------------------I hope you don't expect us to read hundreds of lines of unformatted code? Use the "formatting tags" when you post.
Why are you creating your own TableModel? It looks to me like the DefaultTableModel will store you data. Learn how to use JTable with its DefaultTableModel first. Then if you determine that DefaultTableModel doesn't provide the required functionality you can write your own model. -
JTable howTo: column header = first column??
Hi,
i have created a JTable and with the TableColumnModel i have defined column headers. I now would like to have the first column of my table looking the same way like the column headers.
It shall look similar to what you have in Excel tables: A B C.... = Column headers and 1 2 3 ... = line numbers = first (not editable) column of the table.
I already tried to write an own table renderer which sets the color equal to the color of the headers but it still looks not equal :-( And there is no TableRowModel, right?
How can I achieve this appearance?
Thanks!!!
RobertHere is a simple example to get you started:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=624365 -
Fixed Column and Scrollable JTable problems
I've implemented a table that has the first column fixed, while 2nd to end are scrollable.
following the fixedModel examples, i am able to get this working..but im not able to update it. the exmples tho, subclass AbstractTableModel and use anonymous classes to define it...mine uses a class that subclasses DefaultTableModel..but DefaultTableModel subclasses AbstractTableModel...so i think it should be ok.
i have 2 table models, one for the fixed, and one for the scrollable..they use the same data/column arrays...then i create 2 tables that with these models...
initially i have no data Object[][] data = new Object[0][0]) and a bunch of column names
it works fine..but i have trouble updating it with real data
i use fixedModel.setDataVector(...) and scrollModel.setDataVector(...) to update...but it doesnt work..i dont get any exceptions or anything..just nothing comes up...revalidating the tables doesnt work
if i choose not to use the fixed/scrollable tables..and just use one normal table with setDataVector..it works fine
any ideas?
heres the code:
fixedModel = new SortableTableModel() {
/* for sorting to work correctly */
public Class getColumnClass(int col) {
return getValueAt(0, col).getClass();
public boolean isCellEditable(int row, int col) {
return false;
//new methods
public int getColumnCount() {
return 1;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return (String)columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][0];
fixedModel.setDataVector(data,columnNames);
scrollModel = new SortableTableModel() {
public Class getColumnClass(int col) {
return getValueAt(0, col).getClass();
public boolean CellEditable(int row, int col) {
return false;
//new methods
public int getColumnCount() {
return columnNames.length -1;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return (String)columnNames[col+1];
public Object getValueAt(int row, int col) {
return data[row][col+1];
public void setValueAt(Object obj, int row, int col) {
data[row][col +1] = obj;
scrollModel.setDataVector(data, columnNames);
ListSelectionModel lsm = fixedTable.getSelectionModel();
lsm.addListSelectionListener(new SelectionListener(true));
lsm = scrollTable.getSelectionModel();
lsm.addListSelectionListener(new SelectionListener(false));
fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JViewport viewport = new JViewport();
viewport.setView(fixedTable);
viewport.setPreferredSize(fixedTable.getPreferredSize());i really need to get this fixed..thanks for the help!i fixed the problem a couple days ago
my anonymous class for the fixed and scrollable table models defines the data given from a 2D Object array..and not a vector of vectors, which i was using when setting the data :P
oops...
thanks for the help tho. -
Problem in updating first column header in JTable
hi
I am using JTable in my application. I want to change first column name of JTable every time when a JList is selected. I am using DefaultTableModel for JTable. I added first column in Constructor and another in a method. I have to edit only first column header. How can i do this???
I used this code but it is not working.
table.getColumnModel().getColumn(0).setHeaderValue("Name of column");
table.getTableHeader().resizeAndRepaint();
Your help will be appreciated.
Thanks in advance
Sonaltable.getColumnModel().getColumn(0).setHeaderValue("Name of column");
table.getTableHeader().repaint();Works for me so post a SSCCE ( http://www.sscce.org/ ) that shows the problem. -
Order by in MATERIALIZED VIEW not work successfully with first column (ID)
Dears,
I am trying to create a Materialized View as below:
CREATE MATERIALIZED VIEW HR.MV_EMP
PCTFREE 10
MAXTRANS 255
TABLESPACE users
STORAGE (
INITIAL 65536
MINEXTENTS 1
MAXEXTENTS 2147483645
BUILD IMMEDIATE
REFRESH ON DEMAND
AS
SELECT *
FROM employees
where rownum < 5000 order by employee_id desc ;But while querying the MATERIALIZED VIEW, it did not work successfully as the data did not appear in the accurate order.
I tried to create the same MATERIALIZED VIEW but order by another column (Column Date), it worked successfully and the data appeared in the accurate order.
It means that MATERIALIZED VIEW not work successfully with the first column (id).
Can you please help me in this ?
Thanks & regards,,A few pointers :
1. As has been pointed out, the ROWNUM has been incorrectly placed. ROWNUM values are assigned as rows are fetched from the source before the ORDER BY. You need to ORDER BY first (in a SubQuery) and then ROWNUM afterwards (outside the SubQuery).
2. I wonder why you want only the last 5000 EMPLOYEE_IDs. What if Employee_ID 1 is still an active employee (he is the founder, first employee and CEO ?). There could be very many "low" EMPLOYEE_IDs that are still active.
3. Logically I would expect some filter other than the ROWNUM ... ORDER BY to be used to select candidate rows. Then, an ORDER BY in the CREATE query would be unnecessary.
4. When querying the Materialized View you must explicitly ORDER BY (irrespective of whether you did or did not do an ORDER BY in the CREATE ...)
5. How do you expect to refresh the MV ? Will it always be a COMPLETE Refresh ? Remember that your "5000 employees" filter would likely exclude older employees at the next refresh. If you use some other filter, it should be consistent across all refreshs.
Hemant K Chitale -
(JTable) How can i get the first columns cell in a selected row?
Hello. I am trying to figure out how i can get the first columns cell within a selected row no matter what cell is selected in that row. I have a class that extends AbstractTableModel which represents the table. Now i have another class that extends DefaultSelectionModel. Each model is added to the JTable via setModel(TableModel dataModel), setSelectionModel(ListSelectionModel newModel). Now i don't understand what i have to return from getMaxSelectionIndex(). Any ides? Thanks.
class xTableModel extends AbstractTableModel{
private static String[] cols;
private Object[][] data;
public void setTableModel(Object data[][], String[] cols){
this.cols = cols;
this.data = data;
public String getColumnName(int col){
return cols[col];
public int getRowCount() {
return data.length;
public Object getValueAt(int row, int col) {
return data[row][col];
public void setValueAt(Object value,int row,int col){
data[row][col]=value;
public int getColumnCount(){
return cols.length;
class ColumnListenerModel extends DefaultListSelectionModel{
public int getMaxSelectionIndex(){}int row = table.getSelectedRow();
Object data = table.getValueAt(row, 0); -
How to make table column of the webdynpro application scrollable??
Hi all,
I want to make some columns of my table to be fixed and some to be scrollable...
So if anybody know how to do it..
Please do let me know...
Thanks and regards..Shruti,
If you are using NW 7.0 (NW04s) then check properties:
-- Table.scrollableColCount
-- Column.fixedPosition
Both let you define number of of "fixed" columns at left/right and number of scrollable columns in between.
Valery Silaev
SaM Solutions
http://www.sam-solutions.net
Maybe you are looking for
-
Using constant values in SQL Loader control file
Hi, I have a requirement where I need to migrate the data of 6 tables from MS Access into Oracle data base. I have written SQL Loader scripts so that I can create CSV files based on MS Access data and then migrate into Oracle. But in Oracle tables we
-
Word-Kapitelnummern fehlen in PDF-Lesezeichen
Hallo, wir erstellen umfangreiche Dokumente in MS-Word mit Gliederung und automatischer Nummerierung der Überschriften. Anhand der Word-Überschriften lassen wir im PDF die Lesezeichen erstellen. Seit der Umstellung auf Acrobat Pro 9 wird zwar die Gli
-
I have OSX, vers. 10.5.8. I want to use the Cloud, but I don't want Mountain Lion. Can I do that?
-
Multiple SAP solutions and IGS watchdog
Hello All, I have install two R/3 4.7 servers on Windows 2003 with Oracle 9i as backend, on one machine using MCOD. It has SAP GUI also. The problem is that now if I start the servers using MMC then IGS watchdog service doesn't start in any of the So
-
Export from Discoverer to Excel more than 65K rows
Hi I need to export data from discoverer to excel, in some cases it is more than 65K rows, does any body know if the file can be split in multiple files o worksheets in Excel? Any help will be appreciate Thanks Vladimir