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
Similar Messages
-
Hi,
How can i convert rows to column in sql
I have table with the two columns child_table_name and parent_table_name as below. How can convert the below table to the expected output. show all the child and corresponding parent_table in one row. Please help to write sql
Child_table_Name Parent_Table_name
abc bbb
abc aaa
def ccc
def ttt
Expected Output
abc bbb aaa
def ccc ttt
Thanks,
ChHi,
That's called a Pivot, and here's one way to do it:
WITH got_r_num AS
SELECT child_table_name
, parent_table_name
, ROW_NUMBER () OVER ( PARTITION BY child_table_name
ORDER BY parent_table_name
) AS r_num
FROM table_x
SELECT *
FROM got_r_num
PIVOT ( MAX (parent_table_name)
FOR r_num IN ( 1 AS parent_1
, 2 AS parent_2
, 3 AS parent_3
The forum FAQ has a page devoted to pivots:
https://forums.oracle.com/message/9362005#9362005
The query above can show up to 3 parents per child. If you know you'll never have more than 2 (as in your message) then you don't need the line that defines parent_3. On the other hand, if you might need more than 3 parents, you can add as many more as you need.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
Point out where the statement above is getting the wrong results, and explain, using specific examples, how you get the right results from the given data in those places. Remember that there is no built-in order to the rows in a table, so if your explanationuses words like "first" or "latest", define what they mean in terms of the data in your table.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
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 -
How to convert rows to columns of a table?
I want to convert rows to columns of a table..
Query in SQL??965373 wrote:
I want to convert rows to columns of a table..
Query in SQL??PIVOT by Frank Help for a query to add columns
PIVOT by TomK http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:766825833740 -
How to get selected row data of an ADF table in HashMap?
Hi,
Can anyone please tell me how to selected row data of an ADF table in HashMap like :
Object obj = pageTable.getSelectedRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)obj;
Now in above code I want the convert rowData in HashMap.
Can anyone please tell me how to do that? Its urgent.
Thanks,
VikVik,
No need to ask the same question 3 times...
In [url http://forums.oracle.com/forums/message.jspa?messageID=4590586]this post, Nick showed you how to get the Row.
If it were so urgent, you could have done a little reading of the javadocs to come up with code like this (not tested, up to you to do that)
HashMap m = new HashMap();
Row r = get it like Nick showed you to;
Object values[]=r.getAttributeValues();
String names[]=r.getAttributeNames();
for (int i=0; i<r.getAttributeCount(); i++)
m.put(names, values[i]); -
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 SaxenaIs 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 -
How to convert rows to columns in sql server 2008
How to convert rows to columns in sql server 2008 using the GROUP BY function? (only one query allowed)
Lookup the Pivot transformation. From BOL:
The Pivot transformation makes a normalized data set into a less normalized
but more compact version by pivoting the input data on a column value. For
example, a normalized Orders data set that lists customer name, product, and quantity purchased typically has multiple rows for any customer who purchased multiple products, with each row for that customer showing order
details for a different product. By pivoting the data set on the product column, the Pivot transformation can output a data set with a
single row per customer. That single row lists all the purchases by the customer, with the product names shown as column names, and the quantity shown as a value in the product column. Because not every customer purchases every product, many columns may contain
null values.
When a dataset is pivoted, input columns perform different roles in the pivoting process. A column can participate in the following ways:
The column is passed through unchanged to the output. Because many input rows
can result only in one output row, the transformation copies only the first
input value for the column.
The column acts as the key or part of the key that identifies a set of
records.
The column defines the pivot. The values in this column are associated with
columns in the pivoted dataset.
The column contains values that are placed in the columns that the pivot
creates.
Paul -
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 -
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 -
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> -
Get Row and Column Id of table..
Hi All,
I have a table with number of columns having Link UI element. Can anyone have idea that how will I get a row ID/ Column ID, if I select any Link2Action UI element on any Row column.
Thanks,
Sanket SethiHi,
I guess you want to read the column (ie text value) of Link to Action UI. Check this link for reference: [Link to Action in Table|http://www.zbalai.com/_abap/content/190_Web_Dynpro_Table_Link/web_dynpro_table_link.html]
Hope this helps u.,
Thanks & Regards,
Kiran. -
Dynamic Table - Add rows and columns in same table
Hi there,
I wonder if someone could help please? I'm trying to create and table where a user can add both rows and columns (preferably with separate buttons) but am having trouble trying to figure out how to do this. Is it possible? If so how? I'm not familar with script but have found examples of seprate tables where you can add a row and then another table where you can add columns and essentailly want to merge the two but cannot make it work.
Any help much appreciated!
Thanks,
KenIt is great example....you can learn the concepts there and apply....however you may have to think twice before you implement column adding dynamically....because the technique here is make copy of what we already have and reproduce it as a new item and this technique works great for rows as they all have every thing in common. But when it comes to columns it may have unique visible identity as column head and displaying repeatedly the same column head may not look good. Of-Course you can do few extra lines of code and change the column appearance based on users input each time. Situations where users need to add additional column is very unlikely (sure your requirement might be an exception).
Key in allowing adding/removing instances is managing design mode settings under Object>>Binding>>....and select the checkbox "Repeat <subform/row/...> for Each Data Item" and then set Min, Max and Initial count values.
Also you need to club your effots by using simple scipt with button clicks....
for the example refered in URL you posted following is what I did to make the first table allow Adding/Removing Rows....
1. Opened the form in LC designer.
2. Add two buttons AddRow & RemoveRow right next to RemoveColumn
3. For AddRow I used following JS code....
Table1._Row1.addInstance(1);//that means any time this button is clicked a new instance of Row1 is added use _Row2 or Row3 based on your needs
var fVersion = new Number(xfa.host.version); // this will be a floating point number like "7.05"
if (fVersion < 8.0) // do this for Acrobat versions earlier than 8.0
// make sure that the new instance is properly rendered
xfa.layout.relayout();
4. For RemoveRow I used following JS code....
Table1._Row1.removeInstance(1);//Syntax is...<objectReference>.removeInstance(<index of the repeating object that needs to be removed>); //in this case since we used 1 alwasys second object from top gets deleted.
var fVersion = new Number(xfa.host.version); // this will be a floating point number like "7.05"
if (fVersion < 8.0) // do this for Acrobat versions earlier than 8.0
// make sure that the new instance is properly rendered
xfa.layout.relayout();
5. Now time to update settings at Object>>Binding tab and set "Repeat......" and also set Min, Max and Initial count as explained above.
Those settings needs to be updated for Row1 (or your choice of row) of the table
6. Set the Height to Expand of the Subform, where the table is housed.... this is done under Layout pallet
7. Save the PDF as dynamic template and verify the results...
If you still run into issues I can send you copy that works on my machine, but you need send me an email at n_varma(AT)lycos.com
Good luck, -
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,
DaveYou 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 -
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,
MartinAre 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 :)
Maybe you are looking for
-
So it seems that a LOT of people have been having this problem. (Being...) Credit card being declined. I have had 2 different indicators from iTunes that something I have done is wrong. 1. iTunes does not accept my security code. -This could be
-
Fm to get current + next 3 fiscal months name
hi all, In my alv report , i need to populate the stock of current fiscal month plus stock for succeeding 3 months.Using fm 'GET_CURRENT_YEAR' i am getting current month details with input sydatum and company code. But how to get next 3 fiscal months
-
Help with partial image loss from Viewer to Canvas
Hi--I'm brand new to FCP and would really appreciate any help with my problem. I'm creating 2 second video clips composed of four still images (15 frames...or 500ms each) laid back to back, then rendered. Very simple, I know. The individual images ar
-
ILearning 6.0 in windows.
How can I install iLearning 6.0 in windows 7 64 bit? Is that possible? Because only windows 32 bit is available with in the edelivery.oracle.com download section.
-
Full Page view for PDF and TIF attachments
Hello Can any one help please, I upgraded my software for my device and no longer have the options for "full page view" to see detailed PDF and TIF attachments. This is a big problem for me please help. Thanks in advance. Message Edited by pltcare on