JTable: Selecting rows in columns independently

Dear all,
I have a JTable with two columns. I want the user to be able to select cells in columns independently. At present, the entire row gets marked as selected. Is it possible at all to, for instance, select row1 1 to 3 in column 1 and rows 4 to 5 in column 2? If so, where's the switch? Thanks a lot in advance!
Cheers,
Martin

Are you trying to use a seperate table for each column.
Thats not a good idear.
Here is what you have to do.
1. Create a sub class of JTable
2. You will have to redefine how the selection is done so. You will need some sort of a collection to store the list of selected cells indexes
2.1 Selecting a cell is simply adding the coordinations of the cell to the selection
2.2 de selecting is just removing it from the collection.
2.3 Here is what you have to override
     setColumnSelectionInterval()
     setColumnSelectionInterval()
     changeSelection()
     selectAll()
     getSelectedColumns()
     getSelectedColumn()
     getSelectedRows()
     getSelectedRow() You migh also need few new methods such as
     setCellSelected(int row, int column, boolean selected);
     boolean isCellSelected(int row, int column);
     clearSelection();
     int[][] getSelectedCells();You will have to implement the above in terms of your new data structure.
3. Handle mouse events.
Ex:- when user cicks on a cell if it is already selected it should be deselected (see 2.2)
other wise current selected should be cleared and the clicked cell should be selected
if your has pressed CTRL key while clicking the the cell should be selected without deselecting the old selection.
---you can use above using a MouseListener
When the user hold down a button and move the mouse accross multiple cell those need to be selected.
--- You will need a MouseMotionListener for this
You might also need to allow selection using key bord. You can do that using a KeyListener
4. Displaying the selection
You have to make sure only the selected cells are high lighted on the table.
You can do this using a simple trick.
(Just override getCellEditor(int row, int column) and getCellRenderer(int row, int column) )
Here is what you should do in getCellRenderer(int row, int column)
public TableCellRenderer getCellRenderer(int row, int column)
  TableCellRenderer realRenderer = super.getCellRenderer(int row, int);
  return new WrapperRenderer(realRenderer,selectedCellsCollection.isCellSelected(row,column));
static class WrapperRenderer implements TableCellRenderer{
    TableCellRenderer realRenderer;
    boolean selected;
    public WrapperRenderer(TableCellRenderer realRenderer, boolean selected){
       this.realRenderer = realRenderer;
       this.selected = selected;
    public Component getTableCellRendererComponent(JTable table,
                                               Object value,
                                               boolean isSelected,
                                               boolean hasFocus,
                                               int row,
                                               int column){       
        return realRenderer.getTableCellRendererComponent(table,value,selected,hasFocus,row,column);
}What the above code does is it simply created wrapper for the Renderer and when generating the rendering component it replaces the isSeleted flag with our on selected flag
and the original renderer taken from the super class will do the rest.
You will have to do the same with the TableCellEditor.
By the way dont use above code as it is becouse the getCellRenderer method create a new instance of WrapperRenderer every time.
If the table has 10000 cells above will create 10000 instances. So you should refine above code.
5. Finnaly.
Every time the selection is changes you should make the table rerender the respective cells in or der to make the changes visible.
I'll leave that part for you to figure out.
A Final word
When implementing th above make sure that you do it in the java way of doing it.
For the collection of selected cells write following classes
TableCellSelectionModel  // and interface which define what it does
DefaultTableCellSelectionModel //Your own implementation of above interface the table you create should use thisby default
//To communicate the selection changes
TableCellSelectionModelListener
TableCellSelectionModelEventif you read the javadoc about similer classes in ListSelectionModel you will get an idear
But dont make it as complex as ListSelectionModel try to keep the number of methods less than 5.
If you want to make it completly genaric you will have to resolve some issues such as handling changes to the table model.
Ex:- Rows and colums can be added and removed in the TableModle at the run time as a result the row and column indexes of some cells might change
and the TableCellSelectionModel should be updated with those changes.
Even though the todo list is quite long if you plan your implementation properly the code will not be that long.
And more importantly you will learn lots more by trying to implementing this.
Happy Coding :)

Similar Messages

  • How to set the Selected row and Column in JTable

