JTable Selecting Column/Row
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
public class TableDemo extends JPanel {
private boolean DEBUG = false;
public TableDemo() {
super(new GridLayout(1,0));
JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
JScrollPane scrollPane = new JScrollPane(table); //Set up column sizes.
initColumnSizes(table); //Fiddle with the Sport column's cell editors/renderers.
setUpSportColumn(table, table.getColumnModel().getColumn(2)); //Add the scroll pane to this panel.
add(scrollPane);
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel)table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 3; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent( null, column.getHeaderValue(), false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)). getTableCellRendererComponent( table, longValues, false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
public void setUpSportColumn(JTable table, TableColumn sportColumn) {
JComboBox comboBox = new JComboBox();
comboBox.addItem("SnowBoarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
private Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)}, {"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)}, {"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)}, {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)} };
public final Object[] longValues = {"Sharon", "Campione", "None of the above", new Integer(20), Boolean.TRUE};
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
else {
return true;
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
data[row][col] = value; fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
System.out.println();
} System.out.println("--------------------------");
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("TableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableDemo newContentPane = new TableDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() { createAndShowGUI();
According to this Application the rendering and cell editing is done based on the column. And it displays the same column values for each row.
I want to use the same application but want to change the[b] set of column values for each row.
ex:
[u] Column values[/u]
Row 0 = { Snowboarding ,Rowing, Knitting.......}
Row 2 = { A,B,C,..........}
Row 3 = {1,2,3}
Help PLEASE!!!!
thanks
This posting shows one way:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=446022
Similar Messages
-
JTable selecting a row....
I have tried many things to figure out how to select a row using jTable. Nothing works for me, can someone please help. Here are some samples of what I have tried. If you need more information please ask and I will post it immediately. Thanks
Attempt #1
void jTable1_mouseClicked(MouseEvent e) {
ListSelectionModel lm = jTable1.getSelectionModel();
int selectedRow1 = lm.getMinSelectionIndex();
if ((e.getModifiers() & InputEvent.BUTTON1_MASK)!=0) {
int row = jTable1.getSelectedRow();
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Attempt #2
void jButtonSelect_actionPerformed(ActionEvent e) {
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel lm = jTable1.getSelectionModel();
int selectedRow1 = lm.getMinSelectionIndex();
if ((e.getModifiers() & InputEvent.BUTTON1_MASK)!=0) {
int row = jTable1.getSelectedRow();
ListSelectionModel rowSM = jTable1.getSelectionModel();
rowSM.addListSelectionListener (new ListSelectionListener() {
public void valueChanged (ListSelectionEvent e) {
if (e.getValueIsAdjusting ()) return;
ListSelectionModel lsm = (ListSelectionModel ) e.getSource();
if(lsm.isSelectionEmpty()){
System.out.println("No rows are selected.");
else{
int selectedRow = lsm.getMinSelectionIndex();
System.out.println("Row "+selectedRow+" is now selected.");
Thank you once again :0)Why do you want to know when a row is selected?
If you are just trying to edit data you are going about this the hard way. Just use the table model.
If you want to have some other action occur when a row is selected try something like this.
table.addMouseListener (new MouseAdapter()
public void mouseClicked (MouseEvent e)
Point origin = e.getPoint();
if ( e.getClickCount() == 2)
{ // double clicked
int row = table.rowAtPoint(origin);
if (row == -1)
return;
else
// Do something
else
// single click
int row = tabl.rowAtPoint (origin);
if (row > -1)
// Do something else -
JTable-Selecting a row when i press an alphabet in a single column table
hi,
I have come across a issue where if i press a alphabet the row containig the leading alphabet should be selected.
for eg: if i press "s" the first occurence of row containing string starting with "s" ie "stateful" sholud be selected.My table has 1 column only..
please look in to it nad provide a solution.
Looking fwd
cheers,
sharathUse a JList. It supports this functionality.
Otherwise you would need to add a KeyListener to the table. Loop through the model using getValueAt(...) and compare the first character and then highlight the line. -
IWork Numbers -- how to determine the current selected column/row?
I am trying to write a script that grabs some text from a Numbers spreadsheet based on the selected field. I just can't figure how to actually get the column and row in a way I can use. Here's my start:
tell application "Numbers"
tell document 1
-- DETERMINE THE CURRENT SHEET
set currentsheetindex to 0
repeat with i from 1 to the count of sheets
tell sheet i
set x to the count of (tables whose selection range is not missing value)
end tell
if x is not 0 then
set the currentsheetindex to i
exit repeat
end if
end repeat
if the currentsheetindex is 0 then error "No sheet has a selected table."
-- GET THE VALUES OF THE SELECTED CELLS
tell sheet currentsheetindex
set the current_table to the first table whose selection range is not missing value
tell the current_table
set the range_values to the value of every cell of the selection range
set therange to every cell of the selection range
set thecol to column of first item of therange
set therow to row of first item of therange
end tell
end tell
end tell
end tell
It gives me a result like
row "30" of table "table" of sheet "sheet 1" of document "Scheduler.numbers" of application "Numbers"
but what I need is just "30" so I can use it for my scripts. I can't figure how to convert this to a string or some other useful format.
Can anyone help? I like Numbers but I always run into little problems like this, something I can't figure how to do, compared with other scriptable programs.Search forGetSelParams or better for get_SelParams in the existing threads.
I posted this handler more than 30 times !
Yvan KOENIG (VALLAURIS, France) vendredi 18 mars 2011 17:03:05 -
Hi
How is it possible to select the entire row of a JTable without the cell that`s selected, gaining a border.
Any help would be appreciated.
Thanks
KellyCould you explain what you need? You don't want the border of the selected row to be displayed?
-
JTable: Selecting rows in columns independently
Dear all,
I have a JTable with two columns. I want the user to be able to select cells in columns independently. At present, the entire row gets marked as selected. Is it possible at all to, for instance, select row1 1 to 3 in column 1 and rows 4 to 5 in column 2? If so, where's the switch? Thanks a lot in advance!
Cheers,
MartinAre you trying to use a seperate table for each column.
Thats not a good idear.
Here is what you have to do.
1. Create a sub class of JTable
2. You will have to redefine how the selection is done so. You will need some sort of a collection to store the list of selected cells indexes
2.1 Selecting a cell is simply adding the coordinations of the cell to the selection
2.2 de selecting is just removing it from the collection.
2.3 Here is what you have to override
setColumnSelectionInterval()
setColumnSelectionInterval()
changeSelection()
selectAll()
getSelectedColumns()
getSelectedColumn()
getSelectedRows()
getSelectedRow() You migh also need few new methods such as
setCellSelected(int row, int column, boolean selected);
boolean isCellSelected(int row, int column);
clearSelection();
int[][] getSelectedCells();You will have to implement the above in terms of your new data structure.
3. Handle mouse events.
Ex:- when user cicks on a cell if it is already selected it should be deselected (see 2.2)
other wise current selected should be cleared and the clicked cell should be selected
if your has pressed CTRL key while clicking the the cell should be selected without deselecting the old selection.
---you can use above using a MouseListener
When the user hold down a button and move the mouse accross multiple cell those need to be selected.
--- You will need a MouseMotionListener for this
You might also need to allow selection using key bord. You can do that using a KeyListener
4. Displaying the selection
You have to make sure only the selected cells are high lighted on the table.
You can do this using a simple trick.
(Just override getCellEditor(int row, int column) and getCellRenderer(int row, int column) )
Here is what you should do in getCellRenderer(int row, int column)
public TableCellRenderer getCellRenderer(int row, int column)
TableCellRenderer realRenderer = super.getCellRenderer(int row, int);
return new WrapperRenderer(realRenderer,selectedCellsCollection.isCellSelected(row,column));
static class WrapperRenderer implements TableCellRenderer{
TableCellRenderer realRenderer;
boolean selected;
public WrapperRenderer(TableCellRenderer realRenderer, boolean selected){
this.realRenderer = realRenderer;
this.selected = selected;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column){
return realRenderer.getTableCellRendererComponent(table,value,selected,hasFocus,row,column);
}What the above code does is it simply created wrapper for the Renderer and when generating the rendering component it replaces the isSeleted flag with our on selected flag
and the original renderer taken from the super class will do the rest.
You will have to do the same with the TableCellEditor.
By the way dont use above code as it is becouse the getCellRenderer method create a new instance of WrapperRenderer every time.
If the table has 10000 cells above will create 10000 instances. So you should refine above code.
5. Finnaly.
Every time the selection is changes you should make the table rerender the respective cells in or der to make the changes visible.
I'll leave that part for you to figure out.
A Final word
When implementing th above make sure that you do it in the java way of doing it.
For the collection of selected cells write following classes
TableCellSelectionModel // and interface which define what it does
DefaultTableCellSelectionModel //Your own implementation of above interface the table you create should use thisby default
//To communicate the selection changes
TableCellSelectionModelListener
TableCellSelectionModelEventif you read the javadoc about similer classes in ListSelectionModel you will get an idear
But dont make it as complex as ListSelectionModel try to keep the number of methods less than 5.
If you want to make it completly genaric you will have to resolve some issues such as handling changes to the table model.
Ex:- Rows and colums can be added and removed in the TableModle at the run time as a result the row and column indexes of some cells might change
and the TableCellSelectionModel should be updated with those changes.
Even though the todo list is quite long if you plan your implementation properly the code will not be that long.
And more importantly you will learn lots more by trying to implementing this.
Happy Coding :) -
Hello,
I have a JTable component with 4 columns. I only allow single row selection. If I select a row not all columns are selected. The one you clicked on does not have the selection color. Ho can you select all columns with the selection color ?
regards
JohanJust guessing because I had a hard time wading though all your code. you probably have a custom renderer on that column. Your renderer needs to change the background color if the cell is selected.
-
Hello,
I have a problem selecting a row in a JTable.
I use
mytable.getSelectionModel().setSelectionInterval(row, row);
to select a row, but after that this row is only highlighted. After calling this method I cannot change the selection using the arrow keys.
Can anybody give me a hint, how I can get the row selected, so that I can use the arrow keys immediately after selecting the row?
Any help is welcome.
Thanks,
FritzHello,
I got the solution:
final int pRow = row;
final int pCol = column;
final JTable myTable = mytable;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myTable.requestFocusInWindow();
myTable.changeSelection(pRow, pCol, true, true); -
JTable - Column swap disabling for selected columns
Hi,
In my JTable i want to disable the swapping of selected columns, table.getTableHeader().setReorderingAllowed(false); this disables the whole table swapping.
Is there anyway to disable only selected column swapping?
Thanks in advance.
Yours,
ArunI was able to disable the column swapping in all the ways, i.e. i've solved the problem that i've said in my previous post.
The following are the scenario'scovered, if the user wants to disable swapping of 1st and 2nd column of a JTable
1. Donot allow dragging of the 1st and 2nd column and
2. If the user drag-drop 3 or 4 th column in place of 1st or 2nd column, then undo the swap operation by re-swapping the columns.
Try the following example
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.MouseInputListener;
import javax.swing.plaf.basic.BasicTableHeaderUI;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
public class FixedTableColumnsExample
FixedTableColumnsExample()
String[] columnNames = {"First","Last Name","Sport","# of Years","Vegetarian"};
Object[][] data = {
{"Mary", "Campione","Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml","Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath","Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour","Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne","Pool", new Integer(10), new Boolean(false)}
JTable table = new JTable(data, columnNames);
TableColumnModel columnModel = table.getColumnModel();
EditableHeader test = new EditableHeader(columnModel);
table.setTableHeader(test);
JFrame frame = new JFrame("Table Fixed Column Demo");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JScrollPane scrollPane = new JScrollPane(table);
frame.getContentPane().add( scrollPane );
frame.setSize(400, 300);
frame.setVisible(true);
public static void main(String[] args)
new FixedTableColumnsExample();
class EditableHeader extends JTableHeader
public EditableHeader(TableColumnModel columnModel)
super(columnModel);
public void updateUI()
setUI(new EditableHeaderUI());
class EditableHeaderUI extends BasicTableHeaderUI
boolean is1and2Swapped = true;
protected MouseInputListener createMouseInputListener()
return new MouseInputHandler((EditableHeader) header);
class MouseInputHandler extends BasicTableHeaderUI.MouseInputHandler
protected EditableHeader header;
public MouseInputHandler(EditableHeader header)
this.header = header;
public void mouseDragged(MouseEvent e)
int draggedColumnIndex = ((EditableHeader)e.getSource()).getDraggedColumn().getModelIndex();
if(draggedColumnIndex != 0 && draggedColumnIndex != 1 )
super.mouseDragged(e);
is1and2Swapped = true;
else
is1and2Swapped = false;
public void mouseReleased(MouseEvent e)
int draggedColumnIndex = ((EditableHeader)e.getSource()).getDraggedColumn().getModelIndex();
Point p = e.getPoint();
TableColumnModel columnModel = header.getColumnModel();
if(p.x < 0)
p.x = 0;
int index = columnModel.getColumnIndexAtX(p.x);
super.mouseReleased(e);
if((index == 0 || index == 1) && is1and2Swapped)
header.getColumnModel().moveColumn(index,draggedColumnIndex);
}Is there anyother better way to do the swap disabling? If so please suggest me.
This solution is having one disadvantage.
Consider the following scenario,
a) 1 and 2 are fixed columns.
b) Move column 4 to 3rd position
c) Move new 3rd column to 1st or 2nd column's position
d) the new 3rd column is moving to position 4(its original position when the model was created) instead of position 3.
This is because the TableColumModel is not updated properly. I'm working on that. Any Suggestions?
Thanks
Arun. -
JTable - Selecting selected columns
Is there a way to select a "selected" number of columns (i.e. not all columns of a row) in JTables?
The default selection criteria is by rows, I want to be able to select by both rows and columns, something like the excel spreadsheets.
Thanks.Look at some of these
http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
There is one which adds a 'row header'. From there you should be able to select a row with it. -
Select multiple rows on a JTable
Hi!
Given: JTable, multiple selection allowed
Wanted: a way to be able to set multiple non-continuous rows selected
eg. on a JTable with 5 rows,
I want to set rows 1, 3 and 5 selected
Anyone?
Stoffel.table.setSelectionMode(ListSelectionModel.MULTIPLE_INTE
VAL_SELECTION);
select rows using <ctrl> and/or <shift>Or if you want to set programaticly use this methods, see the api
for explanation.
table.changeSelecton(int row, int column, boolean toogle, boolean extend);
table.addRowSelection(int index0, int index1);
table.addColumnSelectionInterval(int index0, int index1)
... -
Interactive Report - Include Non-selected Column in Row Text Search
Hi,
We have an interactive report that contains many columns. NAME VARCHAR2(30), TYPE VARCHAR2(30) etc and DESCRIPTION VARCHAR2(4000).
Normally the DECRIPTION column would not be shown (avalilable for dispaly via 'Select Columns' but not selected), however we need the default Row Text Search (ie direct entry into the search field instead of creating a column filter) to search the DESCRIPTION field wether it is selected for display or not.
This will allow the user to enter a term that may be contained in the DESCRIPTION to find records without trying to display a 4000 character field in the report - which just looks horrible.
We are using ApEx 4.1.1.
Thanks,
Martin FiggHi Ray,
As I expected this has got us very close. We went with the code:
select
facility_id,
facility_name,
'<span title="' || facility_desc|| '">'||substr(facility_desc,0,50)||decode(sign(length( facility_desc)-50),1,' (More...)',NULL)||'</span>' facility_desc,
equipment_id,
equipment_name,
'<span title="' || equipment_desc|| '">'||substr(equipment_desc,0,50)||decode(sign(length( equipment_desc)-50),1,' (More...)',NULL)||'</span>' equipment_desc,
from
rf_full_item_list_vwhich works well. The only issue is that when you download to csv you get the html tags etc as well. Put I am a lot closer to a solution than we were.
Thanks again.
Martin -
How to select a row in Jtable at runtime
how to select a row in Jtable at runtime.
use
setRowSelectionInterval(int fromRowIndex, int toRowIndex);example if your table has 10 rows then u want to select the rows from 4 to 8 then use
setRowSelectionInterval(3, 7);if you want to select just one row for example 5 then use
setRowSelectionInterval(5, 5); -
How do I locate column/row (number) selected in applescript
I require a simple script to adjust the column widths of the current selected column only. I want to base it on a script below which I found on the internet. This script adjusts multiple column widths to the value input and adjusts the stub column to the remaining space. I would like to know how easy it is to create a script with a similar input window that adjusts the column/row selected leaving the others in tact.
tell application "Adobe InDesign CS4"
activate
if class of parent of selection is not cell then
display dialog " Do not highlight any cells " buttons " OK " default button 1 with icon caution
else
set monTableau to parent of parent of selection
set NbColonnes to count columns of monTableau
set monBlocTexte to parent text frames of selection
set maBoiteTexte to item 1 of monBlocTexte
set {y, x, h, l} to geometric bounds of maBoiteTexte
set largeurBloc to (l - x)
tell text frame preferences of maBoiteTexte
set NumColTexte to text column count
set largGout to text column gutter
end tell
display dialog "Width of columns (mm) " default answer 20
set largeurTexte to text returned of the result
set largcol2 to (largeurTexte as integer)
set largcol1 to ((largeurBloc - (NumColTexte - 1) * largGout) / NumColTexte - (NbColonnes - 1) * largcol2)
if largcol1 < 2 then
set largcol1 to ((largeurBloc - (NumColTexte - 1) * largGout) / NumColTexte) / NbColonnes
set largcol2 to ((largeurBloc - (NumColTexte - 1) * largGout) / NumColTexte) / NbColonnes
end if
set width of column (1) of monTableau to largcol1
repeat with counter from 2 to NbColonnes
set width of column (counter) of monTableau to largcol2
end repeat
end if
end tell
Your help will be greatly appreciated
Thanks
Dave WilliamsPerhaps like this:
tell application "Microsoft Excel"
set i to first row index of active cell
end
log i
Regards,
H -
JTable select row by double click, single click
Hi all,
I would like to double click on the row of the JTable and pop up a window for adding stuff, a single click for selecting the row and then in the menu bar I can choose to etither add, change or delete stuff. I try to use the ListSelectionModel but does not seems to distinguish between double or single click.
Any idea, doc, samples?
or I should not use ListselectionModel at all?
thanks
andrewHi. I used an inner class. By using MouseAdapter u dont have to implement all methods in the interface..
MouseListener mouseListener = new MouseAdapter()
public void mouseClicked(MouseEvent e)
if(SwingUtilities.isLeftMouseButton(e))// if left mouse button
if (e.getClickCount() == 2) // if doubleclick
//do something
U also need to add mouselistener to the table:
table.addMouseListener(mouseListener);
As I said, this is how I did it.. There are probably alot of ways to solve this, as usual :). Hope it helps
Maybe you are looking for
-
What is the maximum file size recommended by Apple for Pages documents. Yes this question was asked in 2009. However it was not answered. It is not feasible to break a document into different files when the purpose is to submit a book for publicatio
-
Find the owner of a socket? or Where is sockstat(1)
In other BSD unixes, sockstat(1) is the convenient way to find the PID of the owner of a socket. In OS X the man page for netstat(1) mentions it in the SEE ALSO section, but it doesn't appear to be a part of OS X. If so, is there another convenient w
-
Insert a scrollable window in Captivate frame?
Hi! I have a long image that I would like to insert in the captivate slide, i cant make it smaller or the project bigger. I would like to know if I can insert a window in the slide that has a horizontal scroll bar the user can use to scroll the
-
Hi, I want to use public API to add items to content areas. However this API ( wwsbr_api) seems only work when user is Portal30. When i try to run this API with other user it fails. i've run the script sbrapi.sql to add some grant to the user. This i
-
Color "shifted" in CS4 RAW files
Hello everyone. Ill try to explain my problem. Until last year I used ACR (combined with Bridge CS3) to color manage my images. Then I would convert them to DNG using the Adobe DNG Converter, and bring them into iMatch (www.photools.com), which is th