Reacting on selection-changes in a JTable...

Hello,
I created an AbstractTableModel which is the basic for my JTable. Now I want to react on changes of the selection in the table. So I implemented a ListSelectionListener and overwrote the valueChanged()-method. But there is no reaction when the selection changes...is there a special trick with this method, or what else could be the reason for my problem ?
Thanx,
Findus

Did you register your listener?
yourTable().getSelectionModel().addListSelectionListener(yourListener);

Similar Messages

  • How to listen for cell selection changes within a JTable

    Problem: my table has 8 columns, with 4 of them containing very large text (up to 1000 chars). Solution is to set the initial size these columns so that the 1st 20 chars are visible, and if one of these columns gains focus/selection via mouse-clicking/tabbing/arrow keys, the entire text is shown in a JTextArea below the table.
    I added a ListSelectionListener to the table, but this only informs me when the row selection has changed.
    I added a FocusListener to the table, but this only informs me when the table gains/loses focus, not when it's been changed within.
    I added a TableColumnModelListener to the TableColumnModel, but this only informs me when the column selection has changed.
    I didn't bother with MouseListener as this won't handle change of selection via tabbing.
    The LSL got me half way there, and the TCML got me the other half. Any ideas on how to combine?
    Or is there something obvious that I'm missing?

    Walter Laan wrote:
    Use both and call the same method which updates the text area based on the current selected (or focused == lead selection index) cell.Yeah - that's what I figured. I just didn't know if there was a magic bullet (i.e., a single listener) out there that I was missing.
    While you are at it, also add a table model listener which calls the same method if the selected cell is updated.I'll keep that in mind, but it's not necessary in this particular case. The table cells in question will be uneditable. The text area will have supporting Edit/Save/Cancel buttons.

  • 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

  • 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;
    }

  • Change selectedRow in JTable

    Is there anyone can tell how to programmatically change or select a row in JTable so that I can get the selected row using getSelectedRow() method ??

    Try it!
    setRowSelectionInterval( row, row );
    or
    ListSelectionModel rsm = table.getSelectionModel();
    rsm.setLeadSelectionIndex( row );

  • 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);
    }

  • 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 generate selection change event through code in JTree?

    I am developing an application which downloads the file from other system and adds it into the tree. On selecting any file in the tree I m displaying it's contents. But now i am trying to display the contents of downloaded file as soon as it's download completes. Here i am not getting the way to how to generate the event as the download completes, because i tried that setSelectionPath(TreePath path), but it also don't generates the selection change event. Is there any other way to do so?

    Put null in place of oldLeadSelectionPath. From the API for TreeSelectionEvent:
    protected TreePath     oldLeadSelectionPath:
    leadSelectionPath before the paths changed, may be null.
    I'm at the office and can't try out anything, so please let me know whether that works for you.
    db
    edit Or it may be easier to put all code from your valueChanged (...) override in a new method and invoke that method both from valueChanged (...) and wherever else you need.
    Edited by: Darryl.Burke

  • How to block lead selection change in a tree ?

    Hi Guys,
    <u>Scenario</u>
    I have MasterTree - DetailEditor pair. <i>MasterTree</i> is used to visit some tree-structured data and <i>DetailEditor</i> is used to edit currently selected tree node.
    <u>Requirement</u>
    If currently selected node data is updated through <i>DetailEditor</i> and needs to be saved, than on a subsequent tree selection change the user should be warned about unsaved data.
    <u>Implementation</u>
    In <b>onAction</b> event handler of <i>MasterTree</i> I check whether last selected node data is updated and needs to be saved and if this is the case rollback <i>treeSelection</i> to that node. On the time <b>onAction</b> event handler is called the tree selection is changed from the node that needs save to the newly selected node. In order to rollback <i>treeSelection</i> I need to introduce variable referencing last selected tree node.
    <u>Question</u>
    Is there any other technique to implement above scenario without using additional variable and manually rollback <i>treeSelection</i> ? For example, to plug in WDP framework on validation step just before lead selection is changed.
    Thanks in advance

    Alex,
    Here is a link to the phase model of WD:
    http://help.sap.com/saphelp_nw04/helpdata/en/b8/cd96edb9c8794aa362e6e8b4236a1f/frameset.htm
    There aren't any hooks provided prior to the event handlers being called. As far as I can tell, the way you are handling it is the only way that will work.
    -Cindy

  • 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 to veto a JComboBox selection change in ItemListener

    I have a JComboBox whose current value is tied to some data cached in my application. I want to be able to examine the selection in an ItemListener attached to the JComboBox, and if the value is different than what I have cached, I want to ask the user if they really want to change because the change will render some other data as no longer valid. If the user wants to abandon the change, then I want to "abandon" or "veto" the selection change and reset it to the old value.
    For instance, if the combo box has values "Foo" and "Bar" in it, and "Foo" is the cached selection, then the user goes and changes the selection to "Bar", I want to prompt them with something like "You have changed the value to Bar. Doing so will render XXX no longer valid. Do you want to continue?" -- if they cancel the change, then leave the selection as "Foo".
    What is the best way to do this within ItemListener's itemStateChanged? Are there better ways to do this besides what I've outlined? I didn't see anything in "Core JFC" book or the JDK documentation that discussed this sort of thing.
    Thanks in advance,
    Eric

    Hi,
    It is a design problem and not realy a language problem... The way I create vetoing design it that a keep the previous selection of the JComboBox... upon action I look if the application can do the new computation...if not...ask the user... if true| run calculations if not set the JComboBox to the previous selection...
    JRG

  • How to change data in  jtable?

    Hai.I have a problem to change data in jtable.Can anbody help me to slove this?
    Think you in advance

    Did you want to change individual cells?
    For example, to change cell (2, 1) to "new data":
    yourTable.setValueAt("new data", 1, 2)

  • How to trap Selection change

    Hi All,
    I need to observer selection change. How do i go about it. In basicpersistinterface the kBPISelectionObserverImpl is bound with the panel. Similarly I want to call a method on selection change and not update some UI, so where do i need to put my ActiveSelectionObserver.
    It can  be just displaying an alert of selection change, but how do we trap it.
    Please contribute your valuable suggestions.
    Thanks in advance.
    Jasmine Shaikh

    You can aggregate your observer to any easily accessed boss that's permanently around. For example kSessionBoss already has 15 observers, kAppBoss has 7 observers. You would use a private IID, though. Invoke AutoAttach from a StartupShutdown service.
    Given that, you're probably wrong architecture-wise by watching the selection without UI involved. There are plenty other notifications, besides there are also different mechanisms to watch the selection from closer on (e.g. SelectionExt). Can you give more details on your intent?
    Dirk

  • 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.

  • How to change images of selected items in gridview on selection changed event in universal app

    Hi,
    I am developing Universal App. I have bind the images to the Gridview using ObservableCollection. I have set gridview
    SelectionMode as Multiple . I want to change the images of selected items but I don't know how to do in Selection Changed event of Gridview. I got selected items with the help of
    Gridview SelectedItems property. How can i change the images of respected selected items?
    Please reply me asap.
    Thanks in advance.

    Hi, Sorry for late reply,
    Please change the class : 
    public class ImageCollection : INotifyPropertyChanged
    private string source;
    public string Source
    get { return source; }
    set { SetProperty(ref source, value); }
    public int MyProperty { get; set; }
    protected void SetProperty<T>(ref T storage, T value, [System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
    if (!object.Equals(storage, value))
    storage = value;
    if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    protected void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
    if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    public event PropertyChangedEventHandler PropertyChanged;
    XAML
    <GridView x:Name="gd"
    Tapped="gd_Tapped">
    <GridView.ItemTemplate>
    <DataTemplate>
    <Grid Height="300" Width="250">
    <Image Source="{Binding Source}" Stretch="Fill"/>
    <Grid Height="100" Background="#B2000000" VerticalAlignment="Bottom">
    <TextBlock Text="{Binding MyProperty}" FontSize="25" />
    </Grid>
    </Grid>
    </DataTemplate>
    </GridView.ItemTemplate>
    </GridView>
    C#
    //ObservableCollection of class
    ObservableCollection<ImageCollection> img = new ObservableCollection<ImageCollection>();
    public MainPage()
    this.InitializeComponent();
    img.Add(new ImageCollection() { MyProperty = 1, Source = "ms-appx:///Assets/Logo.scale-100.png" });
    img.Add(new ImageCollection() { MyProperty = 2, Source = "ms-appx:///Assets/2.jpg" });
    img.Add(new ImageCollection() { MyProperty = 3, Source = "ms-appx:///Assets/3.jpg" });
    img.Add(new ImageCollection() { MyProperty = 4, Source = "ms-appx:///Assets/4.jpeg" });
    gd.ItemsSource = img;
    private void gd_Tapped(object sender, TappedRoutedEventArgs e)
    GridView gv = (GridView)sender;
    ImageCollection ic = gv.SelectedItem as ImageCollection;
    ic.Source = "ms-appx:///Assets/4.jpeg";
    gv.UpdateLayout();
    I have used  INotifyPropertyChanged now UI is not fluctuate 
    and I have not bind again O-Collection.
    I hope so You will get right answer. 
    shah

Maybe you are looking for

  • Question about the customized FPGA signal generator.

    I connected the AO0 and AO1 ports to the oscilloscope. But I got nothing. What should I do? Attachments: Customized FPGA Signal Generator.lvproj ‏2159 KB

  • What is error code 603 and how does one fix it?

    What is error code 603, please, regarding add-on installation?  (The error codes page says for "error 6xx" to contact the Exchange online forum for assistance..)  It is a "failed online license check" for an add-on that is a free add-on listed on the

  • Duplicate option in workflow

    Hi In CA in admin ACC - Workflow- Publishing-commonWorkflow when i have to make changes in that i just right click on it and gave duplicate the workflow but that duplicate option is ter but its just read only mode cant able to duplicate pls help me h

  • My user doing the direct posting in MIRO without useing the PO

    Hello Exports My user doing the direct posting in MIRO without using the PO. but after posting in MIRO, its picking up the R ( invoice Verification ) in Payment block field. and also i ve check in Vendor master there is no "R" Falg in Payment block f

  • How call the constructor of the super type in the sub type?

    Hi, everybody: There are two type as belowing code: CREATE TYEP super_t AS OBJECT ( a NUMBER(7,1), b NUMBER(7,1), CONSTRUCTOR FUNCTION super_t (a IN NUMBER:=null, b IN NUMBER:=null) RETURN SELF AS RESULT ) NOT FINAL; CREATE TYEP sub_t UNDER super_t (