Col to row
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');
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 -
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.
-
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... -
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 -
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. -
Hello All,
Here is what I am trying to do...
1. I am having two rows, one column in an Object Variable. (vLoopCountObj).
2. I am having 30 Rows, 2 Columns in my second Object Variable (vTableRowsObj)
3. I have a FOR EACH LOOP which will run for number of rows in vLoopCountObj i.e 2 times here.
4. I have a Script Task inside the FOR EACH LOOP to display all the rows of vTableRowsObj.
5. When I execute, 30 Rows gets displayed only once. It will not display when the loop goes for second iteration. Please help me to display for second time.
6. I have used below code to display the rows whithin the script task which is in SSIS dataflow task.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Xml
Imports System.Collections
Imports System.Data.OleDb
Public Class ScriptMain
Public Sub Main()
Dim oleDA As New OleDbDataAdapter
Dim dt As New DataTable
Dim col As DataColumn
Dim row As DataRow
Dim sMsg As String
oleDA.Fill(dt, Dts.Variables("vTableRowsObj").Value)
MsgBox("Number of Rows " + dt.Rows.Count.ToString())
For Each row In dt.Rows
For Each col In dt.Columns
sMsg = sMsg & col.ColumnName & ": " & row(col.Ordinal).ToString & vbCrLf
Next
MsgBox(sMsg)
sMsg = ""
Next
Dts.TaskResult = Dts.Results.Success
End Sub
End ClassHi Raj,
It is verrrry interesting issue. I can also confirm that it doesnt loop again. I've made a simple test and figured that in the second loop even you fill the Dataadapter, record count is zero. Which brings me up to the idea: Somehow, after you read the object
variable resultset, you can not read it again in the for each loop.
Strange, probably a bug or a technical issue that is beyond my existing knowledge.
I can provide a workaround. You can also loop in script task for first variable. (Nested loops)
Let other members to examine and comment on this.
Regards
Onur
(For others who also wants to test, here is my scenario
Execute SQL Task 1:
Query: SELECT 1 as Cnt UNION ALL SELECT 2 as Cnt
Resultset: Full Resultset
ResultSet Tab: Name: 0, Variable Name: User::vLoopCountObj;
Execute SQL Task 2:
Query: SELECT 1 as ColA, 2 as ColB UNION ALL SELECT 3 as ColA, 4 as ColB UNION ALL SELECT 5 as ColA, 6 as ColB
Resultset: Full Resultset
ResultSet Tab: Name: 0, Variable Name: User::vTableRowsObj;
For Each Loop Container:
Collection: Enum: ForEach ADO Enum
Source Object: User::vLoopCountObj
Enum Mode: Rows n the first Table
Script Task:
ReadOnlyVariables: User::vTableRowsObj
Script Source:
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Xml
Imports System.Collections
Imports System.Data.OleDb
Public Class ScriptMain
Public Sub Main()
Dim oleDA As New OleDbDataAdapter
Dim dt As New DataTable
Dim col As DataColumn
Dim row As DataRow
Dim sMsg As String
oleDA.Fill(dt, Dts.Variables("vTableRowsObj").Value)
Dts.Events.FireInformation(-1, "START!!!!!!!!!!!!!!", "START LOOP", "", 0, True)
Dts.Events.FireInformation(1, "RowCount: ", dt.Rows.Count.ToString(), "", 0, True)
For Each row In dt.Rows
For Each col In dt.Columns
sMsg = sMsg & col.ColumnName & ": " & row(col.Ordinal).ToString & vbCrLf
Next
Dts.Events.FireInformation(1, "Msg: ", sMsg, "", 0, True)
sMsg = ""
Next
Dts.TaskResult = ScriptResults.Success
End Sub
End Class
BI and ERP Senior Consultant @ Nexum Bogazici
If it is, Please dont forget to mark as answered or at least vote as helpful if the post helps you in any ways. -
How can I add rows to a JTable based on an Abstract Table Model?
I have done this ...
public class myui extends JPanel {
private AbstractTableModel jTable1Model;
blah blah
jTable1Model = new AbstractTableModel() {
String[] column = new String[]{"TID", "Name", "Address"};
Vector<Vector<Object>> table = new Vector<Vector<Object>>();
@Override
public int getRowCount() {
return table.size();
@Override
public int getColumnCount() {
return column.length;
@Override
public String getColumnName(int col) {
return column[col];
@Override
public Object getValueAt(int row, int column) {
return table.get(row).get(column);
@Override
public void setValueAt(Object value, int row, int column) {
table.get(row).set(column, value);
fireTableCellUpdated(row, column);
public void insertRow() {
Vector<Object> columns = new Vector<Object>();
columns.add(null);columns.add(null);columns.add(null);
table.add(columns);
fireTableRowsInserted(0, table.size());
blah blah
public synchronized void ImportVisitorDataToJTable1(Object value, int row, int col) {
jTable1Model.InsertRow(); <-----///// This line not being recognised as a valid member function call
jTable1.setValueAt(value, row, col);
}I thought to insert a row I can define a function in the abstracttablemodel class and then instantiate the class and override or create new methods that I can use.
But after instantiating the class and overriding appropriately and adding the insertRow function, when I try to use it in ImportVisitorDataToJTable1 as seen above its not being recognized as a funtion of jTable1Model1. respect naming conventions. Example: myui --> MyUI, ImportVisitorDataToJTable1 -->importVisitorDataToJTable1
2. convert Anonymous to Member: AbstractTableModel --> MyTableModel
3. row parameter makes no sense here as it depends on current row count:
public synchronized void importVisitorDataToJTable1(Object value, int col) {
int row = jTable1Model.getRowCount();4. here is a more adequate "fireTable.."-call for insertRow:
fireTableRowsInserted(table.size() - 1, table.size() - 1);
5. check if you can take advantage using DefaultTableModel as suggested by Maxideon. -
Hi experts!
I need the total number of ROWS in EACH database i have (All schema)
I've tried this for each DB
select sum(num_rows)
from sys.dba_tables
where owner like '%%'
i obtain the number of all rows for all schema in database.
I have many database, i use agent g10.0 and enterprice manager to query them.
I
've seen that in Enterprise Manager, when you select a Database Istance, then go on "administration" tab, and u click on TABLES link, you can see number of rows and last time the table was analyzed. How are they have been calculated? With table dba_tables? How can i query to obtain these values?
I know it's a stupid task but my boss wants this info :(> I know it's a stupid task but my boss wants this info :(
Tell him two gazillion. Also tell him that the gazillion scale has been specifically created for managers like him with heads firmly stuck up the back side.
Anyway, here's some sample code. Note that you cannot use DBA_TABLES view. Object tables are not listed in there and they can contain rows (obviously). There is also the case of dealing with case and "weirdly" names tables - thus double quotes are needed.
I only did the first 10 tables.. It is stupid to just one, never mind all of them in database...
SQL> declare
2 type TStrings is table of varchar2(1000);
3
4 cursor c is
5 select '"'||owner||'"."'||object_name||'"' as TAB_NAME from dba_objects where object_type='TABLE' and rownum < 11 order by 1;
6
7 tabList TStrings;
8 sqlSelect varchar2(1000);
9 cnt integer;
10 total integer;
11
12 procedure W( line varchar2 ) is
13 begin
14 DBMS_OUTPUT.put_line( line );
15 end;
16 begin
17 total := 0;
18 open c;
19 loop
20 fetch c bulk collect into tabList limit 100;
21 for i in 1..tabList.Count
22 loop
23 sqlSelect := 'select count(*) from '||tabList(i);
24 begin
25 execute immediate sqlSelect into cnt;
26 total := total + cnt;
27 W( sqlSelect || ' ' || cnt || ' rows(s)' );
28 exception when OTHERS then
29 W( sqlSelect || ' ' || sqlerrm(sqlcode) );
30 end;
31 end loop;
32 exit when c%NOTFOUND;
33 end loop;
34 close c;
35 W( total|| ' gazillion rows in the database' );
36 end;
37 /
select count(*) from "SYS"."CLU$" 10 rows(s)
select count(*) from "SYS"."COL$" 43696 rows(s)
select count(*) from "SYS"."CON$" 2898 rows(s)
select count(*) from "SYS"."FILE$" 5 rows(s)
select count(*) from "SYS"."ICOL$" 2184 rows(s)
select count(*) from "SYS"."IND$" 1434 rows(s)
select count(*) from "SYS"."PROXY_ROLE_DATA$" 0 rows(s)
select count(*) from "SYS"."SEG$" 3032 rows(s)
select count(*) from "SYS"."UET$" 0 rows(s)
select count(*) from "SYS"."UNDO$" 11 rows(s)
53270 gazillion rows in the database
PL/SQL procedure successfully completed.
SQL> PS. Cursor needs fine tuning as certain table objects cannot be directly accessed via a SELECT statement (e.g. nested tables, overflow IOT tables, etc). -
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);
} -
Double click on a JTable row.
I got and run a sample about double click on a JTable and it works fine. This sample defines a TableModel as shown at the end this note.
On the other hand, I have an application in which I have defined a JTable
using the DefaultTableModel as follows :
DefaultTableModel dtm = new DefaultTableModel(data, names);
JTable table = new JTable(dtm); where data and names are String arrays.
Of course the mouse listener stuffs have been also specified.
table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if (e.getClickCount() == 2){
System.out.println(" double click" );
} );Because the difference with the sample was the table model,
I changed it with the DefaultTableModel class. At this point, the Double click does not work anymore.
So I gues it should be an option which prevents double click to work.
I thought of using mousePress() instead of mouseClick(), but it's very dangerous (I tried). . If by error the user clicks twice (instead of only once) the mousePress method is invoked twice for the same entry
My question is now simple, may I use double click on a JTable with the default table model. If so, what I have to do ?
Thanks a lot
Gege
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return names.length; }
public int getRowCount() { return data.length;}
public Object getValueAt(int row, int col) {return data[row][col];}
public String getColumnName(int column) {return names[column];}
public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
};import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class ClickIt extends MouseAdapter
public void mousePressed(MouseEvent e)
JTable table = (JTable)e.getSource();
Point p = e.getPoint();
if(e.getClickCount() == 2)
System.out.println("table.isEditing = " + table.isEditing());
int row = table.rowAtPoint(p);
int col = table.columnAtPoint(p);
String value = (String)table.getValueAt(row,col);
System.out.println(value);
private JTable getLeftTable()
final String[] names = { "column 1", "column 2", "column 3", "column 4" };
final Object[][] data = getData("left");
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return names.length; }
public int getRowCount() { return data.length;}
public Object getValueAt(int row, int col) {return data[row][col];}
public String getColumnName(int column) {return names[column];}
public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
JTable table = new JTable(dataModel);
return configure(table);
private JTable getRightTable()
String[] colNames = { "column 1", "column 2", "column 3", "column 4" };
JTable table = new JTable(new DefaultTableModel(getData("right"), colNames));
return configure(table);
private Object[][] getData(String s)
int rows = 4, cols = 4;
Object[][] data = new Object[rows][cols];
for(int row = 0; row < rows; row++)
for(int col = 0; col < cols; col++)
data[row][col] = s + " " + (row*cols + col + 1);
return data;
private JTable configure(JTable table)
table.setColumnSelectionAllowed(true);
table.setCellSelectionEnabled(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.addMouseListener(this);
return table;
private JPanel getContent()
JPanel panel = new JPanel(new GridLayout(1,0,0,5));
panel.add(new JScrollPane(getLeftTable()));
panel.add(new JScrollPane(getRightTable()));
return panel;
public static void main(String[] args)
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new ClickIt().getContent());
f.pack();
f.setVisible(true);
} -
How to change the row position in a datatable
I am storing my list of lists in a datatable :
DataTable table = new DataTable();
for(int i = 0; i < info.Count; i++)
table.Columns.Add(names[i]);
for(int col = 0; col < info.Count; col++)
for(int rows = 0; rows < info[col].Count; rows++)
DataRow r = table.Rows.Add();
r[names[col]] = info[col][rows];
However the problem is that it is stored diagonally. Meaning that the first column is shown on rows 0-3, the second column 4-7 and so on. I want all the columns to be stored in positions 0-3. How can I do that ?"What would you suggest instead of datatable? I just want to show info of my lists that's all."
Show in a control such as the WinForms's DataGridView or something similar?
If you do not known the number and type of columns in advance then yes, using DataTable is a convenient way to do that as binding the grid to the list of lists won't work. Well, if the number of rows you can consider populating the grid control directly.
If you do know the number and type of columns it's in general preferable to create a class to hold the information that corresponds to a row and then use a list of objects of that class. That list can easily be displayed in a grid control.
Maybe you are looking for
-
How to calculate total stock quantity in cube
Dear Master I want to verify the data between BI report and cube whether correct or not.My report name is stock summary. It's giving report for Total quantity stock (0TOTALSTCK) for paricular date. This KF(0TOTALSTCK) inflow is 0RECTOTSTCK and ou
-
how do I create an app? I have a buddy who is in a band and they have an app for android users only, I was wondering how I would go about creating one for iphone, ipod, & ipad users.
-
Changing Internal & External URLs?
We run split DNS so right now for all services the internal and external Exchange 2010 URLs are simply set to mail.domain1.com. If I change them to mail.domain2.net, assuming there is a valid cert on the Exchange box for mail.domain2.net, and assumin
-
Why is the last script executed twice?
Here is my problem. I have two files, file1.sql and file2.sql that are called in a third file test.sql. The output from test.sql show that file2.sql was called twice --file1.sql select 'file1' as str from dual; --file2.sql select 'file2' as str from
-
Security and Network Management: EAP-PEAP AUTHENTICATION
Hi, does someone has the example of the implementation of EAP-PEAP authentication on a Cisco Aironet 1242 AP? I'm trying to make the configuration of one, but not succeeding. Jorge