Reg: col to rows-
Hi Experts,
I've a scenario like the below -
Input data:
STORE
QUARTER1
QUARTER2
QUARTER3
QUARTER4
shop1
100
300
500
700
shop2
250
450
650
850
Expected Output:
Quarter
Shop-1
Shop-2
1
100
250
2
300
450
3
500
650
4
700
850
I guess (but not sure) - will UNPIVOT function help in achieving this.
I'm refering this - http://www.oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php#unpivot but not able to figure out its exact usage.
Could you please help me with this?
Help much appreciated.
-- Ranit
(Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production)
ranitB wrote:
Thanks a lot Ramin. The output got is as expected.
Could you please explain the working of your query?
Just formatted your query:
select * from (
select store, q, val from t
UNPIVOT(
val for q in(q1, q2, q3, q4)
PIVOT( max(val) for store in('shop1' sh1, 'shop2' sh2)
first we are unpivoting your data :
select store, q, val from t
UNPIVOT(
val for q in(q1, q2, q3, q4)
val is the virtual column name for unpivoted data (you can gave any name)
shop1
Q1
100
shop1
Q2
300
shop1
Q3
500
shop1
Q4
700
shop2
Q1
250
shop2
Q2
450
shop2
Q3
650
shop2
Q4
850
Then we need pivot data for column store and for this in inline view we pivot data :
select * from (
select store, q, val from t
UNPIVOT( val for q in(q1, q2, q3, q4)
PIVOT( max(val) for store in('shop1' sh1, 'shop2' sh2));
Ramin Hashimzade
Similar Messages
-
Has anyone been able to create a HtmlDataTable with dynamic col and rows?
Has anyone been able to create a HtmlDataTable with dynamic col and rows?
If so please explain. I am successfully able to dynamically add columns using the getChildren method of the htmldatatable object
BUT for each new column created no data is displayed.
I am only able to display data for columns originally created when i clicked and dragged the dataTable icon from the pallette in netbeans visual web kit.
Any help on this is greatly appreciated. I have been searching the web and these forums for around 8 hours and no one seems to have a working example of this. Lots of similar posts asking how to do it though :(
Thanks in advance.This might be useful: http://balusc.xs4all.nl/srv/dev-jep-dat.html
-
Col-to-Rows needed for MINUS later
Query 1
SCOTT@orcl>SELECT CUST_NAME, DOD_PROD_CODE, to_char(DOD_DOH_NO,999999) DOD_DOH_no,
2 to_char(DOH_SO_REF_NO,999999) DOH_SO_REF_NO
3 FROM DELIVERY_ORDER_HEADER, DELIVERY_ORDER_DETAIL, CUSTOMER_MASTER
4 WHERE DOH_NO = DOD_DOH_NO
5 AND DOH_PARTY_CODE = CUST_CODE
6 AND DOH_SO_REF_NO = 13
7 ORDER BY 2;
CUST_N DOD_PROD_CODE DOD_DOH DOH_SO_
ENERGY P01033691.1 11 13
ENERGY P01033691.5 11 13
ENERGY P01033691.5 12 13
ENERGY P01033691.7 11 13
ENERGY P01033691.7 12 13
ENERGY P01033691.8 12 13
ENERGY P0140000014 11 13
ENERGY P01400012 11 13
8 rows selected.Query 2
SCOTT@orcl>SELECT CUST_NAME, SALEVD_PROD_CODE, SALEVH_DO_REF_NO,
2 to_char(SALEVH_SO_REF_NO,999999) SALEVH_SO_REF_NO
3 FROM SALES_INVOICE_HEADER, SALES_INVOICE_DETAIL,CUSTOMER_MASTER
4 WHERE SALEVH_NO = SALEVD_SALEVH_NO
5 AND SALEVH_PARTY_CODE = CUST_CODE
6 AND SALEVH_SO_REF_NO = 13
7 ORDER BY 2;
CUST_N SALEVD_PROD_COD SALEVH_DO_ SALEVH_
ENERGY P01033691.1 11,12 13
ENERGY P01033691.5 11,12 13
ENERGY P01033691.7 11,12 13
ENERGY P01033691.8 11,12 13
ENERGY P0140000014 11,12 13
ENERGY P01400012 11,12 13
6 rows selected.i want Query No.2 to be exactly returning the same number of rows, like Query No.1 - 8 Rows.
for example, in Query 1, there are 2 rows returned for product code P01033691.5 & P01033691.7,
whereas in Query 2 they are shown on single rows.
This is not the only case, the situaton may change where there can be more than 2 or just 1 values (in this case 11,12)
for SALEVH_DO_REF_NO Col. in Query 2.
i want to always break Col-to-Rows for Query 2,
based on the DOD_PROD_CODE & DOD_DOH_NO of Query 1 matching with SALEVD_PROD_CODE, SALEVH_DO_REF_NO of Query 2 .
so that it will become easier finally to use MINUS between both Queries like this;
Query 3
SELECT CUST_NAME, DOD_PROD_CODE, to_char(DOD_DOH_NO,999999) DOD_DOH_no,
to_char(DOH_SO_REF_NO,999999) DOH_SO_REF_NO
FROM DELIVERY_ORDER_HEADER, DELIVERY_ORDER_DETAIL, CUSTOMER_MASTER
WHERE DOH_NO = DOD_DOH_NO
AND DOH_PARTY_CODE = CUST_CODE
AND DOH_SO_REF_NO = 13
MINUS
SELECT CUST_NAME, SALEVD_PROD_CODE, SALEVH_DO_REF_NO,
to_char(SALEVH_SO_REF_NO,999999) SALEVH_SO_REF_NO
FROM SALES_INVOICE_HEADER, SALES_INVOICE_DETAIL,CUSTOMER_MASTER
WHERE SALEVH_NO = SALEVD_SALEVH_NO
AND SALEVH_PARTY_CODE = CUST_CODE
AND SALEVH_SO_REF_NO = 13as per the above data the Query3 should not return any rows, but lets say a row gets added to Query 1 result,
i mean a new DOD_DOH_NO for the same DOH_SO_REF_NO. a 9th row for example;
ENERGY P01400012 13 13
and theres is no Invoice done, then Query 3 should return just 1 row which is just the above 1, the 9th row.
any help will be highly appreciated. TYMr. Massimo,
Your Query MUST return rows and those should be the following 8 rows;
CUST_NAME SALEVD_PROD_COD SALEVH_ SALEVH_
ENERGY P01033691.1 11 13
ENERGY P01033691.5 11 13
ENERGY P01033691.7 11 13
ENERGY P01400012 11 13
ENERGY P0140000014 11 13
ENERGY P01033691.5 12 13
ENERGY P01033691.7 12 13
ENERGY P01033691.8 12 13
8 rows selected.
Your Latest Query returned no rows at all;
SCOTT@orcl>SELECT CUST_NAME, DOD_PROD_CODE, to_char(DOD_DOH_NO,999999) DOD_DOH_no,
2 to_char(DOH_SO_REF_NO,999999) DOH_SO_REF_NO
3 FROM DELIVERY_ORDER_HEADER doh, DELIVERY_ORDER_DETAIL dod, CUSTOMER_MASTER c
4 WHERE DOH_NO = DOD_DOH_NO
5 AND DOH_PARTY_CODE = CUST_CODE
6 AND 0 = (select count(0) FROM SALES_INVOICE_HEADER, SALES_INVOICE_DETAIL,CUSTOMER_MASTER c2
7 WHERE SALEVH_NO = SALEVD_SALEVH_NO
8 AND SALEVH_PARTY_CODE = CUST_CODE
9 AND SALEVH_SO_REF_NO = DOH_SO_REF_NO
10 AND c2.CUST_NAME=c.CUST_NAME
11 AND SALEVD_PROD_CODE = DOD_PROD_CODE
12 AND regexp_like(SALEVH_DO_REF_NO ,'(^|,)'||to_char(DOD_DOH_NO,999999)||'(,|$)')
13 AND to_char(SALEVH_SO_REF_NO,999999) = to_char(DOH_SO_REF_NO,999999))
14 AND 0 < (select count(0) FROM SALES_INVOICE_HEADER, SALES_INVOICE_DETAIL
15 WHERE SALEVH_NO = SALEVD_SALEVH_NO
16 AND SALEVH_SO_REF_NO = DOH_SO_REF_NO
17 AND regexp_like(SALEVH_DO_REF_NO ,'(^|,)'||to_char(DOD_DOH_NO,999999)||'(,|$)'));
no rows selectedi will rephrase and putting my case again. i am sure this time you;ll have better grasp on it.
These are the records for Items actually Delivered,columns are;
Customer Name = CUST_NAME
Item Code = DOD_PROD_CODE
Deliver Order No. = DOD_DOH_NO (NUMBER)
Sales Order Ref. No. = DOH_SO_REF_NO
SELECT CUST_NAME, DOD_PROD_CODE, to_char(DOD_DOH_NO,999999) DOD_DOH_no,
to_char(DOH_SO_REF_NO,999999) DOH_SO_REF_NO,DOD_QTY_DISPATCHED
FROM DELIVERY_ORDER_HEADER, DELIVERY_ORDER_DETAIL, CUSTOMER_MASTER
WHERE DOH_NO = DOD_DOH_NO
AND DOH_PARTY_CODE = CUST_CODE
ORDER BY 3;
CUST_NAME DOD_PROD_CODE DOD_DOH DOH_SO_ DOD_QTY_DISPATCHED
TOPAZ P01400034 9 14 4
TOPAZ P01025299.5 9 14 8
TOPAZ P01025299.7 9 14 15
TOPAZ P0140000010 9 14 2
TOPAZ P01025299.2 9 14 10
TOPAZ P01025299.9 9 14 10
TOPAZ P01025299.3 9 14 10
ENERGY P01033691.1 11 13 2
ENERGY P01033691.5 11 13 4
ENERGY P01033691.5 12 13 4
ENERGY P01033691.7 11 13 5
ENERGY P01033691.7 12 13 5
ENERGY P01033691.8 12 13 5
ENERGY P01400012 11 13 3
ENERGY P0140000014 11 13 10
ENERGY P01033691.7 13 13 2
ENERGY P01033691.8 13 13 5
17 rows selected.
Query No. 2
The following are the Invoice issued for the Items Delivered above.
Not all Invoices have been issued, still left, are for DOD_DOH_NO 9 & 13.
The columns are ;
Customer Name = CUST_NAME
Item Code = SALEVD_PROD_CODE
Invoice Deliver Order Ref.No. = SALEVH_DO_REF_NO (VARCHAR2)
Sales Order Ref. No. = SALEVH_SO_REF_NO
SELECT SUBSTR(CUST_NAME,9,6) CUST_NAME, SALEVD_PROD_CODE, SALEVH_DO_REF_NO,
to_char(SALEVH_SO_REF_NO,999999) SALEVH_SO_REF_NO
FROM SALES_INVOICE_HEADER, SALES_INVOICE_DETAIL,CUSTOMER_MASTER
WHERE SALEVH_NO = SALEVD_SALEVH_NO
AND SALEVH_PARTY_CODE = CUST_CODE;
CUST_N SALEVD_PROD_COD SALEVH_DO_ SALEVH_ SALEVD_QTY
ENERGY P01033691.1 11,12 13 2
ENERGY P01033691.5 11,12 13 8
ENERGY P01033691.7 11,12 13 10
ENERGY P01033691.8 11,12 13 5
ENERGY P01400012 11,12 13 3
ENERGY P0140000014 11,12 13 10
6 rows selected.
Note: SALEVH_DO_REF_NO is VARCHAR2 field, that i have used save DOD_DOH_NO (type NUMBER) values,
in comma separated manner, offering user to club more than 1 Delivery Orders on a single Invoice.
Therefore i want a query that will turn Query2 result to something like;
CUST_NAME SALEVD_PROD_COD SALEVH_ SALEVH_
ENERGY P01033691.1 11 13
ENERGY P01033691.5 11 13
ENERGY P01033691.7 11 13
ENERGY P01400012 11 13
ENERGY P0140000014 11 13
ENERGY P01033691.5 12 13
ENERGY P01033691.7 12 13
ENERGY P01033691.8 12 13
8 rows selected. -
Suppress COL and ROW based actual period and previous one
Hi!
Here is a problem I am trying to solve:
Lets say you have in COL a list of products and in ROW a list of client.
Most of the products bought by the client are the same month after month...
Most of the clients are the same month after month...
So I would like my COL to suppress depending on period N and period N-1 because my products hardly change. To add a new one, I will put the INSERT = Y in my expansion.
I would like my ROW to suppress depending on period N and period N-1 because in the long list of my clients, only some of them buy my products. To add new clients, I will put the INSERT = Y in my expansion.
I hope the definition of my problem above is good, here is how I try to solve it in my EVDRE;
PARAMETER EXPANSION 1 | EXPANSION 2
ExpandIn ROW | COL
Dimension Product | Client
MemberSet basmembers | basmembers
BeforeRange |
AfterRange |
Suppress [2009.JAN,2009.FEB ] | [2009.JAN,2009.FEB]
Insert y | y
It doesnt work!
When I have data in January, and I check February the expansion returns totaly empty!!
Thanks for your help
Nic
NB: I forgot to add that I am running SP3 v 5.0.502.03
Edited by: Nicolas Argente on Jul 16, 2008 4:22 PMFor your information, I also raised a ticket at SAP Support Portal from this problem. I will keep you updated with this problem.
Nic -
Reg:Arrangement of rows in UI table as our requirement....
Hi all,
In my Project I have an UI Table in which it is having 5 rows in that i have a column having Dropdown by keys and it will hold 5 possible values (Ex:Coverage type1,coverage type2.......coverage type5) and in which we will select two rows.
wenever we are pressing combine Button (Action) those two values will combine to geather and should come in one row i.e (After Pressing combine Coverage type1 & Coverage type2,Cverage type3.........coverage type5 in one Drop Down in one row).
iam able to do this the problem i have to solve is When ever iam combing two rows the combined two rows are coming at the last row but my wish is to get is:
Ex: If i Combine 1st row and 2 row those combined row should come at first.
if i Combine 2nd row and 1st row those combined row should come at Second.
if i combine 3rd row and 4th row those combined row should come at third.
like this it should hapeen so any one help me out in solving this issue.Ha Mahesh,
Option 1: After removing your old rows (which I guess you do) and adding your new row, you could do a sort
//You need to create a Comprator yourself implementing a Comparator Interface.
Comparator cmp = new MySorter();
wdContext.getNodeBlahBlah.sortElements(cmp)
Option 2: After removing your old rows you can add your row and at the position you like.
int index = 2;
IWDNodeElement nodeElement = wdContext.createElement();
wdContext.getNodeBlahBlah.addElement(index, nodeElement);
Something like that ...
Jeschael -
Oracle Traspostion of Col to Rows
Hi
I have A table after processing a file like
Building Person
B New
P AMit
B Old
P Raj
B Old
P akshay
B New
P Atul
Value B: Building
P: Person
there are Only Two Values for Building i.e. New,Old
I need Output as :
Building
Person
New
AMit
Old
Raj
Old
akshay
New
Atul
Please Suggest Query for it.
I am able to Make
Building
Person
New
null
null
AMit
Old
null
null
Raj
Old
null
null
akshay
New
null
null
Atul
by this following query
select
decode( Building, 'New', Person, null ) Building,
decode( Building, 'Old', Person, null ) Person
from my_table;
Can i implement this in Interface.Pl do not post duplicates - Column to Rows Convertion...or Transpose.
-
Reg : Passing multiple rows of table data to the RFC
Hi,
I am passing one row of data from webdynpro table to table of RFC.
How to pass multiple rows of data.
Please help me out.
Thanks
Rishahi
Person--->node(cardinality 1..n)
FirstName-->Attribute
LastName-->Attribute.
Person1-->RFC table node.(cardinality 1..n)
FName-->Attribute
LName-->Attribute
for(int i=0;i<wdContext.nodePerson().size();i++)
//Retrieving values from table
IPrivate<View>.IPersonElement element1=wdContext.nodePerson().createPersonElement();
String fname=element1.getFirstName();
String lname= element1.getLastName();
wdContext.nodePerson().addElement(element1);
//Inserting into table of RFC
IPrivate<View>.IPerson1Element element2=wdContext.nodePerson1().createPerson1Element();
element2.setFname(fname);
element2.setLname(lname);
wdContext.nodePerson1().addElement(element2);
Regards
sowmya. -
Reg : Table control row settings to change mode
Hi geeks.
I am working on a requirement where the table control has to be in display mode at the time of prepopulating(initial display).This works fine and could get all columns in display mode for which i used column properties of table control. I could select a row from the table control and created a button above the table control for copy of the row which is added to the last row of the TC. I could get this with out any issues. They want the added row to be in changed mode whereas the other rows selected previously should remain in the display mode. Can anybody help me out to solve.Timely help will be appreciated <removed by moderator>
Regards ,
Kumar.
Edited by: Vinod Kumar on Aug 2, 2011 9:21 AMThis thread will assist you.
[Table control with non editable rows;
Make use of some flag for identifying the new records that will be appended in itab on the press of the button.
Then in PBO,
loop at itab with control tc cursor tc-current_line.
module editnewrow.
endloop.
module editnewrow output.
if itab-flag = 'X'.
loop at screen.
screen-input = 1.
modify screen.
endloop.
itab-flag = ' '. (resetting back to non-editable state for consequent press of the button)
modify itab index tc_4000-current_line.
endif.
endmodule. -
How Can i convert the Columns In to Row in a oracle Select Query ?
If the data is like this...
CTRY DT WT
KSA 20-MAR-09 200
KSA 02-MAY-09 20
UAE 22-JAN-09 20
UAE 02-JAN-09 30
UAE 22-MAY-09 20
we can convrt the rows dt into columns like this (We have done month wise ..We can chage the query to do
data wise)
SELECT CTRY,
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'JAN-2011' THEN SUM(WT) ELSE '' END AS 'JAN-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'FEB-2011' THEN SUM(WT) ELSE '' END AS 'FEB-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'MAR-2011' THEN SUM(WT) ELSE '' END AS 'MAR-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'APR-2011' THEN SUM(WT) ELSE '' END AS 'APR-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'MAY-2011' THEN SUM(WT) ELSE '' END AS 'MAY-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'JUN-2011' THEN SUM(WT) ELSE '' END AS 'JUN-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'JUL-2011' THEN SUM(WT) ELSE '' END AS 'JUL-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'AUG-2011' THEN SUM(WT) ELSE '' END AS 'AUG-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'SEP-2011' THEN SUM(WT) ELSE '' END AS 'SEP-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'OCT-2011' THEN SUM(WT) ELSE '' END AS 'OCT-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'NOV-2011' THEN SUM(WT) ELSE '' END AS 'NOV-2011',
CASE TO_CHAR(DT,'MON-YYYY') WHEN 'DEC-2011' THEN SUM(WT) ELSE '' END AS 'DEC-2011'
FROM TAB1
GROUP BY CTRY,TO_CHAR(DT,'MON-YYYY'); -
Reg: Order of row fetched -
Hi Experts,
Scenario -
A file has data in sorted order and it is inserted into Oracle table by SQL Loader (Direct-path load enabled).
If the table is queried (without any ORDER BY clause), is there a guarantee that the ordering will be same as in the text file?
I'm quite sure it's "NO" , and has been discussed several times that - without any explicit ORDER BY clause there's no guarantee that rows will be fetched in order.
But is there any way to demonstrate this?
I tried the below workout... (but rows were always fetched in the inserted order):
CREATE TABLE table_x
AS
SELECT /*+ APPEND */ LEVEL lvl
FROM dual
CONNECT BY LEVEL <= 10
ORDER BY 1 desc;
DECLARE
CURSOR cur_x
IS
SELECT lvl FROM table_x;
BEGIN
FOR j IN 1..100
LOOP
FOR i IN cur_x
LOOP
Dbms_Output.put_line(i.lvl);
END LOOP;
Dbms_Output.put_line('-------LOOP '||j||'------------');
END LOOP;
END;
Help much appreciated!
Thanks and Regards
-- Ranitone example could be:
drop table t;
create table t
as
select rownum id
from dual
connect by level <= 1000000;
select /*+ parallel(8) */ * from t where rownum < 30;
ID
262801
262802
262803
262804
262805
262806
262807
262808
262809
262810
262811
262812
262813
262814
262815
262816
262817
262818
262819
262820
262821
262822
262823
262824
262825
262826
262827
262828
262829
So parallel access does change the order.
I think Tom Kyte mentioned the importance of an explicit order by rather frequently (a good example is http://tkyte.blogspot.de/2005/08/order-in-court.html) - almost as frequently as he mentioned the importance of bind variables... -
Theme 20: Cannot create a page with 2 regions in one and 2 reg. in next row
Hello,
I have a page (template Two Level Tabs) with 4 regions in an application with theme 20.
Region 1
======
Display Point: Page Template Body (2. items below region content)
Column: 1
Region 2
======
Display Point: Page Template Body (2. items below region content)
Column: 2
Region 3
======
Display Point: Page Template Body (3. items above region content)
Column: 1
Region 4
======
Display Point: Page Template Body (3. items above region content)
Column: 2
So I should get a layout like this:
Region1 | Region2
Region3 | Region4
But I get a layout like this:
Region1 | Region2 | Region3 | Region4
Is this a but in Theme 20? With an other theme it works fine.
Regards,
MarkIts all empty html-regions. I create this page because I have the problem with a complex page, but so its easier to find the failure.
The sequences are 10 (region test1), 20 (region test2), 30 (region new row 1), 40 (region new row 2), look here:
Regions
Display Point: Region Position 02
10 test1 HTML
20 test2 HTML (Column 2)
Display Point: Region Position 04
30 new row 1 HTML
40 new row 2 HTML (Column 2) -
How to change colors of table col and row header?
Could I change table header colors when run vi ? Is such a thing possible?
ex: Header words color from black changed to green in column 2 of table.cloud a écrit:
...But I mean is "How to change header words color" not changed cell words color.
tst gave you the answer ! A header cell is just a cell with a -1 value as index...
Chilly Charly (aka CC)
E-List Master - Kudos glutton - Press the yellow button on the left... -
Multiple selection of row in a jtable
Hello All,
I am working with this jtable 'tblSearch'. The application requirement is that the user should have the ability to select multiple rows using the control key. I am using the bold part of the code to color the selected row light gray. Can you someone help me to select multiple rows by holding the control key down.
public void PopulateAS400(){
cmbView.hidePopup();
setCursor(hourglassCursor);
int scrPos = scpSearch.getHorizontalScrollBar().getValue();
oapprovalSQL = SQLFactory.createOrderApprovalSql();
Vector FreightList = oapprovalSQL.getData(getAs400SearchString(), getOrderby(), AS400, AS400Overide.length, searchItems, rdoMatchAny.isSelected());
columnNames = (Vector)FreightList.get(1);
data = (Vector)FreightList.get(0);
model = new DefaultTableModel(data,columnNames) {
public Object getValueAt(int row, int col) {
return super.getValueAt(row,col);
public boolean isCellEditable(int row, int col) {
if (row == 0){
getTblSearch().setColumnSelectionAllowed(true);
return true;
getTblSearch().setColumnSelectionAllowed(false);
return false;
public Class getColumnClass(int c) {
if(c == 5 || c == 9){
return BigDecimal.class;
}else{
return String.class;
JTable tmp = new JTable(model)
private final KeyStroke tabKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
private final KeyStroke shiftTabKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB,KeyEvent.SHIFT_DOWN_MASK);
public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend)
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if(currentEvent instanceof KeyEvent)
KeyEvent ke = (KeyEvent)currentEvent;
if(ke.getSource()!=this)
return;
if (KeyStroke.getKeyStrokeForEvent(ke).equals(tabKeyStroke))
if (rowIndex > 0)
rowIndex = 0;
columnIndex = 0;
toggle = false;
extend = false;
getTblSearch().setColumnSelectionAllowed(true);
else if (KeyStroke.getKeyStrokeForEvent(ke).equals(shiftTabKeyStroke))
if (rowIndex > 0)
rowIndex = 0;
columnIndex = getTblSearch().getColumnCount()-1;
toggle = false;
extend = false;
getTblSearch().setColumnSelectionAllowed(true);
else if (columnIndex == getTblSearch().getColumnCount()-1)
rowIndex = 0;
columnIndex = getTblSearch().getColumnCount()-1;
toggle = false;
extend = false;
getTblSearch().setColumnSelectionAllowed(true);
super.changeSelection(rowIndex, columnIndex, toggle, extend);
public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColumnIndex)
Component c = super.prepareRenderer(renderer, rowIndex, vColumnIndex);
if ((vColumnIndex == 7) && (rowIndex > 0))
if ((model.getValueAt(rowIndex,7) != null) && (model.getValueAt(rowIndex,7).toString().equalsIgnoreCase("NMI")))
c.setBackground(Color.red);
else if ((model.getValueAt(rowIndex,7) != null) && (model.getValueAt(rowIndex,7).toString().equalsIgnoreCase("NMI ANSWERED")))
c.setBackground(Color.green);
else
c.setBackground(Color.white);
else
c.setBackground(Color.white);
**if (isRowSelected(rowIndex) && (rowIndex > 0)){**
**((JComponent)c).setBackground(Color.LIGHT_GRAY);**
if (rowIndex == 0 && isCellSelected(rowIndex, vColumnIndex)) {
c.setBackground(lightBlue);
return c;
setTblSearch(tmp);
getTblSearch().setAutoscrolls(true);
getTblSearch().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTblSearch().setAutoCreateColumnsFromModel(false);
getTblSearch().setColumnSelectionAllowed(false);
getTblSearch().setRowSelectionAllowed(true);
getTblSearch().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JTableHeader header8 = getTblSearch().getTableHeader();
ColumnHeaderListener colH8 = new ColumnHeaderListener();
colH8.setCallFrom("OrderApproval");
colH8.setOapproval(this);
header8.addMouseListener(colH8);
header8.setReorderingAllowed(false);
header8.setResizingAllowed(false);
getTblSearch().getColumn("Co #").setCellEditor(asCompCell);
getTblSearch().getColumn("Reg").setCellEditor(asRegCell);
getTblSearch().getColumn("Rep #").setCellEditor(asRepCell);
packColumns(getTblSearch(), 1);
getTblSearch().getColumnModel().getColumn(6).setPreferredWidth(240);
for(int i=0; i<searchEntries8.length; i++) {
getTblSearch().setValueAt(searchEntries8,0,i);
((GenericTextEditor)getTblSearch().getCellEditor(0,i)).setCellEditorValue(searchEntries8[i]);
scpSearch.add(new PopupContainer());
popupMenu = new JPopupMenu();
JMenuItem printFinalOrderMenu = new JMenuItem(PRINTFINALORDER_CMD);
printFinalOrderMenu.addActionListener(new PrintFinalOrderMenuListener());
popupMenu.add(printFinalOrderMenu);
MouseListener popupListener = new PopupListener();
getTblSearch().addMouseListener(popupListener);
scpSearch.setViewportView(getTblSearch());
scpSearch.getHorizontalScrollBar().setValue(scrPos);
setCursor(normalCursor);
Thank you all for your time n help.
Edited by: anjan_dev on Jan 29, 2008 2:14 PM
Edited by: anjan_dev on Jan 29, 2008 2:15 PM
Edited by: anjan_dev on Jan 29, 2008 2:16 PMThe issue is when I have one row already selected and then when I click on another row while holding the control key down. Our application needs an user to be able to select multiple rows at the same time.That is the default behaviour. I have no idea why it doesn't work for you.
Get rid of all your custom KeyEvent logic and try it again.
If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
http://homepage1.nifty.com/algafield/sscce.html
Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
http://forum.java.sun.com/help.jspa?sec=formatting -
Changing background color in JTable, only changes one row at a time...
I'm trying to change the color of rows when the 5th column meets certain criteria. I think I'm very close, but I've hit a wall.
What's happening is the row will change color as intended when the text in the 5th column is "KEY WORD", but when I type "KEY WORD" in a different column it will set the first row back to the regular colors. I can easily see why it's doing this, everytime something is changed it rerenders every cell, and the listener only checks the cell that was just changed if it met the "KEY WORD" condition, so it sets every cell (including the previous row that still meets the condition) to the normal colors. I can't come up with a good approach to changing the color for ALL rows that meet the condition. Any help would be appreciated.
In this part of the CellRenderer:
if (isSelected)
color = Color.red;
else
color = Color.blue;
if (hasFocus)
color = Color.yellow;
//row that meets special conditions
if(row == specRow && col == specCol)
color = color.white; I was thinking an approach would be to set them to their current color except for the one that meets special conditions, but the two problems with that are I can't figure out how to getColor() from the table, and I'm not sure how I would initially set the colors.
Here's the rest of the relevant code:
public void tableChanged(TableModelEvent e)
int firstRow = e.getFirstRow();
int lastRow = e.getLastRow();
int colIndex = e.getColumn();
if(colIndex == 4)
String value = (String)centerTable.getValueAt(firstRow, colIndex);
// check for our special selection criteria
if(value.equals("KEY WORD"))
for(int j = 0; j < centerTable.getColumnCount(); j++)
CellRenderer renderer =
(CellRenderer)centerTable.getCellRenderer(firstRow, j);
renderer.setSpecialSelection(firstRow, j);
import javax.swing.table.*;
import javax.swing.*;
import java.awt.Component;
import java.awt.Color;
public class CellRenderer extends DefaultTableCellRenderer
int specRow, specCol;
public CellRenderer()
specRow = -1;
specCol = -1;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int col)
setHorizontalAlignment(JLabel.CENTER);
Color color = Color.green;
if (isSelected)
color = Color.red;
else
color = Color.blue;
if (hasFocus)
color = Color.yellow;
if(row == specRow && col == specCol)
color = color.white;
//setForeground(color);
setBackground(color);
setText((String)value);
return this;
public void setSpecialSelection(int row, int col)
specRow = row;
specCol = col;
}If I'm still stuck and more of my code is needed, I'll put together a smaller program that will isolate the problem tomorrow.That worked perfectly for what I was trying to do, but I've run into another problem. I'd like to change the row height when the conditions are met. What I discovered is that this creates an infinite loop since the resizing triggers the renderer, which resizes the row again, etc,. What would be the proper way to do this?
Here's the modified code from the program given in the link. All I did was declare the table for the class, and modify the if so I could add the "table.setRowHeight(row, 30);" line.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
public class TableRowRenderingTip extends JPanel
JTable table;
public TableRowRenderingTip()
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data =
{"Buy", "IBM", new Integer(1000), new Double(80.5), Boolean.TRUE},
{"Sell", "Dell", new Integer(2000), new Double(6.25), Boolean.FALSE},
{"Short Sell", "Apple", new Integer(3000), new Double(7.35), Boolean.TRUE},
{"Buy", "MicroSoft", new Integer(4000), new Double(27.50), Boolean.FALSE},
{"Short Sell", "Cisco", new Integer(5000), new Double(20), Boolean.TRUE}
DefaultTableModel model = new DefaultTableModel(data, columnNames)
public Class getColumnClass(int column)
return getValueAt(0, column).getClass();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Alternating", createAlternating(model));
tabbedPane.addTab("Border", createBorder(model));
tabbedPane.addTab("Data", createData(model));
add( tabbedPane );
private JComponent createAlternating(DefaultTableModel model)
JTable table = new JTable( model )
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row, column);
// Alternate row color
if (!isRowSelected(row))
c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);
return c;
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.changeSelection(0, 0, false, false);
return new JScrollPane( table );
private JComponent createBorder(DefaultTableModel model)
JTable table = new JTable( model )
private Border outside = new MatteBorder(1, 0, 1, 0, Color.RED);
private Border inside = new EmptyBorder(0, 1, 0, 1);
private Border highlight = new CompoundBorder(outside, inside);
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row, column);
JComponent jc = (JComponent)c;
// Add a border to the selected row
if (isRowSelected(row))
jc.setBorder( highlight );
return c;
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.changeSelection(0, 0, false, false);
return new JScrollPane( table );
public JComponent createData(DefaultTableModel model)
table = new JTable( model )
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row, column);
// Color row based on a cell value
if (!isRowSelected(row))
c.setBackground(getBackground());
String type = (String)getModel().getValueAt(row, 0);
if ("Buy".equals(type)) {
table.setRowHeight(row, 30);
c.setBackground(Color.GREEN);
if ("Sell".equals(type)) c.setBackground(Color.YELLOW);
return c;
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.changeSelection(0, 0, false, false);
return new JScrollPane( table );
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
public static void createAndShowGUI()
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Table Row Rendering");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableRowRenderingTip() );
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}Edited by: scavok on Apr 26, 2010 6:43 PM -
Comboboxes are not set on the 1st time a row is clicked in the dataTable
I have somewhat the following setup:
I have a DataTable that is filled with a listof objects, a actionListener is handeled when a row is clicked.
Under the Table there are two ComboBoxes (lets call them Category and Item) that get their values from lists of Objects. The values of the list that backs the Item combo depend on the selected value of the Category combo.
Lets assume the values look like this:
CategoryA
---ItemA1
---ItemA2
CategoryB
---ItemB1
---ItemB2
Together with some textboxes, they should represent the values of the clicked row in the Table.
Now the problem:
When the comboboxes have a different value than the row that is beïng selected the values of the comboboxes and textboxes are not set correctly until the 3rd time the row is clicked.
It also doesn't go into the onClickMehod in the backing bean before the 3rd click. This is checked by a logger.
an example:
before clicking, the category combo is set to "CategoryB", the Item combo is set to "ItemB1" and the textboxes are empty. The row that is going to be clicked has as its category "CategoryA" and as its Item "ItemA1"
1st click:
the form still shows the values like they were before clicking, the log doesn't show that the method is triggered
2nd click:
the Item combo is set to "ItemA1", the category is still set to "CategoryB", the textBoxes are still empty. The log still doesn't show that the method is triggered
3rd click:
the Category combo is set to "CategoryA", the Item combo is set to "ItemA1", the textboxes also have their correct values.
the code is as followed:
JSP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head></head>
<body>
<f:view>
<h:form binding="#{backingBean.pageLoad}">
<h:dataTable binding="#{backingBean.dataTable}" columnClasses="COL1, COL1, COL2, COL2, COL3" value="#{backingBean.myObjects}" var="myObject" width="100%" headerClass="HEADING" rowClasses="ROW1, ROW2" rows="10">
<h:column>
<f:facet name="header">
<h:commandLink actionListener="#{backingBean.sortDataList}" styleClass="rowHeader">
<f:attribute name="sortField" value="getItemCategory" />
<h:outputText value="Category"/>
</h:commandLink>
</f:facet>
<h:commandLink shape="rect" styleClass="rowtext" value="#{myObject.item.itemCategory.description}" actionListener="#{backingBean.rowSelect}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink actionListener="#{backingBean.sortDataList}" styleClass="rowHeader">
<f:attribute name="sortField" value="getItem" />
<h:outputText value="Item"/>
</h:commandLink>
</f:facet>
<h:commandLink shape="rect" styleClass="rowtext" value="#{myObject.item.name}" actionListener="#{backingBean.rowSelect}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink actionListener="#{backingBean.sortDataList}" styleClass="rowHeader">
<f:attribute name="sortField" value="getDescription" />
<h:outputText value="Certification"/>
</h:commandLink>
</f:facet>
<h:commandLink shape="rect" styleClass="rowtext" value="#{myObject.description}" actionListener="#{myObject.description}"/>
</h:column>
<f:facet name="footer">
<h:panelGroup style="text-align:right">
<h:commandButton value="first" action="#{backingBean.pageFirst}" disabled="#{backingBean.dataTable.first == 0}" />
<h:commandButton value="prev" action="#{backingBean.pagePrevious}" disabled="#{backingBean.dataTable.first == 0}" />
<h:commandButton value="next" action="#{backingBean.pageNext}" disabled="#{backingBean.dataTable.first + backingBean.dataTable.rows >= backingBean.dataTable.rowCount}" />
<h:commandButton value="last" action="#{backingBean.pageLast}" disabled="#{backingBean.dataTable.first + backingBean.dataTable.rows >= backingBean.dataTable.rowCount}" />
<h:commandButton value="Append New" action="#{backingBean.ClearFields}" />
</h:panelGroup>
</f:facet>
</h:dataTable>
<h:inputHidden value="#{backingBean.sortField}"/>
<h:inputHidden value="#{backingBean.sortAscending}"/>
<h:inputHidden value="#{backingBean.myObjectId}"/>
<br />
<br />
<table style="border-collapse: collapse; width:100%" cellpadding="3" border="1">
<tr>
<td style="text-align:left; width:20%; background-image:url('images/lbar.gif'); font-family:Arial; font-size:smaller; font-weight:bold" colspan="3">Detail</td>
</tr>
<tr>
<td style="text-align:right; width:20%; background-color:#CCCCCC; font-family:Arial; font-size:smaller; font-weight:bold">Category </td>
<td style="width:80%; background-color:#CCCCCC;font-weight:bold">
<h:selectOneMenu value="#{backingBean.selectedCategory}" onchange="submit();" valueChangeListener="#{backingBean.CategoryChange}">
<f:selectItems value="#{backingBean.selectedCategories}"/>
</h:selectOneMenu>
</td>
</tr>
<tr>
<td style="text-align:right; width:20%; background-color:#CCCCCC; font-family:Arial; font-size:smaller; font-weight:bold">Item id </td>
<td style="width:80%; background-color:#CCCCCC;font-weight:bold">
<h:selectOneMenu value="#{backingBean.selectedItem}">
<f:selectItems value="#{backingBean.selectedItems}"/>
</h:selectOneMenu>
</td>
</tr>
<tr>
<td style="text-align:right; width:20%; background-color:#CCCCCC; font-family:Arial; font-size:smaller; font-weight:bold">Item Description </td>
<td style="width:80%; background-color:#CCCCCC;font-weight:bold"> <h:inputTextarea value="#{backingBean.description}" cols="60" rows="5"/></td>
</tr>
</table>
</h:form>
</f:view>
</body>
</html>the backing bean:
public class BackingBean{
-- Declaration of properties --
public void rowSelect(ActionEvent event) {
// Get selected MyData item to be edited.
logger.debug("Select row");
FacesContext context = FacesContext.getCurrentInstance();
try
if ((sortField != null) && (myObjects != null)) {
Collections.sort(myObjects, new DTOComparator(sortField, sortAscending));
dataTable.saveState(context);
catch(Exception e){
logger.error(e.getLocalizedMessage(), e);
context.addMessage("ERROR", new FacesMessage(e.toString()));}
logger.debug("Setting fields");
myObject = (MyObject) dataTable.getRowData();
description = myObject.getDescription();
itemCategory = myObject.getItem().getItemCategory();
item = myObject.getItem();
docDisabled = !certified;
selectedCategory = itemCategory.getId();
myObjectId = myObject.getId();
logger.debug("Fields set");
public void sortDataList(ActionEvent event) {
String sortFieldAttribute = getAttribute(event, "sortField");
// Get and set sort field and sort order.
if (sortField != null && sortField.equals(sortFieldAttribute)) {
sortAscending = !sortAscending;
} else {
sortField = sortFieldAttribute;
sortAscending = true;
// Sort results.
if (sortField != null) {
Collections.sort(myObjects, new DTOComparator(sortField, sortAscending));
public void CategoryChange(ValueChangeEvent vce){
try {
logger.debug("SelectedIndexChange: Category: {}",vce.getNewValue().toString());
selectedCategory = Integer.parseInt(vce.getNewValue().toString());
logger.debug("SelectedIndexChange: Category");
itemCategory = itemCategoryService.retrieveItemCategoryById(selectedCategory);
logger.debug("Showing Category: {}", itemCategory.getDescription());
} catch (Exception e) {
logger.error("Error occured: {}",e.toString());
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("ERROR", new FacesMessage(e.toString()));
public List<SelectItem> getSelectedItems() {
selectedItems = new ArrayList<SelectItem>();
try
logger.debug("selectedCategory: {}",selectedCategory);
if (itemCategory!=null)
logger.debug("Category Object: {}",itemCategory.getId());
items.clear();
items.addAll(itemCategoryService.retrieveItemCategoryById(selectedCategory).getItems());
logger.debug("items recieved: {}",items.size());
for (int count = 0; count < items.size(); count++) {
selectedItems.add(new SelectItem(items.get(count).getSeq(),items.get(count).getName()));
catch (Exception e){
logger.error("Error occured: {}",e.toString());
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("ERROR", new FacesMessage(e.toString()));
return selectedItems;
public List<SelectItem> getSelectedCategories() {
selectedCategories = new ArrayList<SelectItem>();
try{
for (int count = 0; count < itemCategories.size(); count++) {
if (itemCategories.get(count).getItems().size() != 0)
selectedCategories.add(new SelectItem(itemCategories.get(count).getId(),itemCategories.get(count).getDescription()));
if (selectedCategory == 0)
selectedCategory = itemCategories.get(0).getId();
catch (Exception e){
logger.error("Error occured: {}",e.toString());
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("ERROR", new FacesMessage(e.toString()));
return selectedCategories;
-- other getters and setters --
}I've already tried to use the action attribute instead of the actionlistener attribute, also tried to add immediate="true" to all fields and columns.
Did try to add onclick="submit();" to the rows.
What can be done to fix it??
ps: the enviroment is JSF + Spring + HibernateThe <h:messages/> tag is where the validation exception is shown, but no validation is used on the form, no other exeptions are sown.
the List<Categories> is filled at a setPageLoad method which is bound to the form by <h:form binding="#{backingBean.pageLoad}">.
The List<SelectedItem> of the categories box is filled in its getter and filled with the values of the List<Categories>
And both the List<SelectedItem> of the items box and the List<Item> are filled in the getter of the List<SelectedItem> of the items box
so instead of that i should rewrite it to something like this:
public BackingBean() {
selectedCategories = new List<SelectedItem>();
selectedItems = new List<SelectedItem>();
categories = CategoryService.retrieveCategories(); //gets all categories
items = ItemService.retrieveItemsByCategory(selectedCategory); //gets the items
for (int count = 0; count < categories.size(); count++) {
selectedCategories.add(new SelectItem(categories.get(count).getId(),categories.get(count).getDescription()));
if (selectedCategory == 0){
selectedCategory = categories.get(0).getId();
for (int count = 0; count < items.size(); count++) {
selectedItems.add(new SelectItem(items.get(count).getId(),items.get(count).getDescription()));
if (selectedItem == 0){
selectedItem = items.get(0).getId();
public void CategoryChange(ValueChangeEvent vce){
try {
if (vce.getPhaseId() != PhaseId.INVOKE_APPLICATION) {
vce.setPhaseId(PhaseId.INVOKE_APPLICATION);
vce.queue();
} else {
FacesContext.getCurrentInstance().renderResponse();
selectedCategory = Integer.parseInt(vce.getNewValue().toString());
category = CategoryService.retrieveCategoryById(selectedCategory); // gets the category Object
} catch (Exception e) {
logger.error("Error occured: {}",e.toString());
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage("ERROR", new FacesMessage(e.toString()));
public List<SelectItem> getSelectedCategories() {
return selectedCategories;
public void setSelectedCategories(List<SelectItem> selectedCategories) {
this.selectedCategories = selectedCategories;
public List<SelectItem> getSelectedItems() {
return selectedCategories;
public void setSelectedItems(List<SelectItem> selectedItems) {
this.selectedItems = selectedItems;
}The bean is request scoped.
Maybe you are looking for
-
I am reinstalling Photoshop ELements 10 on WIndows 7 64.. Serial number is repeatedly rejected as "invalid" I have tried reregistering and was again rejected as invalid. I have tried tech chat with 11/2 wait with no ANSWER?
-
I used my friend itune to transfer songs to my iphone 4 but when i am using itunes from my laptop i am not able to tranfer songs to iphone.. .. why and what need to do ?
-
Reasons why to use Iterator for List rather than for loop ?
when i use the iterator and for loop for traversing through the list. it takes the same time for iterator and also for for loop. even if there is a change it is a minor millisecond difference. what is the actual difference and what is happening behin
-
Hi! Proxy Server Implementation Help required!
Hello Everybody! I am new to java networking and I want to develop Proxy Server in Java. Could somebody tell me where and how to start. Any help will be highly appreciated. Thanks in advance.
-
How to remove exclusive menus and programs from responsibilities
I have a batch of exclusive menus and programs original defined in responsibilities. Right now, need to remove them from around 300 responsibilities. How? thanks