A problem to get the value of a selected cell

Hi all,
I am trying to get the value of a cell in JTable. The problem that I have is ListSelectionListener only listens if the selection changes(valueChanged method).
It means that if I select apple then rum, only rowSelectionModel is triggered, which means I do not get the index of the column from selectionModel of ColumnModel.
apple orange plum
rum sky blue
This is a piece of code from JTable tutorial that I modified by adding
selRow and selCol variables to keep track of the location so that I can get the value of the selected cell.
Thank you.
if (ALLOW_ROW_SELECTION) { // true by default
ListSelectionModel rowSM = table.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();
selRow = selectedRow;
System.out.println("Row " + selectedRow + " is now selected.");
else {
table.setRowSelectionAllowed(false);
if (ALLOW_COLUMN_SELECTION) { // false by default
if (ALLOW_ROW_SELECTION) {
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
colSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
//Ignore extra messages.
if (e.getValueIsAdjusting()) return;
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
if (lsm.isSelectionEmpty()) {
System.out.println("No columns are selected.");
} else {
int selectedCol = lsm.getMinSelectionIndex();
selCol = selectedCol;
System.out.println("Column " + selCol + " is now selected.");
System.out.println("Row " + selRow + " is now selected.");
javax.swing.table.TableModel model = table.getModel();
// I get the value here
System.out.println("Value: "+model.getValueAt(selRow,selCol));
}

maybe you can try with :
table.getSelectedColumn()
table.getSelectedRow()
:)

Similar Messages

  • ListView + MVVM: How do I get the value of a selected cell?

    Hi,
    I love programming WPF using MVVM, but sometimes easy looking problems lead to unbearable suffering.
    Here is my problem: I have a simple list view with about a couple of columns. All I want to do is to copy the cell content to clipboard, when the user right-clicks on a cell.
    <ListView Grid.Row="0" ItemsSource="{Binding Articles}" SelectedItem="{Binding SelectedArticle}" SelectionMode="Single">
    <ListView.View>
    <GridView>
    <GridView.Columns>
    <GridViewColumn Header="ID" Width="70" DisplayMemberBinding="{Binding Path=ID, Mode=OneWay}" />
    <GridViewColumn Header="Name" Width="150" DisplayMemberBinding="{Binding Path=Name, Mode=OneWay}"/>
    <GridViewColumn Header="Price" Width="100" DisplayMemberBinding="{Binding Path=Price, Mode=OneWay}"/>
    <GridViewColumn Header="Description" Width="70" DisplayMemberBinding="{Binding Path=Description, Mode=OneWay}"/>
    </GridView.Columns>
    </GridView>
    </ListView.View>
    </ListView>
    Without MVVM I probably would have used the some Click-Event and extract the info from the event args. But of course I don't want to break the MVVM pattern.
    But if I use some kind of event binding I cannot find a way to retrieve event args or the sender object:
    <i:EventTrigger EventName="PreviewMouseRightButtonDown">
    <i:InvokeCommandAction Command="{Binding CopyCellValueToClipCommand}"/>
    </i:EventTrigger>
    Using this trigger I can react to the desired event, but how can I retrieve the cell value?
    I really hope you guys have a clue.
    Thanks for your help,
    Michael

    I'm not so sure about listview, I rarely use them for more complicated requirements.
    I would use a datagrid.
    You can bind a cellinfo:
    http://stackoverflow.com/questions/20080130/how-to-bind-currentcell-in-wpf-datagrid-using-mvvm-pattern
    <DataGrid AutoGenerateColumns="True"
    SelectionUnit="Cell"
    SelectionMode="Single"
    Height="250" Width="525"
    ItemsSource="{Binding Results}"
    CurrentCell="{Binding CellInfo, Mode=OneWayToSource}"/>
    and
    private DataGridCellInfo _cellInfo;
    public DataGridCellInfo CellInfo
    get { return _cellInfo; }
    set
    _cellInfo = value;
    OnPropertyChanged("CellInfo");
    MessageBox.Show(string.Format("Column: {0}",
    _cellInfo.Column.DisplayIndex != null ? _cellInfo.Column.DisplayIndex.ToString() : "Index out of range!"));
    You can use index and bind selecteditem or get contents of cell:
    public DataGridCell GetDataGridCell(DataGridCellInfo cellInfo)
    var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
    if (cellContent != null)
    return (DataGridCell) cellContent.Parent;
    return null;
    Hope that helps.
    Recent Technet articles:
    Property List Editing ;  
    Dynamic XAML

  • How to get the values from html:select? tag..?

    i tried with this, but its not working...
    <html:select styleClass="text" name="querydefs" property="shortcut"
                 onchange="retrieveOptions()" styleId="firstBox" indexed="true">
    <html:options collection="advanced.choices" property="shortcut" labelProperty="label" />
    </html:select>
                        <td align="left" class="rowcolor1">
                        <script language="javascript" type="text/javascript">
                              function retrieveOptions(){
                             var sel = document.querydefs.options;
                             var selectedOption = sel[sel.selectedIndex].value;
                             document.write(selectedOption);
                           </script>

    <td align="left" class="rowcolor1">
                        <script language="javascript" type="text/javascript">
                              function retrieveOptions(){
                             var sel = document.querydefs.options;
                             var selectedOption = sel[sel.selectedIndex].value;
                             document.write(selectedOption);
                           </script>This java script is not working at all..its not printing anything in document.write();
    This is code..
    <td class="rowcolor1" width="20%">
    <html:select styleClass="text" name="querydefs" property="shortcut"
                             onchange="retrieveSecondOptions()" styleId="firstBox"
                             indexed="true">
                             <html:options collection="advanced.choices" property="shortcut"
                                  labelProperty="label"  />
                        </html:select>i tried with this also. but no use..i'm not the getting the seleced option...
    function retrieveOptions(){
    firstBox = document.getElementById('firstBox');
                             if(firstBox.selectedIndex==0){
          return;
        selectedOption = firstBox.options[firstBox.selectedIndex].value;
    }actually , how to get the values from <html:select> ...?
    my idea is to know which value is selected from the combo box(<html:select> ) if that value is equal some string i have enable a hyperlink to open a popup window

  • How to get the position of a selected cell in a table ?

    Hi,
    How can I get the position of a selected cell in a table or in a list multicolumn cmd ?
    Thanks.

    Invoke node >>> point to Row Column
    Ben
    Message Edited by Ben on 07-19-2007 03:14 PM
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Attachments:
    Point_To_Row_Column.PNG ‏22 KB

  • Having problem to get the value from radio button

    i am doing my double module project for my degree course and i am also a newbie in JSP. Hope there is someone can help me to solve this problem. Now, i set the value of a radio button to "don't smoke", "smoke lightly", and "smoke heavily". Then i use request.getParameter ("smoking behavior") to get the value selected by the user, but the result is only "don't" or "smoke", which the character after spacing will be not be retrieved. I dun know how to solve it, so can any expert here help me to solve this problem? Thanks for helping.

    Why do you have to use whitespace. If your radio button group is name smokingBehavior - no whitespace, wouldn't it just make sence to have values of don't, lightly and heavily. This would solve the problem easily. If your teacher is being a pain in the a&!, and requires you to use whitespace for your naming variables I guess you could insert %20 between the two words and unescape the value on the server side. This seems like a lot of unnecessary work and a silly solution - good luck!

  • Get the value from a selected row in a table

    Hi all,
    My table contains a tree structure.
    When I select a single row, I need to get the value of a particular column.
    I created an action on the leadSelect of the table and gave the following code:
    public void onActionleadValue(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionleadValue(ServerEvent)
        String strLeadValue = wdContext.nodeAttribute_View_Out().currentAttribute_View_OutElement().getAttributeAsText("<MyModelAttributename>");
        wdComponentAPI.getMessageManager().reportSuccess("selected lead value "+strLeadValue);
        wdContext.currentContextElement().setLeadselectedvalue(strLeadValue);
        //@@end
    My Bapi returns me 6 records. and when I click on any row its always pointing to the last record value.
    What could be the problem?
    Thanks
    Anjana

    Hi Anjana,
    Try this.
    try
         IWDMessageManager msg = wdComponentAPI.getMessageManager();
         int leadselect = wdContext.nodeSChild1().getLeadSelection();
          for(int i=0;i<wdContext.nodeSChild1().size();i++)
              if(leadselect == i)
              //Displaying output in diff table
    //           IPublicTestComp.ITableNodeElement tabelm = wdContext.createTableNodeElement();
    //           tabelm.setAttribute1(wdContext.nodeSChild1().getSChild1ElementAt(i).getAttribute1());
    //           tabelm.setAttribute2(wdContext.nodeSChild1().getSChild1ElementAt(i).getAttribute2());
    //           tabelm.setAttribute3(wdContext.nodeSChild1().getSChild1ElementAt(i).getAttribute3());
    //           wdContext.nodeTableNode().addElement(tabelm);
              String att1 = wdContext.nodeSChild1().getSChild1ElementAt(i).getAttribute1();
              String att2 = wdContext.nodeSChild1().getSChild1ElementAt(i).getAttribute2();
              String att3 = wdContext.nodeSChild1().getSChild1ElementAt(i).getAttribute3();
                     msg.reportSuccess("Row ("i") : "att1"====="att2"======"+att3);
    } catch (WDDynamicRFCExecuteException e) {
         wdComponentAPI.getMessageManager().reportException("Message : "+ e.getMessage(),true);
    Regards,
    Mithu

  • How do you get the value of a selected list item?

    I have a drop-down list that the user can choose from. How do I get the value of what they selected? I thought I could do this by using the NAME_IN function, but I'm getting FRM-40105 Unable to resolve reference to item X. I don't know what I'm doing wrong.
    Thanks!

    Hi,
    You can use an WHEN-LIST-CHANGED trigger, attached to the list-item itself. And, in this trigger, you can use the name of the item to refer its value.
    For example:
    :block_name.list_item_name
    John

  • How do I get the values from a selected row.

    I am using JDeveloper 9.0.5. On my page, I have placed a button within a table. The button has been assigned an event. The event is within my Action class. This class implements DataAction and has overriden the
    processComponentEvents(DataActionContext actionContext);
    method.
    Question: While I am within the processComponentEvents method, is it possible to obtain the values of selected row?

    Good Morning Jeffery,
    First off thanks for your clear explanation. I have a few related questions as noted from your response:
    There are two ways to communicate the desired model row between the UIX view and the struts controller. One way is to use the singleSelection component in your table and put your buttons in the singleSelection's contents.
    When the user selects the radio button for a particular row and then clicks on one the buttons, a built in event handler in UIX will set the current row in the model to be the user selected row. Therefore, your Struts action can operate on the currently selected model row.
    When you drop a UIX table from the data control palette it is automatically set up in this way (with a single selection).
    Ok, Lets say that i've set everything up as you described. Not lets say that the button was pressed and I hit the overriddenprotected void processComponentEvents(DataActionContext actionContext) throws IOException, ServletException ;
    When I look at the request object, I do not see the values. How do I get access to the rowkey at this point?
    Some people, however, want to actually render buttons in their table rows, and have those buttons initiate an action on their row. If you are doing this, then you need to pass the row id to your struts action as a parameter, which means that you need to know the row id when you are rendering a button for a given row. There is an EL expression that will return the row-id for the current row, it is:
    ${uix.current.rowKeyStr}
    which is not so obvious or well documented in the preview release (sorry) but should be for the production release.
    A generic code snippet would go a long way to shedding some light on that. I guess I am use to using JDeveloper 9.0.3. It seems,"to me", that JDev 9.0.5 has put a completely new twist on things. I find myself wondering when I can use the 9.0.3 syntax and when
    should not. If your team has any short source toys around which demonstrated using rowkeys, or accessing the internal parts of the
    struts controller, I would find that invaluable. It dose not matter if this information is documented.
    Thank you

  • How to get the values of last selected row in Table?

    Hi,
    I have one editable table , where i have Create, Delete and Commit operation on it.
    When i am clicking on Create button it add new row to my table.
    But I want the value of my last selected row from the table in my Bean.
    Can anyone suggest me please....... its urgent
    Jdev:- 11.1.1.0.3
    Thanks,
    Ramit

    just get this code empTable is the table binding
                    RowKeySet rks = new RowKeySetImpl(); 
                    CollectionModel model = (CollectionModel)empTable.getValue(); 
          RowKeySet selectedRowKeys = empTable.getSelectedRowKeys();
          if (selectedRowKeys != null)
                Iterator iter = selectedRowKeys.iterator();
                if (iter != null && iter.hasNext())
                  empTable.setRowKey(iter.next());
                  model.setRowIndex(empTable.getRowIndex()); 
                  Object key = model.getRowKey(); 
                  rks.add(key); 
                    empTable.setSelectedRowKeys(rks); 
          AdfFacesContext.getCurrentInstance().addPartialTarget(empTable);
        public void setEmpTable(RichTable empTable) {
            this.empTable = empTable;
        public RichTable getEmpTable() {
            return empTable;
        }

  • How  to get the value of multi-select in the   Dashboard Prompt

    I have a multi-select prompt in the Dashboard Prompt,  what I want is,   how do I know that user has choose one value,
    for examle,  for some reasons,  if user didn't choose any value,  then I will set one column in answer as "customer office" , if user choose one value, then the column in answer will be "customer name". 
    any comments, thanks.

    Hi,
    first define the presentation variable for the required column prompt. ex: PV
    Then in report level set the filter for that column = @{PV}{customer office}. here u have to give default value as "customer office", so by default the report in dashboard will show customer office even though the user does not select any value from dashboard prompt.
    Mark If Helpful/correct.
    Thanks.

  • Get the value of a selected radio button within a ToggleGroup

    All
    Please see the script below. All I'm trying to do is to identify the selected radio button within a ToggleGroup. This has been working in JavaFX 1.2.
    This is JavaFX 1.3 running on NetBeans 6.9 (beta) on Ubuntu 10.04
    Does anyone know why this is no longer working?
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    import javafx.scene.control.ToggleGroup;
    import javafx.scene.control.RadioButton;
    import javafx.scene.layout.HBox;
    import javafx.scene.control.Toggle;
    def levelGroup = ToggleGroup {};
    var selected: Toggle = bind levelGroup.selectedToggle on replace {
        // here I want to capture the value of the selected toggle
        // the outputted value is always 'null'
        println("level toggle = {selected.value}");
        println("selectedToggle = {levelGroup.selectedToggle.value}");
    Stage {
       scene: Scene {
          width: 300
          height: 300
          content: [
             HBox {
                    translateX: 100
                    translateY: 67
                    spacing: 20
                    content: [
                        RadioButton {
                            toggleGroup: levelGroup
                            text: "Easy"
                            selected: false
                        RadioButton {
                            toggleGroup: levelGroup
                            text: "Medium"
                            selected: true
                        RadioButton {
                            toggleGroup: levelGroup
                            text: "Hard"
                            selected: false
    }

    Actually, your code above wouldn't have worked in JavaFX 1.2 as we only added the value property to the new Toggle mixin in 1.3. I believe what worked for you in 1.2 was when you referred to text, which is not a property on Toggle, so you need to cast the selected variable from Toggle to a RadioButton, which does have a text property. For example, this would work:
    var selected: Toggle = bind levelGroup.selectedToggle on replace {
        println("level toggle = {(selected as RadioButton).text}");
        println("selectedToggle = {(levelGroup.selectedToggle as RadioButton).text}");
    }Alternatively, instead of casting like this, you can store a value in the value property of the Toggle mixin class, which is extended by RadioButton. For example, your code could be changed to the following (in particular note that the only change is the addition of the value properties in each of the RadioButton):
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    import javafx.scene.control.ToggleGroup;
    import javafx.scene.control.RadioButton;
    import javafx.scene.layout.HBox;
    import javafx.scene.control.Toggle;
    def levelGroup = ToggleGroup {};
    var selected: Toggle = bind levelGroup.selectedToggle on replace {
        println("level toggle = {selected.value}");
        println("selectedToggle = {levelGroup.selectedToggle.value}");
    Stage {
       scene: Scene {
          width: 300
          height: 300
          content: [
             HBox {
                    translateX: 100
                    translateY: 67
                    spacing: 20
                    content: [
                        RadioButton {
                            toggleGroup: levelGroup
                            text: "Easy"
                            selected: false
                            value: "Easy"
                        RadioButton {
                            toggleGroup: levelGroup
                            text: "Medium"
                            selected: true
                            value: "Medium"
                        RadioButton {
                            toggleGroup: levelGroup
                            text: "Hard"
                            selected: false
                            value: "Hard"
    }This approach saves you from having to cast from Toggle to RadioButton. This second approach is actually very powerful, as you can store any object in the value field, and can then easily retrieve it at a later point when the user selects the desired RadioButton. Of course, you can just use it as in the simple case above as well.
    I hope that helps.

  • How to get the values of a selected row and edit it

    hi all,
    i am using a table component.I am populating it from the database.i used static text to display the data .i have a edit button in the last column. when i click on it that particular rows data should be shown in a text field in that row itself,so that i should be able to edit it and then if i save it it that row should change to statictext with the updated data.
    please provide a solution for this...
    regards,
    rpk

    Hi Andrea,
    If you are using ADFBC, the easiest way is to drop the attribute(Say Name) from the data control palette as outputText component and add partialTriggers property of it to point to table id(to refresh the outputText whenever the row is selected in table)
    Sireesha

  • How to get the position of a selected cell in a table without using the mouse event?

    Dear All,
        I have a question about table:After clicking the cell of a table, the cell is into the edit status. How to know the row number and column number of the cell, when I click a button?
       The link below is using the mouse down event:
       http://forums.ni.com/ni/board/message?board.id=170&message.id=260102&query.id=55917#M260102
       Is there any other way to do it? Having tried to using the "edit position"  property, but it seems not working well.
       Thanks for any suggestion.
    Hugo 
    Attachments:
    table.vi ‏17 KB

    It works well with the "edit position" property.
    See attached
    Attachments:
    table.vi ‏12 KB

  • Problem in getting the current value of the drop down while calling value change listener

    I have 2 drop down list. I am trying to get the value of first drop down from other drop downs value change listener. Initially one drop down contains a default value. First time I got the value while calling the value change listener. But if I change the default value to other in the first drop down and call the value change listener of the second drop down then I got the old value in the bean. Can anyone suggest a process

    If I use the following code it gives me the current index.
                valueChangeEvent.getComponent().processUpdates(FacesContext.getCurrentInstance());
                System.out.println(valueChangeEvent.getNewValue());
    This is also giving me current index.
    BindingContainer container = BindingContext.getCurrent().getCurrentBindingsEntry();
    AttributeBinding attrIdBinding = (AttributeBinding)container.getControlBinding("PersonTypeId1");
    if(attrIdBinding.getInputValue()!=null)
                   System.out.println(attrIdBinding.getInputValue().toString());
    But at last I got some help from Shay Shmeltzer's Weblog.
    BindingContainer bindings =
                    BindingContext.getCurrent().getCurrentBindingsEntry();
                    // Get the sepecific list binding
                    JUCtrlListBinding listBinding =
                    (JUCtrlListBinding)bindings.get("PersonTypeId1");
                    // Get the value which is currently selected
                    Object selectedValue = listBinding.getSelectedValue();
                      long value =0L;
                    if(selectedValue!=null){
                        System.out.println("Sudip.. Person Type using bindings"+selectedValue.toString());
    But this returns "ViewRow [oracle.jbo.Key[300000860721156 ]]"
    300000860721156 is the original value.. Would you please help me to figure it.

  • Cannot get the value after space

    i am doing my double module project for my degree course and i am also a newbie in JSP. Hope there is someone can help me to solve this problem. Now, i set the value of a radio button to "don't smoke", "smoke lightly", and "smoke heavily". Then i use request.getParameter ("smoking behavior") to get the value selected by the user, but the result is only "don't" or "smoke", which the character after spacing will be not be retrieved. I dun know how to solve it, so can any expert here help me to solve this problem? Thanks for helping.

    You can't use spaces in passed parameters; either give your options numerical values that you can translate on the receiving end, or do an URLEncoder.encode() on the values before submitting them. If you encode them, you'll do an URLDecoder.decode() on them on the receiving end.
    URLEncoder.encode("don't smoke") = "don%27+smoke"
    URLDecoder.decode("don%27+smoke") = "don't smoke"

Maybe you are looking for

  • JTable MultiSelection

    I want to enable a multi selection of rows in a table - how do i get the selected rows number? If it is only one row i can recognize it by the click on the table.....should i just do the same operation?

  • How can i connect my printer to my computer without any chords

    Help me connect my printer to my laptop please

  • Can JOptionPane produce an editable JComboBox?

    Can I use JOptionPane for an input dialog component with a data input area represented by an editable JComboBox ? For example : JOptionPane.showInputDialog( parent, � How Much?�, �This is the title�, JOptionPane.QUESTION_MESSAGE, null, new Object[] {

  • CS-MARS bandwidth utilization

    Hi, I know this product is end of sales and end of support by Cisco now. However appreciate if some MARS experts can guide me how to generate a bandwith utilization report on CS-MARS (like bandwidth consumption on switches based on interfaces) and wh

  • CS6 Video Editing Tutorial Books?

    Can anyone recommend good CS6 video editing tutorials? Preferably a book that covers in-depth video editing in PS. (online tutorials would be helpful as well.) Specifically I want to select portions of a video and cut it out.  (Could be anywhere in t