Clear selection on FocusLost of Jtable.
Hi
I have a jtable in which some columns are editable and some are non-editable. I want to clear the selections in jtbale when focus is lost from jtable.
But i cannot write the code table.clearSelection() in the focusLost() method of JTable since it will not be invoked when another component is clicked using mouse, when the table editing is started.
When another component is clicked when the table is in edit mode, the focusLost() of Jtable will not be invoked, but the focusLost() of that editor component will be triggered. So that table.clearSelection() will not work in this case.
Can anybody suggest a solution to this problem ? I have already added putClienProperty("terminateEditOnFocusLost", Boolean.TRUE) to stop cell editing when focus is lost. Is there any methods like table.putClientProperty("clearSelectionOnFocusLost", Boolean.TRUE); ?? Do i need to add focus listener to each editor components ? Please hep.
with thanks & regards
Anoop
You can listen for all focus change events using the following code:
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addPropertyChangeListener("focusOwner", new PropertyChangeListener()
public void propertyChange(PropertyChangeEvent e)
if (e.getNewValue() == null) return;
Component c = (Component)e.getNewValue();
System.out.println();
System.out.println(c.getClass());
System.out.println(c.getParent().getClass());
});When your table gains focus you can set a boolean variable to indicate this. When another component gains focus (whose parent isn't the table), then you clear the table selection and reset the boolean variable.
Similar Messages
-
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); -
Problem with select all cells in JTable
Hi guys! I get some problem about selecting all cells in JTable. I tried to used two methods:
1> table.selectAll()2> changeSelection(firstcell, lastcell,false,true)
firstcell:[0,0], lastcell[rowcount-1,colcount-1]
Result: only the first row selected when i use both methods.
Note: i set up the selection model as following:
this.dataSheet.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
this.dataSheet.setCellSelectionEnabled(true);
this.dataSheet.setRowSelectionAllowed(true);
this.dataSheet.setColumnSelectionAllowed(true);Thanks !What selection properity should be changed in order to enable selectAll() method work properly? Is there Any constraints? Here is the TableModel I am using. And i set up selection mode use the following code:
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setCellSelectionEnabled(true);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(true);
import java.util.Vector;
import javax.swing.table.*;
import javax.swing.JTable;
public class DataSheetModel extends AbstractTableModel{
private Vector data = new Vector();//Store data
private Vector columnNames = new Vector();//Store head
public DataSheetModel(){}
public DataSheetModel(Vector headVector, Vector dataVector){
if(headVector != null) this.columnNames = headVector;
if(dataVector != null) this.data = dataVector;
public int getColumnCount(){
return columnNames.size()+1;
public int getRowCount(){
return data.size()+1;
public String getColumnName(int col){
if(col==0) return "";
else return (String)columnNames.get(col-1);
public Object getValueAt(int row, int col){
if(col==0) {
if(row != data.size()) return String.valueOf(row);
else return "*";
else{
if(row != data.size()){
Vector rowVector = (Vector)data.elementAt(row);
return rowVector.elementAt(col-1);
}else return null;
public void setValueAt(Object value, int row, int col){
if(row != this.data.size()){
Vector rowVector = (Vector)data.elementAt(row);
rowVector.set(col-1,value);
this.data.set(row,rowVector);
this.fireTableDataChanged();
}else{
Vector rowVector = new Vector();
for(int i=0; i<this.getColumnCount()-1; i++) rowVector.add(null);
rowVector.set(col-1,value);
this.data.add(rowVector);
this.fireTableDataChanged();
public Class getColumnClass(int c){
return getValueAt(0,c).getClass();
public boolean isCellEditable(int row, int col){
if(col == 0) return false;
else return true;
public void setDataVector(Vector head, Vector data){
if(head != null) this.columnNames = head;
if(data != null) this.data = data;
} -
'Clear Paragraph Style' and 'Clear Selection Style'
In an old archived topic, someone wrote:
quote:
In DWMX, you could select text in the design view and in the
"HTML Styles" window (which no longer exists in MX 2004) all you
had to do was click "Clear Selection Style" and all HTML formatting
(paragraph tags, font faces, colours, bold, italics etc) would be
removed. This was marvellous for reformatting <font> tag
based text with CSS. MX 2004 claims to be a CSS machine, but it
seems to lack this very important feature which helps to re-inforce
the use of CSS over font tags.
http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?catid=189&threadid=714513&arc tab=arc
I absolutely agree, and none of the alternative methods
people suggested in that thread matched this lost feature for speed
and ease of use.
I've not seen a replacement for these commands in Dreamweaver
8 either (although I've often wished for one). Does anyone know of
a hidden feature that exists in version 8 for removing all the HTML
formatting in one fell swoop?I count 4 steps.
1. Copy the entire line
2. Paste into notepad
3. Copy the entire line
4. Paste into DW
That does it nicely no matter how much presentational markup
there is.
Murray --- ICQ 71997575
Adobe Community Expert
(If you *MUST* email me, don't LAUGH when you do so!)
==================
http://www.dreamweavermx-templates.com
- Template Triage!
http://www.projectseven.com/go
- DW FAQs, Tutorials & Resources
http://www.dwfaq.com - DW FAQs,
Tutorials & Resources
http://www.macromedia.com/support/search/
- Macromedia (MM) Technotes
==================
"Kals" <[email protected]> wrote in message
news:[email protected]...
>
quote:
I think what the O/P is wanting is a quick and easy method to
remove
> all of
> those presentational tags.
>
> Thanks Gary ? spot on! I'll use the term 'presentational
markup' rather
> than
> 'HTML styles' from now on. (Excuse my ignorance, but
what's an 'OP'?
> Should I
> like being called such a thing? :)
>
>
quote:
Murray: ? but you just cannot create predefined "HTML STYLES"
any
> longer.
> It's no great loss....
>
> Agreed! Okay, we've established that no one's lamenting
the loss of 'HTML
> styles' in the sense of a style sheet that stores HTML
presentational
> markup.
>
>
quote:
And if "HTML STYLES" were not used in the first place, then
even having
> that feature available now wouldn't help OP, if your
interpretation is
> correct.
>
> Perhaps you are misinterpreting what those commands did.
'Clear Paragraph
> Style' was the equivalent of applying a predefined 'HTML
style' with no
> presentational markup ? making it as far as I know, the
quickest, easiest
> way
> to strip all presentational markup out of your HTML
(irrespective of
> whether
> the markup originated through the use of 'HTML styles').
This could have
> very
> easily been replaced by a stand-alone command.
>
>
quote:
There are certainly quick and easy ways to remove many of
them.
> Okay then, here's the test. How many steps does it take
you to clean up
> the
> following paragraph?
>
> <p align="center"><font size="+1" face="Times
New Roman, Times, serif">The
> quick
brown fox
jumps over the
<font
> color="#FF0000">lazy</font>
dog</font></p>
>
> I count 10 steps if you select the entire paragraph and
use nothing but
> the
> Properties panel and/or Text menu. Perhaps you can beat
my attempt. If I
> use
> the 'Clean Up HTML' command, it takes me about 20
seconds to check for and
> type
> in all the individual tags I want removed, then I still
have to manually
> fix
> the alignment. Do you know of a quicker, easier way?
> -
How to select a row in JTable for right mouse click ?
Hi All,
I need to select a row on JTable for right mouse click ?
Can any one help me ?
Thanks a lot.
Seelam.Got solution...
tabel.addRowSelectionInterval(..) works.
thanks. -
Getting the Selected Row from a JTable
hi,
how Can i get the Selected row from a JTable
thanks...You know that JTable class? Well, you see those methods in it called "getSelectedRow()" and "getSelectedRows()"...?
-
Iphoto gives message "no images were selected" when hit print button. Yet the the images are clearly selected in the print window. I've printed hundreds of images without a problem before. Iphoto 6.0.6, MAC 10.5.8, Suggestions?
I have recently started having this problem in PSE8. The Adobe workaround
did work, but I don't fancy having to re register each time I use it.
What I have discovered is that it's nothing to do with the image metadata as it occurs before any image is opened.
It SEEMS to only occur if you use file/open with to open an image in the editor - IE start PSE with that command.
If you close elements down, and start it using programs/PSE/Elements (or your desktop shortcut) - the panorama feature magically works.
Each time I've opened the editor 'automatically' using image/open with, it seems to create the problem.
Hope this helps -
How to select JLabel inside a JTable
hi all,
I have a Jtable which has own renderer so it can store components in it. I have added a Jlabel one of its cells but when I select that row the label stays upon the selected background color. here is a sample screenshot to decribe my problem clearly [http://www.imagecross.com/06/image-hosting-view-01.php?id=6570label.jpg]
is there any way to select the label inside selected background color.
- I have already tried to make the label not opaque but it didnt work -
thanks...I have added bold parts of the code below. if you use other components you can make a type casting and do what you want.
thanks again..
class ComponentRenderer *extends JComponent* implements TableCellRenderer
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
* JLabel l = (JLabel)value;*
* if(isSelected) {*
* l.setForeground(Color.BLUE);*
* l.setOpaque(true);*
* l.setBackground(new Color(184, 207, 229));*
* else {*
* l.setForeground(Color.BLACK);*
* l.setOpaque(true);*
* l.setBackground(Color.WHITE);*
return l;
/*public ComponentRenderer() {
} -
Cell contents selected on focus in JTable
I'm new to swing and trying to get the contents of a JTable cell to be selected when the cell receives focus. I've looked at the TableCellEditor interface and the like, but I just can't seem to get the hang of how it all fits together. Any hits would be appreciated. Thanks.
There are several ways to do this, but here is one to get you started:
First, subclass DefaultCellEditor. Here, I have duplicated all the constructors from DefaultCellEditor but only modified the one used for text.
I have added a inner class, FocusEventHandler, to capture the focus events. In the focusGained method is the code to do the selectAll. (I use the invokeLater so that the selectAll happens after pending events are complete. A mouse click might be interpreted by the text box to position the cursor, so we want the selectAll to happen after that.)
Then, in the constructor for text, I save the text box so the focusGained method knows which text box to selectAll for, register the event handler, and (optionally) change the ClickCountToStart.
public class NewDefaultCellEditor extends javax.swing.DefaultCellEditor {
javax.swing.JTextField saveTextField = null;
// Event handler
public class FocusEventHandler implements java.awt.event.FocusListener {
public void focusGained(java.awt.event.FocusEvent e) {
javax.swing.SwingUtilities.invokeLater(new Runnable () {public void run() {saveTextField.selectAll();}});
public void focusLost(java.awt.event.FocusEvent e) {}
// Constructors
public NewDefaultCellEditor(javax.swing.JCheckBox checkBox) {
super(checkBox);
public NewDefaultCellEditor(javax.swing.JComboBox comboBox) {
super(comboBox);
public NewDefaultCellEditor(javax.swing.JTextField textField) {
super(textField);
saveTextField = textField; // save text field for later
textField.addFocusListener(new FocusEventHandler()); // register event handler
setClickCountToStart(1); // change # of mouse clicks to begin editing
}Now you just have to tell the table to use this Cell Editor. One way to do this is:
MyTable.getColumnModel().getColumn(0).setCellEditor(new NewDefaultCellEditor(new javax.swing.JTextField()));
(this sets the editor for column 0) -
Multiple selection of checkbox in jtable
hi
I am using jtable in which first coloumn is using checbox.Ihave used celleditor and cell renderer for that.I want to check multiple checboxes
at a time and on click of update button wanto send that information to database.But i m not able to check multiple checkboxes.As sson as i click on 2nd checkbox prwvious selection get cleared.Please help me as soon as possible..Ihave used celleditor and cell renderer for that.I want to check multiple checboxesThere is no need to use custom renderers or editors, they are provided by the JTable.
Read the JTable API and follow the link to the Swing tutorial on "How to Use Tables" for a working example. -
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(...); -
Hi All,
I'm looking for a way of selecting all cells from the original drag point to the current cell that the mouse is over.
This is for a year planner which displays the months vertcally and the days horizontally. So if the user was to start selecting cells in one month and move the mouse down a row onto the next month, I would want all cells selected from the first cell to the current cell.
Has anyone got any ideas?Hi Pchatwin,
Any dukes available for bad news? :)
Thanks Stas but wouldn't that select entire rows
rather than cells?
For example, if I have a grid:
12345
67890
and drag from cell 3 to cell 9 I would need to see
cells 3, 4, 5, 6, 7, 8, 9 highlightedUnfortunately this is impossible with JTable's default selection model. By default, JTable models selections simply as an intersection of selected rows and columns. It doesn't track individual cells.
Turning to your example:
If you select cells 2,3,4,5 JTable tracks the following.
Note: The numbers I am using are row/col indexes, not your cell values.
Selected rows = {0}
Selected cols = {1,2,3,4}
This means the following cells are selected:
{{0,1},{0,2},{0,3},{0,4}} or {2,3,4,5}
Now if you want to add cells 6, 7, 8, 9 it won't work. The selection model tracks whether a column is selected or not. It can't be selected for one row and not for another. So it's impossible to have cell 6 selected and not 1. It would mean that column 0 would need to be both selected (to include 6) and not (to include 1). Does this make sense?
Sorry to have to tell you that. On the other hand it may save you some frustration.
Oh, and whether or not one can provide a custom model that allows this, I don't know - I've not tried it myself. It could be, but might be very difficult. For example, what would you return from JTable.getSelectedRows()?
Thanks!
Shannon Hickey (Swing Team)
>
Paul
Maybe you are looking for
-
HT1338 My new magic mouse will not one finger scroll left and right
I am up to date with software but after connecting my new magic mouse it will not one finger scroll left and right. It does scroll up and down. Any ideas on what may be wrong??
-
Accounting document generated even if foreign data incomplete
Hi, I did the customizing for foreign trade data and I created an incompletion procedure (VI29) for some data like Commodity code, Country of destination, statistic value. I have to create a billing document (export from Italy to France) and my expec
-
Sharing photos that others can DOWNLOAD
I'm embarrassed to say that i've been using both iPhoto and IWeb a long time, but I've never understood which "sharing" method to use when I want to let others DOWNLOAD my published photos. The iPhoto help file is confusing because it talks about pub
-
How to disable touch pad on an Envy 17 with Windows 7
I have a new HP Envy 17t laptop running with Windows 7. I use a mouse. When typing, I accidently hit the touch pad and all sorts of messiness happens. How do you disable the Touch Pad. On other HP computers it was quite easy.
-
Hi, I have to modify a report because it goes too slow.. the problem is when joining 5 tables, i'm trying to change it but i'm a little bit "lost".... the original code is de following.. SELECT DISTINCT aaufnr aauart aerdat aktext a~werks