Multiple selections on JTable being screwy
I'm just using an example JTable app to help me decide whether or not I want to use one and it's giving me some trouble. Ctrl+click doesn't give me the behavior I'd expect.
For example, I have a 4x4 cell table. Click on cell 0,0 to select it and it becomes highlighted. Ctrl+click on cell 3,3. Rather than the two cells being highlighted (0,0 and 3,3), four are highlighted (0,0 + 0,3 + 3,0 + 3,3). Is this the way JTables are supposed to work, and if so, what can I do to make it work the way I want (as it does in Excel) ?
Here is the code I'm using
import java.awt.*;
import javax.swing.*;
class AdvancedTableExample
extends JFrame
{
// Instance attributes used in this example
privateJPaneltopPanel;
privateJTabletable;
privateJScrollPane scrollPane;
privateStringcolumnNames[];
privateStringdataValues[][];
// Constructor of main frame
public AdvancedTableExample()
{
// Set the frame characteristics
setTitle("Advanced Table Application" );
setSize( 300, 200 );
setBackground( Color.gray );
// Create a panel to hold all other components
topPanel =new JPanel();
topPanel.setLayout(new BorderLayout() );
getContentPane().add( topPanel );
// Create columns
CreateColumns();
CreateData();
// Create a new table instance
table =new JTable( dataValues, columnNames );
// Configure some of JTable's paramters
table.setRowSelectionAllowed(true );
table.setColumnSelectionAllowed(true );
table.setTableHeader(null);
// Change the selection colour
table.setSelectionForeground( Color.white );
table.setSelectionBackground( Color.red );
// Add the table to a scrolling pane
scrollPane =new JScrollPane( table );
topPanel.add( scrollPane, BorderLayout.CENTER );
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
publicvoid CreateColumns()
{
// Create column string labels
columnNames =new String[8];
for(int iCtr = 0; iCtr < 8; iCtr++ )
columnNames[iCtr] ="Col:" + iCtr;
}
publicvoid CreateData()
{
// Create data for each element
dataValues =new String[100][8];
for(int iY = 0; iY < 100; iY++ )
{
for(int iX = 0; iX < 8; iX++ )
{
dataValues[iY][iX] ="" + iX +"," + iY;
}
}
}
// Main entry point for this example
publicstaticvoid main( String args[] )
{
// Create an instance of the test application
AdvancedTableExample mainFrame=new AdvancedTableExample();
mainFrame.setVisible(true );
}
}