    Hi,
    i have a problem like the JTable having one Method getSelectedRow() and getSelectedColumn to know the Selected row and Column but if i want to explicitly set the Selected Row and Column,then there is no such type of Methods.If anybody has any solution then i will be thankful to him/her.
    Praveen K Saxena

    Is that what you're looking for? :myTable.getSelectionModel().setSelectionInterval(row, row);
    myTable.getColumnModel().getSelectionModel().setSelectionInterval(column, column);

  • Select row and column from header in jtable

    hello i have a problem to select row and column from header in jtable..
    can somebody give me an idea on how to write the program on it.

    Hi Vicky Liu,
    Thank you for your reply. I'm sorry for not clear question.
    Answer for your question:
    1. First value of Open is item fiels in Dataset2 and this value only for first month (january). But for other month Open value get from Close in previous month.
    * I have 2 Dataset , Dataset1 is all data for show in my report. Dataset2 is only first Open for first month
    2. the picture for detail of my report
    Detail for Red number:
    1. tb_Open -> tb_Close in previous month but first month from item field in Dataset2
    espression =FormatNumber(Code.GetOpening(Fields!month.Value,First(Fields!open.Value, "Dataset2")))
    2. tb_TOTAL1 group on item_part = 1
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)))
    3. tb_TOTAL2 group on item_part = 3 or item_part = 4
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) + ReportItems!tb_TOTAL1.Value )
    4. tb_TOTAL3 group on item_part = 2
    expression =FormatNumber(Sum(CDbl(Fields!budget.Value)) - ReportItems!tb_TOTAL2 .Value)
    5. tb_Close -> calculate from tb_TOTAL3 - tb_Open
    expression =FormatNumber(Code.GetClosing(ReportItems!tb_TOTAL3.Value,ReportItems!tb_Open.Value))
    I want to calculate the value of tb_Open and tb_Close. I try to use custom code for calculate them. tb_close is correct but tb_Open is not correct that show value = 0 .
    My custom code:
    Dim Shared prev_close As Double
    Dim Shared now_close As Double
    Dim Shared now_open As Double
    Public Function GetClosing(TOTAL3 as Double,NowOpening as Double)
        now_close = TOTAL3 + NowOpening
        prev_close = now_close
        Return now_close
    End Function
    Public Function GetOpening(Month as String,NowOpen as Double)
        If Month = "1" Then
            now_open = NowOpen
        Else    
            now_open = prev_close
        End If
        Return now_open
    End Function
    Thanks alot for your help!
    Regards
    Panda A

  • An unusual select rows as columns...

    Colleagues,
    I could really use some help on this one. Thanks in advance for all your help.
    Here is what I have:
    the input (create and insert scripts provided below) is:
    ID SCHEMA_ID TBL_ID TBL_COLS_ID COLUMN_VALUE
    =============================================
    100 1 1 76 0
    101 1 1 77 ABCD
    102 1 1 76 0
    103 1 1 77 DEF
    COLUMN NAMES:
    TBL_COLS_ID 76 = 'KEY'
    TBL_COLS_ID 77 = 'KEYVAL'
    End result I am looking for is to select rows into columns like:
    ALSO, I would like to know how this can be done in a dynamic way within a PLSQL procedure as there are multiple tables and columns in each table are different.
    SCHEMA_ID TBL_ID KEY KEYVAL
    =============================
    1 1 0 ABCD
    1 1 0 DEF
    select schema_id,tbl_id,
    decode( tbl_cols_id, 76, COLUMN_VALUE, null) KEY,
    decode( dr_table_cols_id, 77, COLUMN_VALUE, null) KEYVAL
    from items where schema_id =1
    and tbl_id =1
    CREATE TABLE ITEMS(
    ID NUMBER NOT NULL,
    SCHEMA_ID NUMBER,
    TBL_ID NUMBER,
    TBL_COLS_ID NUMBER,
    COLUMN_VALUE VARCHAR2 (30)
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151056, 1, 1, 76, '0');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151057, 1, 1, 77, 'ABCD');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151058, 1, 1, 76, '0');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151059, 1, 1, 77, 'XYZ ');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151060, 1, 1, 76, '0');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151061, 1, 1, 77, 'DEF');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151062, 1, 1, 76, '0');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151063, 1, 1, 77, 'TNT ');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151064, 1, 1, 76, '0');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151065, 1, 1, 77, 'CD ');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151066, 1, 1, 76, '0');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151067, 1, 1, 77, 'NN ');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151068, 1, 1, 76, '0');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151069, 1, 1, 77, 'BCDA');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151070, 1, 1, 76, '0');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151071, 1, 1, 77, 'GAG ');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151072, 1, 1, 76, '0');
    Insert into items
    (ID, SCHEMA_ID, TBL_ID, TBL_COLS_ID, COLUMN_VALUE)
    Values
    (151073, 1, 1, 77, 'ABC1');
    Thank you.

    If I understand correctly, you want to pair up successive records to match the key and value pairs. Assuming that each successive pair of id's (e.g. 151056/76 and 151057/77) go together, then something like tthis should do it. Not that I replaced your 0 in the records for the 76 column values with the id just to make sure that the rows were pairing correctly.
    SQL> SELECT schema_id, tbl_id, key, keyval
      2  FROM (
      3  SELECT schema_id,tbl_id,
      4         DECODE( tbl_cols_id, 76, COLUMN_VALUE, null) KEY,
      5         LEAD(DECODE( tbl_cols_id, 77, COLUMN_VALUE, null),1)
      6         OVER (ORDER BY ID) KEYVAL
      7  FROM items
      8  WHERE schema_id =1 and
      9        tbl_id =1)
    10  WHERE key IS NOT NULL and
    11        keyval IS NOT NULL;
    SCHEMA_ID     TBL_ID KEY          KEYVAL
             1          1 151056       ABCD
             1          1 151058       XYZ
             1          1 151060       DEF
             1          1 151062       TNT
             1          1 151064       CD
             1          1 151066       NN
             1          1 151068       BCDA
             1          1 151070       GAG
             1          1 151072       ABC1TTFN
    John

  • Refreshing JTable contents (rows and columns) handling.

    Hi,
    I have a general question related to refreshing the contents of JTable and handling some application specific requirements.In our application we are planning to refresh the contents of JTable automatically after certain period of time by fetching data from database and update the JTable contents or user has clicked refresh button.
    But following scenarios we are planning to handle when refresh is called automatically or user has clicked refresh button.
    1) User is working with data of JTable. Like rows of JTable has checkBoxes and user selects them and doing operation like viewing the details of selected rows in new details dialog. So if refreshing is done then the selection will be lost if I update the whole data in JTable.
    a)Will it be possible to append the data at the end of JTable rows without disturbing the existing JTable contents.
    b) Is it feasible to compare the data of existing rows and newly fetched rows and update only the rows whose values are changed in database or update specifically updated columns. But this comparision for finding changed values will result in performance problems.So are there any other alternatives of doing this, ideas are most welcome.
    c) Simple way is to alert the user that data will be updated and everything will be refreshed will be the choice in worst case.
    I guess many may have encountered such problems and may have solved it depending on the product requirements.
    Ideas and suggestions are most welcome.
    Regards.

    Hi,
    Here are my views and my assumptions.
    Assumptions :
    1) Your JTable is populated with list of Objects.
    2) Your tables in database is having columns like created date, created time, updated date updated time
    3) Order by clause for all the time will remain same.
    If these assumptions are correct then I think you can achieve your goal.
    Here how it is.
    Your application session will maintain last db hit time and will maintain for every hit that applicate made to fetch data from db.
    When object is created on the server side once it fetch data from table it will compare the created date/time or update date/time with the session varibale that holds last visit date/time. Based on this flag need to be set to indicate if this item is added/updated/deleted since last visit.
    And when all these object is returned to your client, the table model will iterate through the list and based on object index in the list and and if object is changed will update only that perticular row.
    Hope this is what you want to achieve.
    Regards

  • JTable fixed Row and Column in the same window

    Hi
    Could anyone tip me how to make fixed row and column in the same table(s).
    I know how to make column fixed and row, tried to combine them but it didnt look pretty.
    Can anyone give me a tip?
    Thanks! :)

    Got it to work!
    heres the kod.. nothing beautiful, didnt clean it up.
    * NewClass.java
    * Created on den 29 november 2007, 12:51
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package tablevectortest;
    * @author Sockan
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class FixedRowCol extends JFrame {
      Object[][] data;
      Object[] column;
      JTable fixedTable,table,fixedColTable,fixedTopmodelTable;
      private int FIXED_NUM = 16;
      public FixedRowCol() {
        super( "Fixed Row Example" );
        data =  new Object[][]{
            {      "","A","A","A","",""},
            {      "a","b","","","",""},
            {      "a","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {      "I","","W","G","A",""}};
        column = new Object[]{"A","B","C","D","E","F"};
        AbstractTableModel fixedColModel = new AbstractTableModel() {
          public int getColumnCount() {
            return 1;
          public int getRowCount() {
            return data.length;
          public String getColumnName(int col) {
            return (String) column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel    model = new AbstractTableModel() {
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col+1];
          public Object getValueAt(int row, int col) {
            return data[row][col+1];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col+1] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedTopModel = new AbstractTableModel() {
          public int getColumnCount() { return 1; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedModel = new AbstractTableModel() {     
          public int getColumnCount() { return column.length-2; }
          public int getRowCount() { return FIXED_NUM; }
          public Object getValueAt(int row, int col) {
            return data[row + (data.length - FIXED_NUM)][col+1];
        table = new JTable( model );
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTable = new JTable( fixedModel );
        fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedColTable= new JTable(fixedColModel);
        fixedColTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedColTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fixedTopmodelTable = new JTable(fixedTopModel);
        fixedTopmodelTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTopmodelTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);   
        JScrollPane scroll      = new JScrollPane( table );
         scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
         scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
          public void setColumnHeaderView(Component view) {}
        fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        fixedScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        JScrollBar bar = scroll.getVerticalScrollBar();
        JScrollBar dummyBar = new JScrollBar() {
          public void paint(Graphics g) {}
        dummyBar.setPreferredSize(bar.getPreferredSize());
        scroll.setVerticalScrollBar(dummyBar);
        final JScrollBar bar1 = scroll.getHorizontalScrollBar();
        JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
        bar2.addAdjustmentListener(new AdjustmentListener() {
          public void adjustmentValueChanged(AdjustmentEvent e) {
            bar1.setValue(e.getValue());
        JViewport viewport = new JViewport();
        viewport.setView(fixedColTable);
        viewport.setPreferredSize(fixedColTable.getPreferredSize());
        fixedScroll.setRowHeaderView(viewport);
        fixedScroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedColTable
            .getTableHeader());   
        JViewport viewport2 = new JViewport();
        viewport2.setView(fixedTopmodelTable);
        viewport2.setPreferredSize(fixedTopmodelTable.getPreferredSize());
        scroll.setRowHeaderView(viewport2);
        scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTopmodelTable
            .getTableHeader()); 
        scroll.setPreferredSize(new Dimension(600, 19));
        fixedScroll.setPreferredSize(new Dimension(600, 100)); 
        getContentPane().add(     scroll, BorderLayout.NORTH);
        getContentPane().add(fixedScroll, BorderLayout.CENTER);   
      public static void main(String[] args) {
        FixedRowCol frame = new FixedRowCol();
        frame.addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent e ) {
            System.exit(0);
        frame.pack();
        frame.setVisible(true);
    }

  • How to select rows or columns of tables without using the mouse?

    2nd post ever! Yeah! \m/
    In Excel, I can select entire rows or columns of data WITHIN TABLES--i.e., not selecting entire sheet rows or columns--by going to any cell on the perimeter of the table, holding down shift+ctrl, and clicking a direction arrow. So for example, if I have a table in columns D-G and rows 1-5, I can highlight row 4 by going to the first or last cell of that row, holding down the shift+ctrl, and hitting the appropriate direction arrow. You might think this is superfluous given that you can use the mouse to select cells. But that becomes cumbersome with large tables, and this method can be more efficient even with small tables.
    Similarly, it's often useful to navigate tables, particularly large ones, by moving from any cell within the table to the end or beginning of that row or column by holding down ctrl and hitting the appropriate arrow key. In Excel, this ctrl+arrow key method also allows you to skip blank cells, which is another very useful navigational feature.
    I tried numerous combos involving shift, ctrl, command, alt/option and the arrow keys. Haven't found a way to do any of this yet.
    Anyone?

    Hi Josh,
    Numbers is organized differently than Excel, and the navigation tools are different too. Many of us miss our particular favorites from spreadsheets past, but this is Numbers, not a clone. The biggest adjustment is to go from huge monolithic sheet-tables containing virtual sub-tables to a simple blank sheet with small tables, sometimes many per sheet. Navigating is no big deal in these small tables and neither is getting from one small table to another, using the Sheets pane.
    Selecting a particular Table is as easy as clicking on the table's name in the Sheets pane. Selecting a particular row, or column, or ranges of rows or columns is done by clicking on the table's row and column labels, left side and top side once a cell is selected in the table.
    Numbers is weak at handling large Tables and documents that are large overall. We know this and many of us still prefer it to the alternative when the tool fits the task.
    Jerry

  • Simple JTable / Select Row example?

    Hi - I'm having a really hard time wrapping my brain around JTables and their events. Can anybody give me just a real simple example of how to get the value of whatever cell (row, preferrably) by clicking on that cell / row?

    Hey there,
    im currently doing Jtables within a system i am coding too so thought i would help ya out!
    1. You can recognise if a row is selected within your table by using a possible two methods: example of how this can be implemented:
    //This method used for only one row at a time being selected
    int selectedRow = table.getSelectedRow(); (table being the name of your JTable obviously)
                        if (selectedRow == -1) {//When there is no selected row show error message
                             JOptionPane.showMessageDialog(null, "Must select an employee from the table", "Error Message",
                                                      JOptionPane.ERROR_MESSAGE);
                        else {
                        //DO SOMETHING                    }
                   }2. Or you could use the public int [ ] getSelectedRows() method of recognising selected JTable rows: example of how u might implement this, this returns an array of interger values when 1 or more rows are selected:
    int [ ] rowselected = table.getSelectedRows();
    //In order to go through each selected row and do something with it a loop is obviously needed like:
    for (int i = 0; i < rowselected.length; i++) {
                        String empName = (String)(table.getValueAt(rowselected,0));
                        System.out.println(empName);
    Hope this helps ;-)

  • JTable, select row on right mouse click

    Hi,
    If I right click on a jTable row in my application, the row I click on does not get selected.
    How can I modify the mouse listener attached to the jtable to deal with this?
    jtable.addMouseListener( { e->
    if (e.isPopupTrigger())
        swing.popupMenu(menuItems).show(e.getComponent(), e.getX(), e.getY());
    } as java.awt.event.MouseListener)Thanks!

    Problem solved!
    jtable.addMouseListener( { e->
    if (e.isPopupTrigger()){
        int row = jtable.rowAtPoint( e.getPoint() );
        jtable.changeSelection( row, 0, false, false );
        swing.popupMenu(menuItems).show(e.getComponent(), e.getX(), e.getY());
    } as java.awt.event.MouseListener)

  • Selecting rows as columns

    Hi,
    I've got a challenge. I need to select row data as columns.
    Suppose, I have this:
    CREATE TABLE master
      id NUMBER,
      name VARCHAR2(50),
      CONSTRAINT pk_master PRIMARY KEY(id) 
    CREATE TABLE detail
      id NUMBER,
      master_id,
      type VARCHAR2(10),
      value NUMBER,
      CONSTRAINT pk_detail PRIMARY KEY(id),
      CONSTRAINT fk_master FOREIGN KEY(master_id)
           REFERENCES master(id),
      CONSTRAINT c_type CHECK (type IN ('apple','orange'))
    );Now, suppose master and detail holds the following data:
    Master:
    ID  NAME
    1   Jill
    2   Jack
    Detail:
    ID  MASTER_ID TYPE      VALUE
    1   1         apple     120
    2   1         orange    230
    3   2         apple     10Here comes the challenge: what do I have to put in a selectstatement, to get this result:
    NAME    APPLE    ORANGE
    Jill    120      230
    Jack    10I know what types there are up front (only apple and orrange), so the query may use that knowledge.
    Bonus guru points however to the one who can make a generic query that can convert the type rows into columns generically, regardless of what and how many types there are.

    scott@ORA92> -- test data:
    scott@ORA92> SELECT * FROM master
      2  /
            ID NAME
             1 Jill
             2 Jack
    scott@ORA92> SELECT * FROM detail
      2  /
            ID  MASTER_ID TYPE            VALUE
             1          1 apple             120
             2          1 orange            230
             3          2 apple              10
    scott@ORA92> -- PL/SQL for any number of values of type (apple, orange, etc.):
    scott@ORA92> VARIABLE g_ref REFCURSOR
    scott@ORA92> DECLARE
      2    v_sql VARCHAR2(32767);
      3  BEGIN
      4    v_sql := 'SELECT master.name';
      5    FOR rec IN (SELECT DISTINCT type FROM detail) LOOP
      6        v_sql := v_sql
      7        || ',SUM(DECODE(type,''' || rec.type || ''',value)) ' || rec.type;
      8    END LOOP;
      9    v_sql := v_sql
    10    || ' FROM   master, detail'
    11    || ' WHERE  master.id = detail.master_id'
    12    || ' GROUP  BY master.name';
    13    OPEN :g_ref FOR v_sql;
    14  END;
    15  /
    PL/SQL procedure successfully completed.
    scott@ORA92> PRINT g_ref
    NAME                                                    APPLE     ORANGE
    Jack                                                       10
    Jill                                                      120        230
    scott@ORA92>

  • Summing Selected Rows in Column Depending on Value in Another Column

    I'd like to sum only the values in selected rows in a given column depending on the value of another column in the same row. For example, suppose I have a table (please disregard the underscores, needed for correct alignment):
    ___A____B____C___D
    1__5___10___15___0
    2_20___25___30___1
    3_35___40___45___1
    4_50___55___60___0
    5__sum(D=1)
    In cell B5, I'd like to compute the sum of only rows in column B for which the value of the corresponding column D is 1. In this case B5 would be 65.
    How can I do this using functions? Is it possible to do it for a variable range of rows without specifying each row individually?
    Thanks,
    Dave

    You should place your formula to other collumn then calculated ones or in another table. You will be able to calculate whole collumns with: =SUMIF(D;“=1”;B)
    Formula for your example is: =SUMIF(D1:D4;“=1”;B1:B4)
    VB

  • Make Select rows and columns as read only in Table Control

    Hi All,
    I would like to know how to make certain cells in a Table Control as display only.
    Table control should look like-(Those in bold are read only or in display mode)
    <b>Name1            Idno1 </b>         Address1
    <b>Name2            Idno2</b>          Address2
    <b>Name3            Idno3  </b>        Address3
    <b>Name4            Idno4</b>          Address4
    (Blank row to enter name idno and address)
    (Blank row to enter name idno and address)
    (Blank row to enter name idno and address)
    My table control should display all the above fields the way it is above of which first two colums and 4 rows should be read only,and the rest of the empty rows in the TC should be in change mode.i.e it must have provision to add new rows but not change the first two columns of existing rows.
    In short I am looking at solution to hide particular no of rows and columns and <b>not the entire column.</b>

    In the PBO of the table control loop. just write these statements
    NAME and IDNO considering the fields on the screen.
    and WA_TAB is the table work area being passed to the table control to display the rows.
    if not WA_TAB-NAME is initial and not WA_TAB-IDNO is initial.
    loop at screen.
    if screen-name = 'NAME' or
       screen-name = 'IDNO'.
    screen-input = <b>0</b>.
    modify screen.
    endif.
    endloop.
    endif.
    which means that the fields are disabled only if NAME and IDNO are not initial.
    Regards
    - Gopi

  • How to save data from JTable multiple rows and columns

    Hi Y_Not thanks for your help before...
    But what should I do if I want to get/save many data from many column and rows??

    i don't quite understand your (repeated) question. what is the problem with "multiple rows and columns". Y_NOT and i have shown you ways to access them.
    all you need are 2 loops: one around your number of rows and one around the number of columns or vice versa depending in which order you want to save things:
    for (int col = 0; col < data.size(); col++) {
        for (int row = 0 ; row < data[col].size(); row++) {
            // save your data
            saveData(data[col].getElementAt(row));
            // or use yourtable.getValueAt(row, col);
    }this is not a problem of Swing/Java but of simple algorithm...
    thomas

  • Selecting rows as columns in sql table

    i have sql table like 
    currcode    currdesc                  mth    yr        rate
    SGD          SINGAPORE DOLLAR    01    2013      .02
    SGD          SINGAPORE DOLLAR    09    2013      .02  (suppose have rates only for jan and sept )
    RMB          CHINESE RENMINBI     01    2013      .206
    RMB          CHINESE RENMINBI     02    2013      .207
    For each currency rates for 12 months for every year
    i want to show like (user will select the year)
    currcode    currdesc                      Jan       Feb     Mar    Apr     May    Jun    Jul    Aug    
    Sept   oct   nov  Dec
    SGD          SINGAPORE DOLLAR     .02                                                    
                                .02
    RMB          CHINESE RENMINBI      .206      .207
    h2007

    you can use either of the below
    1. Using PIVOT operator
    SELECT currcode,
    currdesc,
    Yr,
    [01] AS Jan,
    [02] AS Feb,
    [03] AS Mar,
    [11] AS Nov,
    [12] AS Dec
    FROM Table t
    PIVOT (MAX(rate) FOR mth IN ([01],[02],[03],[04],..,[11],[12]))p
    2. using classical cross tab logic
    SELECT currcode,
    currdesc,
    yr,
    MAX(CASE WHEN mth = '01' THEN rate END) AS Jan,
    MAX(CASE WHEN mth = '02' THEN rate END) AS Feb,
    MAX(CASE WHEN mth = '03' THEN rate END) AS Mar,
    MAX(CASE WHEN mth = '11' THEN rate END) AS Nov,
    MAX(CASE WHEN mth = '12' THEN rate END) AS Dec
    FROM table
    GROUP BY currcode,currdesc,yr
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs
    Thank u for helping. Your 2nd solution working great. But using Pivot table giving me 2 rows,
    RMB CHINESE RENMINBI
    2013 NULL
    NULL NULL
    0.206  NULL  NULL
    RMB CHINESE RENMINBI
    2013 NULL
    NULL NULL
    NULL  NULL
      0.207
    h2007
    Do you've any additional columns you've not shown in the post above?
    to change NULLs to 0 use this
    SELECT currcode,
    currdesc,
    yr,
    MAX(CASE WHEN mth = '01' THEN rate ELSE 0.00 END) AS Jan,
    MAX(CASE WHEN mth = '02' THEN rate ELSE 0.00 END) AS Feb,
    MAX(CASE WHEN mth = '03' THEN rate ELSE 0.00 END) AS Mar,
    MAX(CASE WHEN mth = '11' THEN rate ELSE 0.00 END) AS Nov,
    MAX(CASE WHEN mth = '12' THEN rate ELSE 0.00 END) AS Dec
    FROM table
    GROUP BY currcode,currdesc,yr
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • JTable select row by double click, single click

    Hi all,
    I would like to double click on the row of the JTable and pop up a window for adding stuff, a single click for selecting the row and then in the menu bar I can choose to etither add, change or delete stuff. I try to use the ListSelectionModel but does not seems to distinguish between double or single click.
    Any idea, doc, samples?
    or I should not use ListselectionModel at all?
    thanks
    andrew

    Hi. I used an inner class. By using MouseAdapter u dont have to implement all methods in the interface..
    MouseListener mouseListener = new MouseAdapter()
    public void mouseClicked(MouseEvent e)
    if(SwingUtilities.isLeftMouseButton(e))// if left mouse button
    if (e.getClickCount() == 2) // if doubleclick
    //do something
    U also need to add mouselistener to the table:
    table.addMouseListener(mouseListener);
    As I said, this is how I did it.. There are probably alot of ways to solve this, as usual :). Hope it helps

Maybe you are looking for

  • How do I install software w/out change to graphic / video settings

    Installing software changes ALL my graphic and video settings, screwing up how I view video, my photo viewing / editing capabilities, and rendering jpeg files in MS Word documents unavailable (they are visible on the monitor but won't print out, can'

  • Acrobat 9.1 standard loupe tool

    I have a user whose loupe tool is misbehaving.  She chooses the loupe tool, and when she clicks on her document, it creates the blue box but never pops up the loupe dialog box with the scroller.  Is this a config I am missing somewhere? Thanks!

  • Basic Trouble Shooting Ideas

    I just wanted to start a list to help many people out with common problems that can be fixed easily. - repair permissions. - reset PRAM and NVRAM (see link below) http://docs.info.apple.com/article.html?artnum=2238 - check the filesystem. - create a

  • How to find my windows office 2007 product key?

    Well,i think it can bring you some help: ''URL removed by a moderator - eh''

  • Photoshop or I Photo for Organizing

    I am new to MAc and cannot deal with I Photo at all. I bought Photoshop but I am not sure that is user friendly either when it comes to organizing Pictures. I also do not know how to copy my library from I photo into Photoshop. Does anybody have inpu