Select whole row in a JTable
I would like to know how I can fix so that when a user clicks a cell in my JTable the whole row gets selected. Not with the clicked cell as white and the rest of the row in blue, but with the whole row in blue. I would also like to stop the cell from beeing edited. The third thing I wonder is how I can hide the grid between the cells, and make it look like a list??
Thanks for replies!
Thanks for the help!
I managed to get the frame around the selected cell also. Did it by extending the DefaultTableCellRenderer. Found some more help here:
http://forum.java.sun.com/thread.jsp?thread=447758&forum=57&message=2028189
Similar Messages
-
Multiple selection of row in a jtable
Hello All,
I am working with this jtable 'tblSearch'. The application requirement is that the user should have the ability to select multiple rows using the control key. I am using the bold part of the code to color the selected row light gray. Can you someone help me to select multiple rows by holding the control key down.
public void PopulateAS400(){
cmbView.hidePopup();
setCursor(hourglassCursor);
int scrPos = scpSearch.getHorizontalScrollBar().getValue();
oapprovalSQL = SQLFactory.createOrderApprovalSql();
Vector FreightList = oapprovalSQL.getData(getAs400SearchString(), getOrderby(), AS400, AS400Overide.length, searchItems, rdoMatchAny.isSelected());
columnNames = (Vector)FreightList.get(1);
data = (Vector)FreightList.get(0);
model = new DefaultTableModel(data,columnNames) {
public Object getValueAt(int row, int col) {
return super.getValueAt(row,col);
public boolean isCellEditable(int row, int col) {
if (row == 0){
getTblSearch().setColumnSelectionAllowed(true);
return true;
getTblSearch().setColumnSelectionAllowed(false);
return false;
public Class getColumnClass(int c) {
if(c == 5 || c == 9){
return BigDecimal.class;
}else{
return String.class;
JTable tmp = new JTable(model)
private final KeyStroke tabKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
private final KeyStroke shiftTabKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB,KeyEvent.SHIFT_DOWN_MASK);
public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend)
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if(currentEvent instanceof KeyEvent)
KeyEvent ke = (KeyEvent)currentEvent;
if(ke.getSource()!=this)
return;
if (KeyStroke.getKeyStrokeForEvent(ke).equals(tabKeyStroke))
if (rowIndex > 0)
rowIndex = 0;
columnIndex = 0;
toggle = false;
extend = false;
getTblSearch().setColumnSelectionAllowed(true);
else if (KeyStroke.getKeyStrokeForEvent(ke).equals(shiftTabKeyStroke))
if (rowIndex > 0)
rowIndex = 0;
columnIndex = getTblSearch().getColumnCount()-1;
toggle = false;
extend = false;
getTblSearch().setColumnSelectionAllowed(true);
else if (columnIndex == getTblSearch().getColumnCount()-1)
rowIndex = 0;
columnIndex = getTblSearch().getColumnCount()-1;
toggle = false;
extend = false;
getTblSearch().setColumnSelectionAllowed(true);
super.changeSelection(rowIndex, columnIndex, toggle, extend);
public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColumnIndex)
Component c = super.prepareRenderer(renderer, rowIndex, vColumnIndex);
if ((vColumnIndex == 7) && (rowIndex > 0))
if ((model.getValueAt(rowIndex,7) != null) && (model.getValueAt(rowIndex,7).toString().equalsIgnoreCase("NMI")))
c.setBackground(Color.red);
else if ((model.getValueAt(rowIndex,7) != null) && (model.getValueAt(rowIndex,7).toString().equalsIgnoreCase("NMI ANSWERED")))
c.setBackground(Color.green);
else
c.setBackground(Color.white);
else
c.setBackground(Color.white);
**if (isRowSelected(rowIndex) && (rowIndex > 0)){**
**((JComponent)c).setBackground(Color.LIGHT_GRAY);**
if (rowIndex == 0 && isCellSelected(rowIndex, vColumnIndex)) {
c.setBackground(lightBlue);
return c;
setTblSearch(tmp);
getTblSearch().setAutoscrolls(true);
getTblSearch().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTblSearch().setAutoCreateColumnsFromModel(false);
getTblSearch().setColumnSelectionAllowed(false);
getTblSearch().setRowSelectionAllowed(true);
getTblSearch().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JTableHeader header8 = getTblSearch().getTableHeader();
ColumnHeaderListener colH8 = new ColumnHeaderListener();
colH8.setCallFrom("OrderApproval");
colH8.setOapproval(this);
header8.addMouseListener(colH8);
header8.setReorderingAllowed(false);
header8.setResizingAllowed(false);
getTblSearch().getColumn("Co #").setCellEditor(asCompCell);
getTblSearch().getColumn("Reg").setCellEditor(asRegCell);
getTblSearch().getColumn("Rep #").setCellEditor(asRepCell);
packColumns(getTblSearch(), 1);
getTblSearch().getColumnModel().getColumn(6).setPreferredWidth(240);
for(int i=0; i<searchEntries8.length; i++) {
getTblSearch().setValueAt(searchEntries8,0,i);
((GenericTextEditor)getTblSearch().getCellEditor(0,i)).setCellEditorValue(searchEntries8[i]);
scpSearch.add(new PopupContainer());
popupMenu = new JPopupMenu();
JMenuItem printFinalOrderMenu = new JMenuItem(PRINTFINALORDER_CMD);
printFinalOrderMenu.addActionListener(new PrintFinalOrderMenuListener());
popupMenu.add(printFinalOrderMenu);
MouseListener popupListener = new PopupListener();
getTblSearch().addMouseListener(popupListener);
scpSearch.setViewportView(getTblSearch());
scpSearch.getHorizontalScrollBar().setValue(scrPos);
setCursor(normalCursor);
Thank you all for your time n help.
Edited by: anjan_dev on Jan 29, 2008 2:14 PM
Edited by: anjan_dev on Jan 29, 2008 2:15 PM
Edited by: anjan_dev on Jan 29, 2008 2:16 PMThe issue is when I have one row already selected and then when I click on another row while holding the control key down. Our application needs an user to be able to select multiple rows at the same time.That is the default behaviour. I have no idea why it doesn't work for you.
Get rid of all your custom KeyEvent logic and try it again.
If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
http://homepage1.nifty.com/algafield/sscce.html
Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
http://forum.java.sun.com/help.jspa?sec=formatting -
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)
... -
How to Select a Row in a JTable, on a right mouse click?
Hi all!
I need to know the Row index in a JTable, on a right mouse click?
Executing following code, I get the "Column Number" on a mouse click
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int columnIdx = tableView.convertColumnIndexToModel(viewColumn);
Dows any body know the code that gets "rowIdx" on a mouse e.getY() method??
Hope early response!int row = table.rowAtPoint( e.getPoint() );
int column = table.columnAtPoint( e.getPoint() ); -
How can select Multiple Rows in a Jtable
Dear Forum
i am working on jclient\swing.
I want to select More than one row at a time from a table
I am trying the following code at INIT but it is not working.
jTable1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Please suggest me for the same.
ThankxGirdhar,
I tried with JDeveloper 9.0.3 and it worked.
Either you are using another JDeveloper version, or you need to specify what you mean with "is not working".
Frank -
How to select a row in a JTable
I want the following to happen: depending on the value of a variable, i have to change the background color and font of one row. Has anyone an idea how to do that?
Thxcheck out http://www.globalleafs.com 's download section. There are many programmes out there in java.
-
To get the unique id of the selected row in a JTable as in Database
Hi,
After fetching the recodrs from the Database, I have displayed them in a JTable. Though I fetched all the columns from db, I am displying only only 2 columns, say Name and Number neither of which is unique, however I have a unique ID for each record in the db. Now when I select some row in the JTable, I need to know its unique ID (the one which is in the db) which i have not displayed in the JTable.
Is there any API method that can store the unique ids of a table? Or how can this be done?
Thanks in Advance.Although, if you don't want the Id visible in the table, then you need to remove its TableColumn from the TableColumnModel.
Then when you want to reference the id you need to use:
table.getModel.getValueAt(...); -
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); -
Selecting multiple rows in JTable
Hi
I wonder if it is possible to select multiple rows in a JTable. I have written the following:
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);However, when I select a second row, my first selected row unselects. I have to shift-click manually to select both rows. Is there a way around this (ie. without the shift-click part)?Well I have done that without finding anything... can you provide a link?
-
Selecting rows from a JTable using keys
Hi all, be very grateful for some help on this.
I want to provide functionality in an application where the user will be able to select multiple rows from a JTable by using the page up/ page down button.
Anybody know how this can be done?
ThanksJust add a KeyListener to the table which does what you want on pressing the relevant key.
it seems a bit odd though. If I pressed page up/down in a table I'd expect it to scroll and would be somewhat confused if it started selecting stuff. Generally it's best not to muck around with the default behaviour of UI components. -
Editable columns in table don't select the whole row
I am new to the forums and posted this to the wrong one the first time and I am not sure how to move it so I am just reposting it here. Sorry.
I have a table with 7 columns. 2 of them are non-editable and the rest are either radio buttons or check boxes. When I click on the 2 non-editable columns, the whole row gets highlighted. When I click on any of the editable columns, the button is selected, but the whole row is not highlighted. If I made the editable columns non-editable then the whole row gets highlighted when the column is clicked on. I want the button selected and the row highlighted when the editable columns are clicked on. Here is some relevant code:
class PackageTable extends JPanel
public PackageTable(String pathfile)
fieldsok = true;
errorfield = new JTextField(250);
startfield = new JTextField(250);
stopfield = new JTextField(250);
tableModel = new MyTableModel();
table = new JTable(tableModel)
public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex)
Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
if (vColIndex == 0)
c.setBackground(new Color(238,238,238));
else
c.setBackground(new Color(255,255,255));
boolean selected = isRowSelected(rowIndex);
if (selected)
c.setBackground(Color.yellow);
return c;
table.setPreferredScrollableViewportSize(new Dimension(300, 1000));
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
TableColumn column = null;
for (int col = 0; col < 7; col++)
column = table.getColumnModel().getColumn(col);
if (col == 0)
column.setPreferredWidth(30);
else if (col == 1)
column.setPreferredWidth(300);
else if (col == 2)
column.setPreferredWidth(10);
column.setCellRenderer(new RadioButtonRenderer());
column.setCellEditor(new RadioButtonEditor(new JCheckBox()));
else if (col == 3)
column.setPreferredWidth(10);
column.setCellRenderer(new RadioButtonRenderer());
column.setCellRenderer(new RadioButtonRenderer());
column.setCellEditor(new RadioButtonEditor(new JCheckBox()));
else if (col == 4)
column.setPreferredWidth(10);
column.setCellRenderer(new RadioButtonRenderer());
column.setCellEditor(new RadioButtonEditor(new JCheckBox()));
else if ((col == 5) || (col == 6))
column.setPreferredWidth(10);
class RadioButtonRenderer implements TableCellRenderer
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
if (isSelected)
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
else
setForeground(table.getForeground());
setBackground(table.getBackground());
if (value == null)
return null;
return (Component) value;
class RadioButtonEditor extends DefaultCellEditor implements ItemListener
private JRadioButton button;
public RadioButtonEditor(JCheckBox checkBox)
super(checkBox);
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
if (value == null)
return null;
button = (JRadioButton) value;
button.addItemListener(this);
return (Component) value;
public void addCellEditorListener(CellEditorListener listener)
listenerList.add(CellEditorListener.class, listener);
public void removeCellEditorListener(CellEditorListener listener)
listenerList.remove(CellEditorListener.class, listener);
protected void fireEditingStopped()
CellEditorListener listener;
Object[] listeners = listenerList.getListenerList();
for (int i = 0; i < listeners.length; i++)
if (listeners[i] == CellEditorListener.class)
listener = (CellEditorListener)listeners[i+1];
listener.editingStopped(changeEvent);
protected void fireEditingCanceled()
CellEditorListener listener;
Object[] listeners = listenerList.getListenerList();
for (int i = 0; i < listeners.length; i++)
if (listeners[i] == CellEditorListener.class)
listener = (CellEditorListener)listeners[i+1];
listener.editingCanceled(changeEvent);
public void cancelCellEditing()
fireEditingCanceled();
public boolean stopCellEditing()
fireEditingStopped();
return true;
public Object getCellEditorValue()
return button;
public boolean isCellEditable(EventObject event)
return true;
public boolean shouldSelectCell(EventObject event)
return true;
public void itemStateChanged(ItemEvent e)
super.fireEditingStopped();
class MyTableModel extends AbstractTableModel
String[] columnNames = {"","Configuration Files","Sorts","Plots","Both","Print","Alerts"};
public MyTableModel() { }
public int getColumnCount()
return columnNames.length;
public int getRowCount()
return totaldata.size();
public String getColumnName(int col)
return columnNames[col];
public Object getValueAt(int row,int col)
return(((Vector)totaldata.get(row)).get(col));
public Class getColumnClass(int c)
return getValueAt(0, c).getClass();
public boolean isCellEditable(int row, int col)
if ((col == 0) || (col == 1))
return false;
else
return true;
public void setValueAt(Object value, int row, int col)
Vector v1 = new Vector();
v1 = (Vector)totaldata.get(row);
v1.set(col,value);
if (col == 1)
if (((String)value).indexOf("/") == -1)
JOptionPane.showMessageDialog(pdsframe, "The CONFIG file that was entered on line " + (row+1) + " is not valid.");
v1.set(col,(Object)"");
return;
fireTableCellUpdated(row, col);
fireTableChanged(new TableModelEvent(this));
public void addNewRow(Vector newRow)
totaldata.add(newRow);
fireTableRowsInserted(totaldata.size()-1, totaldata.size()-1);
public void deleteRow(int Row)
totaldata.remove(Row);
fireTableRowsDeleted(totaldata.size()-1, totaldata.size()-1);
}I have searched forever to try to find how to do this and I can't seem to get it right. If all the radiobuttons in one column are selected and I click on one of those rows in one of those columns, then the whole row is highlighted.
Can anyone help me out?
Thanks.
esk3 {Sorry. I didn't know that I had to provide something that could be executed. I am going to try to put enough in so that it can. This is part of a larger program and this frame is called from another frame. Here it is. I hope it works.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dimension.*;
import java.util.*;
import java.text.*;
// Java extension packages
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.JTable.*;
import javax.swing.JScrollPane.*;
private JFrame pdsframe;
private String printchecked;
private String alertschecked;
private JTextField cb;
private JTextField pf;
private JScrollPane scrollpane;
private JTable table;
private MyTableModel tableModel;
private Vector totaldata;
private JLabel startlabel;
private JLabel stoplabel;
private JTextField startfield;
private JTextField stopfield;
private JTextField errorfield;
private boolean fieldsok;
class MyTableModel extends DefaultTableModel
String[] columnNames = {"","Configuration Files","Sorts","Plots","Both","Print","Alerts"};
public MyTableModel() { }
public int getColumnCount()
return columnNames.length;
public int getRowCount()
return totaldata.size();
public String getColumnName(int col)
return columnNames[col];
public Object getValueAt(int row,int col)
return(((Vector)totaldata.get(row)).get(col));
public Class getColumnClass(int c)
return getValueAt(0, c).getClass();
public boolean isCellEditable(int row, int col)
if ((col == 0) || (col == 1))
return false;
else
return true;
public void setValueAt(Object value, int row, int col)
Vector v1 = new Vector();
v1 = (Vector)totaldata.get(row);
v1.set(col,value);
if (col == 1)
if (((String)value).indexOf("/") == -1)
JOptionPane.showMessageDialog(pdsframe, "The CONFIG file that was entered on line " + (row+1) + " is not valid.");
v1.set(col,(Object)"");
return;
fireTableCellUpdated(row, col);
fireTableChanged(new TableModelEvent(this));
public void addNewRow(Vector newRow)
totaldata.add(newRow);
fireTableRowsInserted(totaldata.size()-1, totaldata.size()-1);
public void deleteRow(int Row)
totaldata.remove(Row);
fireTableRowsDeleted(totaldata.size()-1, totaldata.size()-1);
class RadioButtonRenderer implements TableCellRenderer
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
if (isSelected)
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
else
setForeground(table.getForeground());
setBackground(table.getBackground());
if (value == null)
return null;
return (Component) value;
class RadioButtonEditor extends DefaultCellEditor implements ItemListener
private JRadioButton button;
public RadioButtonEditor(JCheckBox checkBox)
super(checkBox);
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
if (value == null)
return null;
button = (JRadioButton) value;
button.addItemListener(this);
return (Component) value;
public void addCellEditorListener(CellEditorListener listener)
listenerList.add(CellEditorListener.class, listener);
public void removeCellEditorListener(CellEditorListener listener)
listenerList.remove(CellEditorListener.class, listener);
protected void fireEditingStopped()
CellEditorListener listener;
Object[] listeners = listenerList.getListenerList();
for (int i = 0; i < listeners.length; i++)
if (listeners[i] == CellEditorListener.class)
listener = (CellEditorListener)listeners[i+1];
listener.editingStopped(changeEvent);
protected void fireEditingCanceled()
CellEditorListener listener;
Object[] listeners = listenerList.getListenerList();
for (int i = 0; i < listeners.length; i++)
if (listeners[i] == CellEditorListener.class)
listener = (CellEditorListener)listeners[i+1];
listener.editingCanceled(changeEvent);
} fireEditingStopped();
return true;
public Object getCellEditorValue()
return button;
public boolean isCellEditable(EventObject event)
return true;
public boolean shouldSelectCell(EventObject event)
return true;
public void itemStateChanged(ItemEvent e)
super.fireEditingStopped();
class PackageTable extends JPanel
public PackageTable(String pathfile)
fieldsok = true;
errorfield = new JTextField(250);
startfield = new JTextField(250);
stopfield = new JTextField(250);
tableModel = new MyTableModel();
table = new JTable(tableModel)
public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex)
Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
if (vColIndex == 0)
c.setBackground(new Color(238,238,238));
else
c.setBackground(new Color(255,255,255));
boolean selected = isRowSelected(rowIndex);
if (selected)
c.setBackground(Color.yellow);
return c;
table.setPreferredScrollableViewportSize(new Dimension(300, 1000));
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
TableColumn column = null;
for (int col = 0; col < 7; col++)
column = table.getColumnModel().getColumn(col);
if (col == 0)
column.setPreferredWidth(30);
else if (col == 1)
column.setPreferredWidth(300);
else if (col == 2)
column.setPreferredWidth(10);
column.setCellRenderer(new RadioButtonRenderer());
column.setCellEditor(new RadioButtonEditor(new JCheckBox()));
else if (col == 3)
column.setPreferredWidth(10);
column.setCellRenderer(new RadioButtonRenderer());
column.setCellEditor(new RadioButtonEditor(new JCheckBox()));
else if (col == 4)
column.setPreferredWidth(10);
column.setCellRenderer(new RadioButtonRenderer());
column.setCellEditor(new RadioButtonEditor(new JCheckBox()));
else if ((col == 5) || (col == 6))
column.setPreferredWidth(10);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(20,180,1000,300);
JLabel pflabel = new JLabel("Package File: ");
pf = new JTextField(pathfile);
cb = new JTextField(250);
startlabel = new JLabel("START_TIME = ");
stoplabel = new JLabel("STOP_TIME = ");
JLabel typelabel = new JLabel("TYPE OF FORMAT TO OUTPUT");
JButton savebutton = new JButton("Save and Run");
JButton jbtAddRow = new JButton("Add New Row");
JButton jbtUpdateRow = new JButton("Update Row");
JButton jbtDeleteRow = new JButton("Delete Row");
JButton cancelbutton = new JButton("Cancel");
cb.setEditable(false);
cb.setBounds(130,230,100,30);
cb.setEnabled(false);
cb.setVisible(false);
pflabel.setBounds(20,20,100,30);
pf.setEditable(false);
pf.setBounds(130,20,300,30);
startlabel.setBounds(20,90,100,30);
startfield.setEditable(false);
startfield.setBackground(new Color(255,255,255));
startfield.setBounds(130,90,300,30);
stoplabel.setBounds(20,120,100,30);
stopfield.setEditable(false);
stopfield.setBackground(new Color(255,255,255));
stopfield.setBounds(130,120,300,30);
typelabel.setBounds(525,150,400,30);
savebutton.setBounds(130,500,130,30);
jbtAddRow.setBounds(280,500,130,30);
jbtUpdateRow.setBounds(430,500,130,30);
jbtDeleteRow.setBounds(580,500,130,30);
cancelbutton.setBounds(730,500,130,30);
add(scrollPane);
add(pflabel);
add(pf);
add(startlabel);
add(stoplabel);
add(startfield);
add(stopfield);
add(typelabel);
add(jbtAddRow);
add(jbtUpdateRow);
add(jbtDeleteRow);
add(savebutton);
add(cancelbutton);
public void createAndShowGUI() {
//Create and set up the window.
pdsframe = new JFrame("PDS Batch Parameters");
pdsframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
totaldata = new Vector();
//Create and set up the content pane.
PackageTable newContentPane = new PackageTable(pathfile);
newContentPane.setOpaque(true); //content panes must be opaque
pdsframe.setContentPane(newContentPane);
//Display the window.
pdsframe.setLayout(null);
pdsframe.setSize(1100,700);
pdsframe.setLocationRelativeTo(null);
pdsframe.setFocusableWindowState(true);
pdsframe.setVisible(true);
pdsframe.show();
pdsframe.setAlwaysOnTop(true);
pdsframe.requestFocus();
public void main()
Toolkit.getDefaultToolkit().beep();
createAndShowGUI();
}Does this help? I hope it works. These are the relevant parts. Thanks.
esk3 -
How to delete the selected rows in a JTable on pressing a button?
How to delete the selected rows in a JTable on pressing a button?
You are right. I did the same.
Following is the code where some of them might find it useful in future.
jTable1.selectAll();
int[] array = jTable1.getSelectedRows();
for(int i=array.length-1;i>=0;i--)
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.removeRow(i);
} -
To change the font of a selected row in a Jtable
Hello,
Is it possible to change the font of a selected row in a jtable?
i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font?
thank you.String will be left justified
Integer will be right justified
Date will be a simple date without the time.
As it will with this renderer.Only if your custom renderer duplicates the code
found in each of the above renderers. This is a waste
of time to duplicate code. The idea is to reuse code
not duplicate and debug again.
No, no, no there will be NO duplicated code.
A single renderer class can handle all types ofdata.
Sure you can fit a square peg into a round hole if
you work hard enough. Why does the JDK come with
separate renderers for Date, Integer, Double, Icon,
Boolean? So that, by default the rendering for common classes is done correctly.
Because its a better design then having code
with a bunch of "instanceof" checks and nested
if...else code.This is only required for customization BEYOND what the default renderers provide
>
And you would only have to use instanceof checkswhen you required custom
rendering for a particular classAgreed, but as soon as you do require custom
renderering you need to customize your renderer.
which you would also have to do with theprepareRenderer calls too
Not true. The code is the same whether you treat
every cell as a String or whether you use a custom
renderer for every cell. Here is the code to make the
text of the selected line(s) bold:
public Component prepareRenderer(TableCellRenderer
renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row,
, column);
if (isRowSelected(row))
c.setFont( c.getFont().deriveFont(Font.BOLD) );
return c;
}It will work for any renderer used by the table since
the prepareRenderer(...) method returns a Component.
There is no need to do any kind of "instanceof"
checking. It doesn't matter whether the cell is
renderered with the "Object" renderer or the
"Integer" renderer.
If the user wants to treat all columns as Strings or
treat individual columns as String, Integer, Data...,
then they only need to override the getColumnClass()
method. There is no change to the prepareRenderer()
code.
Have you actually tried the code to see how simple it
is?
I've posted my code. Why don't you post your solution
that will allow the user to bold the text of a Date,
Integer, and String data in separate column and then
let the poster decide.Well, I don't see a compilable, runnable demo anywhere in this thread. So here's one
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Vector;
public class TableRendererDemo extends JFrame{
String[] headers = {"String","Integer","Float","Boolean","Date"};
private JTable table;
public TableRendererDemo() {
buildGUI();
private void buildGUI() {
JPanel mainPanel = (JPanel) getContentPane();
mainPanel.setLayout(new BorderLayout());
Vector headerVector = new Vector(Arrays.asList(headers));
Vector data = createDataVector();
DefaultTableModel tableModel = new DefaultTableModel(data, headerVector){
public Class getColumnClass(int columnIndex) {
return getValueAt(0,columnIndex).getClass();
table = new JTable(tableModel);
// table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
table.setDefaultRenderer(String.class, new MyTableCellRenderer());
table.setDefaultRenderer(Integer.class, new MyTableCellRenderer());
table.setDefaultRenderer(Float.class, new MyTableCellRenderer());
table.setDefaultRenderer(Date.class, new MyTableCellRenderer());
JScrollPane jsp = new JScrollPane(table);
mainPanel.add(jsp, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
private Vector createDataVector(){
Vector dataVector = new Vector();
for ( int i = 0 ; i < 10; i++){
Vector rowVector = new Vector();
rowVector.add(new String("String "+i));
rowVector.add(new Integer(i));
rowVector.add(new Float(1.23));
rowVector.add( (i % 2 == 0 ? Boolean.TRUE : Boolean.FALSE));
rowVector.add(new Date());
dataVector.add(rowVector);
return dataVector;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
TableRendererDemo tableRendererDemo = new TableRendererDemo();
tableRendererDemo.setVisible(true);
SwingUtilities.invokeLater(runnable);
class MyTableCellRenderer 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 ( isSelected){
setFont(getFont().deriveFont(Font.BOLD));
else{
setFont(getFont().deriveFont(Font.PLAIN));
if ( value instanceof Date){
SimpleDateFormat formatter =(SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
setText(formatter.format((Date)value));
if(value instanceof Number){
setText(((Number)value).toString());
return this;
}Hardly a "bunch of instanceof or nested loops. I only used the Date instanceof to allow date format to be specified/ modified. If it was left out the Date column would be "18 Apr 2005" ( DateFormat.MEDIUM, which is default).
Cheers
DB -
The columns of a selected row in a JTable
Hello guys,
I am trying to loop through the columns of a selected row in a JTable. Any ideas how i can do that?
Thanks in advance for your replies.
Antana.there is getValueAt(int row, int column) method in JTable.
will this help you?
and please post swing related queries to swing forum.
--Azodious_ -
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);
Maybe you are looking for
-
Elements 12 Editor Crashes Before Opening
A few months ago I bought and downloaded Photoshop Elements 12 from Adobe's website due to my Elements 8 crashing before it opens. For about a month it worked fine, but when I clicked on the logo Elements 12 wouldn't open. I would right-click my imag
-
Can't sign signature fields in Adobe Reader XI
Using Adobe Acrobat X (not the Pro edition!) Dutch (NL) Language Edition I created a document with two signature fields. Afterwards I tried to save as "Reader Extended". (The only option I found under "Save As" that looked similar to this command in
-
Migrating SAP Scripts to Adobe Forms
Hi All, We are going for a new Rollout in US based on our European implementation in 2001 which was on 4.6b. Eventually this system was upgrated to ECC 6.0 recently however all the outputs are still using SAP Scripts. For the new Rollout
-
whats the use of sap queries
-
The biggest, most annoying glitch I live with daily in Photoshop CS4 is the fact that my workspace will not stay the way I want it. I have it set up as follows: navigator & Info at the top, color & swatches next, Character & Paragraph next, History