Displaying jtable as rows instead of columns
This may be really simple, but I can't figure it out. I want to display information in a JTable as rows instead of columns. Can anyone help me with this?
Thanks in advance,
m
Check here:
http://www2.gol.com/users/tame/swing/examples/SwingExam
les.html
They may well have what you want, if not they will
probably have some ideas you can use.There's always the swing tutorial, also. I learned JTables from the tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/table.html and it gave me a lot of good ideas and points to start from.
You could probably create your own cell renderer (or use the header renderer) and set the first column to use that to display their text.
Similar Messages
-
Displaying SQL Query results in rows instead of Columns
Hi,
I'm fairly new to Oracle so forgive me if this is a really stupid question.
I used Mysql for a while and if I wanted to display query results in rows instead of columns I could end the SQL command with '\G' instead of a semicolon.
This would give me output like...
Column_1: AAAA
Column_2: BBBB
Column_3: CCCC
Instead of the normal
Column_1 Column_2 Column_3
AAAAAA BBBBBBB CCCCCCC
Is there an equivalent in SQLPlus to the MySQL \G termination?
Thanks.
John> so forgive me if this is a really stupid question.
It is certainly not a stupid question, but pivoting is a very frequently asked and answered question:
[url http://forums.oracle.com/forums/search.jspa?threadID=&q=pivot&objID=f75&dateRange=all&userID=&numResults=15]http://forums.oracle.com/forums/search.jspa?threadID=&q=pivot&objID=f75&dateRange=all&userID=&numResults=15
In 11g you have special PIVOT and UNPIVOT functions.
Regards,
Rob. -
How to display ID and Type in a row instead of column
I have a table A with ID_NO, TYPE, PUBID(foreign key).
The type can be CAT, ISBN, ISSN. I also have another table B with PUB_ID (primary key) and a lot of other details.
The requirements are to display the results as rows like this:
PUB_NO | CAT | ISBN | ISSN
222 | abc | qwe | zxc
I know it would be easy to display like this:
ID_NO | TYPE | PUB_NO
abc | CAT | 222
qwe | ISBN | 222
zxc | ISSN | 222
But I need it in a row instead. I was thinking of getting all PUB_NOs and looping through each to get the rest in a PL/SQL procedure but is this the best approach?
I can't wrap my head around this. I'm not a DB expert and I haven't done any PL/SQL in a very long time.
Thanks for your help
MarcelJohn:
<quote>
I did point out the need for unique types in my original post with the MAX/DECODE solution.
</quote>
Indeed, you did. Sorry about that ... I looked closely only at your last post with the two SQLs and missed the caveat you had included in the first post.
:o) ... couldn't stop myself ... one last loose [but reasonable?!?!] thing [I can think of] to keep those 2 sql different:
insert into pubDetail values (333,'333');
â¦
flip@FLOP> select * from pubDetail;
Â
PUB_NO PUB_DATA
111 111
222 222
333 333
Â
flip@FLOP> select * from test_a;
Â
ID_NO TYPE PUB_NO
abc CAT 111
def CAT 222
qwe ISBN 111
xyz ISSN 222
Â
flip@FLOP> SELECT d.pub_no, a.cat, b.isbn, c.issn
2 FROM pubDetail d,
3 (SELECT pub_no, id_no cat
4 FROM test_a
5 WHERE type = 'CAT') a,
6 (SELECT pub_no, id_no isbn
7 FROM test_a
8 WHERE type = 'ISBN') b,
9 (SELECT pub_no, id_no issn
10 FROM test_a
11 WHERE type = 'ISSN') c
12 WHERE d.pub_no = a.pub_no(+) AND
13 d.pub_no = b.pub_no(+) AND
14 d.pub_no = c.pub_no(+)
15 ;
Â
PUB_NO CAT ISBN ISSN
111 abc qwe
222 def xyz
333
Â
flip@FLOP> SELECT d.pub_no
2 ,MAX(DECODE(a.type, 'CAT' , id_no)) cat
3 ,MAX(DECODE(a.type, 'ISBN', id_no)) isbn
4 ,MAX(DECODE(a.type, 'ISSN', id_no)) issn
5 FROM pubDetail d, test_a a
6 WHERE d.pub_no = a.pub_no
7 AND a.type IN ('CAT', 'ISBN', 'ISSN')
8 GROUP BY d.pub_no
9 ;
Â
PUB_NO CAT ISBN ISSN
111 abc qwe
222 def xyzHope you take this only as a bit of humor [about incomplete requirements] ⦠I like your stuff! -
Display only one row for distinct columns and with multiple rows their valu
Hi,
I have a table having some similar rows for some columns and multiple different rows for some other columns
i.e
o_mobile_no o_doc_date o_status d_mobile_no d_doc_date d_status
9825000111 01-jan-06 'a' 980515464 01-feb-06 c
9825000111 01-jan-06 'a' 991543154 02-feb-06 d
9825000111 01-jan-06 'a' 154845545 10-mar-06 a
What i want is to display only one row for above distinct row along with multiple non distinct colums
ie
o_mobile_no o_doc_date o_status d_mobile_no d_doc_date d_status
9825000111 01-jan-06 'a' 980515464 01-feb-06 c
991543154 02-feb-06 d
154845545 10-mar-06 a
regards,
KumarRe: SQL Help
-
Displaying JTable (AbstractTableModel) rows based on radiobox criteria
hi,
Would appreciate some pointers as to how to do this ...
I have a AbstractTableModel that needs to display rows depending on which radiobox criteria is selected.
There are only 2 columns in the JTABLE:
(1) categories (string)
(2) register interest (boolean)
The radioboxes (and the criterias) are:
1. display all rows
2. display only rows when register interest = false
3. dislplay only rows when register interest = true
How can i achieve this ?
The GetValue/SetValue from AbstractTableModel() deal at the column and not row level. So i am stumped.
Thanks for any help.
TonySince you have a custom table model, just create one collection that represents the permanent (all) data, and one collection that represents the filtered data. When the radio selection changes, update the filtered data collection by filtering the permanent data collection.
-
TDMS Data appears in row instead of column
Hi,
I am working on a program that reads in temperature data from a TDMS file, shifts the data through a 'normalising' equation and puts it back into the same TDMS file onto a different page.
The problem I am getting is when the normalised data gets written back into the TDMS file, the data that should appear in the columns now appears in rows. See picture attached that illustrates this.
Does anyone know how I can write the data to the file so that it appears in the column and not the row. In my VI you will see that I have had to transpose the 2D array otherwise all the data just appears in one single row.
Also several cells just containing 0 have appeared in my data set which should not be there.
I will attach my VI to this. I will also attach one of the TDMS data files.
Thanks in advance,
Rhys
Solved!
Go to Solution.
Attachments:
Row Column Switch.png 285 KB
normalising program.vi 36 KB
TDMS Files.zip 18 KBHi Rhys,
After looking into your normalising program.vi, I would recommend:
Don't use that Transpose 2D array, it doesn't solve your problem.
Write the "normalized" data to different channels, you get all the data just appears in one single column because you write all the “normalized” data to one single channel repeatedly, thus they'll appear in one column(channel).
Several cells containing zeros is because float64 y1[30] array in your normalising equation, you need remove the zero elements from y1[30] before writing to file.
I attached the modified normalising program.vi, hope this can do some help to your problem.
The snapshot below shows the data in Excel after "normalising" equation, the channel data appears in columns.
Attachments:
normalising program(updated).vi 37 KB -
Output data in row wise instead of column
hi all,
i need to get the output data in row wise which is getting now as column wise.
for eg:
below is my final internal table.
HEADING DATE MATNR BUKRS DMBTR
jan/08 200801 567 10 800
feb/08 200802 567 10 900
mar/08 200803 567 10 200
apr/09 200804 567 10 400
the output should come as
MATNR BUKRS Jan/08 Feb/08 Mar/08 Apr/08
567 10 800 900 200 400.
instead of column wise the output should display as row as above.
please help how to get this.
thanks in advanceHi Vignesh,
Please use below program which I created for you reference. It will work for your requirement.
DATA:BEGIN OF it_test OCCURS 1,
date(6),
matnr(5),
bukrs(3),
END OF it_test.
it_test-date = 'jan/08'.
it_test-matnr = '01234'.
it_test-bukrs = 'AE1'.
APPEND it_test.
it_test-date = 'feb8'.
it_test-matnr = '56789'.
it_test-bukrs = 'AE1'.
APPEND it_test.
it_test-date = 'mar8'.
it_test-matnr = '23478'.
it_test-bukrs = 'AE1'.
APPEND it_test.
START-OF-SELECTION.
LOOP AT it_test.
WRITE :/ 'DATE', 'MATNR', 'BUKRS', it_test-date, it_test-matnr, it_test-bukrs .
ENDLOOP.
Output Will be as follows :-
DATE MATNR BUKRS jan/08 01234 AE1
DATE MATNR BUKRS feb8 56789 AE2
DATE MATNR BUKRS mar8 23478 AE3
Please set to resolve if this satisfies your requirement.
Regards
Abhii.. -
Different number of rows for different columns in JTable
hi
I need to create a JTable with different number of rows for different columns...
Also the rowheight should be different in each column...
say there is a JTable with 2 columns... Col1 having 5 rows and column 2 having 2 rows...
The rowHeight in Col2 should be an integer multiple of Rowheight in Col1
how do I do this ??
can anybody send me some sample code ?????
thanx in advanceHow about nesting JTables with 1 row and many columns in a JTable with 1 column and many rows.
Or you could leave the extra columns null/blank.
You could use a GridBagLayout and put a panel in each group of cells and not use JTable at all.
It would help if you were more specific about how you wanted it to appear and behave. -
Showing report data columns into two rows instead of one row using SSRS 2012
Hi All,
I have a ssrs report with 13 columns and I want to show those 13 columns data into two rows instead of showing in one row. please send me step by step process.
id fullname firstname lastname mailingaddress billingaddress
city state zipcode
1 ABC A C
xyz xyz123 york
PA 12345
homephone cellphone workphone company
1234567890 4567890123 0123456789 ABC,Inc
id fullname firstname lastname mailingaddress billingaddress
city state zipcode
2 XYZ X Z
abc abc123 lewisburg
PA 54321
homephone cellphone workphone company
4567890123 0123456789 1234567890 xyz,Inc
id fullname firstname lastname mailingaddress billingaddress
city state zipcode
3 BCD B D
123abc xyz123 leesburg PA
54123
homephone cellphone workphone company
4567895623 0783456789 1238967890 Hey,Inc
Thanks in advance,
RH
sqlDo a right mouse click on the left, gray row marker => "Insert Row"=> "Inside Group
- Above or Below", then you get a second detail row.
Olaf Helper
[ Blog] [ Xing] [ MVP] -
How to display number of rows as columns in a select statement? This is on
How to display number of rows as columns in a select statement? This is on 10g R2.
Thanks,
RFor the current (ie. row 1 of 100)
row_number over (order by -pick_a_column_set) as rnfor the total number of columns returned in your query
count(*) over() as total_count -
JTable - Resize rows the same way as the columns
Hi!
I have run into a very frustrating problem and have tried to solve this for many hours but can't come up with a good solution. If there is anyone that can help me on the right track I will be very grateful!
When I'm using a JTable it provides good "graphical" functionality to handle resize of colums, but when it comes to resize rows it is not available.
I have found a solution for the row height adjustment in the following post: [http://forums.sun.com/thread.jspa?forumID=257&threadID=453665]
That solution only partially work in my case because of the following:
The JTable exists inside a JInternalFrame and the JTable should not be able to get bigger then the actual size of the InternalFrame it is put in (so no scrollbar).
The problem with the solution above is that the JTable total height will also expand when a row is resized (contrary to what happens when the columns are resized), ending up with a JTable that is bigger then the InternalFrame.
So my question is:
Is it possible to provide the same ("graphical") resize functionality for rows as for columns in a JTable? Or any row resize functionality that prevent the JTable from getting bigger then the container it is placed in?
Thanks for your time!
Best regards,
MarcusThanks for the fast answer!
Yes, that would solve the height expanding problem. Thanks!
It would be even better though if the row resize functionality would behave the same as the column resize (for consistency). For example: If a row is resized the other rows will get smaller so they all fit into the InternalFrame.
It has to be some easy way to do this. I have started on a solution with component listeners etc. (to track resize) but it is quite hard to get it right and I keep getting the feeling I reinventing the wheel all over again:(
Any ideas out there? -
Display rows into multiple columns
I have a table in the following format:
id value
a1 0
a2 0
a3 0
a4 0
b1 0
b2 0
b3 0
b4 0
how do I go about displaying it into four columns in the following format:
id1 value1 id2 value2
a1 0 b1 0
a2 0 b2 0
a3 0 b3 0
a4 0 b4 0Hi,
789063 wrote:
I got that error in toad. So now I am testing from command prompt. When you say "command prompt", do you mean SQL*Plus?
Sorry, I don't know much about Toad. If Toad is returning 0 rows, and the same query is returning 8 rows in SQL*Plus, then I suspect you are not connecting to the same database or the same user. ASre you sure you're running the exact same query in both front ends?
Here is the data set that I am testing for:
<pre>
id1 value
smple_val_1 0
smple_val_2 1
smple_val_3 1
smple_val_4 2
smple_other_1 3
smple_other_2 5
smple_other_3 8
smple_other_4 13
some_other_val1 1
some_other_val2 0
some_other_val3 3
some_other_val4 5
</pre>
I am trying to select only 'smple%' in the query, which should display in four columns like:
<pre>
id1 val1 id2 val2
smple_val_1 1 smple_other_1 3
smple_val_2 0 smple_other_2 5
smple_val_3 0 smple_other_3 8
smple_val_4 2 smple_other_4 13
</pre>Is that really the output you want? Why not
ID1 VAL1 ID2 VAL2
smple_val_1 0 smple_other_1 3
smple_val_2 1 smple_other_2 5
smple_val_3 1 smple_other_3 8
smple_val_4 2 smple_other_4 13with the 0's and 1's in the val1 column reversed?
Here is the ddl I used:
<pre>
CREATE TABLE table_x
( id VARCHAR2 (20) PRIMARY KEY
, value NUMBER
INSERT INTO table_x (id, value) VALUES ('smple_val_1', 0);
INSERT INTO table_x (id, value) VALUES ('smple_val_2', 1);
INSERT INTO table_x (id, value) VALUES ('smple_val_3', 1);
INSERT INTO table_x (id, value) VALUES ('smple_val_4', 2);
INSERT INTO table_x (id, value) VALUES ('smple_other_1', 3);
INSERT INTO table_x (id, value) VALUES ('smple_other_2', 5);
INSERT INTO table_x (id, value) VALUES ('smple_other_3', 8);
INSERT INTO table_x (id, value) VALUES ('smple_other_4', 13);
INSERT INTO table_x (id, value) VALUES ('some_other_val1', 1);
INSERT INTO table_x (id, value) VALUES ('some_other_val2', 0);
INSERT INTO table_x (id, value) VALUES ('some_other_val3', 3);
INSERT INTO table_x (id, value) VALUES ('some_other_val4', 5);
</pre>Thanks, that's good.
Where is the explanation of how you get the results you want from that data? There are a lot of different ways to get the same results from the same data, especially from a small set of sample data. I might provide a query that gets the right results for the wrong reasons, and when you run that query on a different set of data, it won't necessarily work. That's exactly what happened before. I guessed at what you wanted, but I guessed wrong. Guessing is not a very efficient or reliable way to solve problems. Don't make people guess: explain what you want.
In particular, explain how you can tell, buy looking at a row and column in the original table, to which row and which column of the output it corresponds. I'm pretty sure that the id column of the table always corresponds to either the id1 or idl2 column of the output, and that value always corresponds to either val1 or val2. From this latest set of sample data, it looks like all the rows in table_x that start with 'smple_val' will correspond to the id1 and val1 columns, and that all therows that start with 'smple_other_' will correspond to the id2 and val2 columns. It also looks like each row of the output represents a unique value of the last character of table_x.id.
If I guessed right this time, then what you want is:
SELECT MIN (CASE WHEN id LIKE 'smple\_val\_%' ESCAPE '\' THEN id END) AS id1
, MIN (CASE WHEN id LIKE 'smple\_val\_%' ESCAPE '\' THEN value END) AS val1
, MIN (CASE WHEN id LIKE 'smple\_other\_%' ESCAPE '\' THEN id END) AS id2
, MIN (CASE WHEN id LIKE 'smple\_other\_%' ESCAPE '\' THEN value END) AS val2
FROM table_x
GROUP BY SUBSTR (id, -1)
ORDER BY SUBSTR (id, -1)
;But this is only a guess. I can't guarrantee that this will work on your real data any better than my last guess did. You'll get better answers faster if you provide an explanation, so that poeple don't have to guess so much. -
JTable with row header plus value extraction from headers
Hi, I am trying to do the following:
Short Version-
1. Create a table that has both row and column headers
2. Allow the user to mouse over any of these headers such that doing so will display an image I have produced on a panel. (I already know how to create the image and how to display it, I'm just not sure how to associate it with a particular row or column header)
3. Make the row headers look as much as possible like the column headers.
Slightly Longer Version-
Column headers will be labled A-H (maximum) while row headers will be labled 1-12 (maximum). Either can be less, however, depending on user input. After the table has been realized, the user will move the mouse over say, header 'H' and when they do, a JPEG image will appear on another panel and a tooltip will appear above the cell showing a formula. This happens when either row or column headers are moused over.
Currently, I am using the following code from the O'reilly Swing book as a baseline for experimentation but any help you can offer will be appreciated. I'm fairly new to the JTable world... :-(
TableModel tm = new AbstractTableModel(){
String data[] = {"", "a", "b", "c", "d", "e"};
String headers [] = {"Row #", "Column1", "Column2", "Column3", "Column4", "Column5"};
public int getColumnCount(){ return data.length;}
public int getRowCount() { return 1000;}
public String getColumnName(int col){ return headers[col];}
public Object getValueAt(int row, int col){
return data[col] + row;
//creates a column model for the main table. This model ignores the first
//column added and sets a minimum width of 150 pixels for all others
TableColumnModel cm = new DefaultTableColumnModel(){
boolean first = true;
public void addColumn(TableColumn tc){
if(first) {first = false; return;}
tc.setMinWidth(150);
super.addColumn(tc);
//Creates a column model that will serve as the row header table. This model
//picks a maxium width and stores only the first column
TableColumnModel rowHeaderModel = new DefaultTableColumnModel(){
boolean first = true;
public void addColumn(TableColumn tc){
if(first) {
tc.setMaxWidth(tc.getPreferredWidth());
super.addColumn(tc);
first = false;
JTable grid = new JTable(tm, cm);
//set up the header column and hook it up to everything
JTable headerColumn = new JTable(tm, rowHeaderModel);
grid.createDefaultColumnsFromModel();
headerColumn.createDefaultColumnsFromModel();
//make sure the selection between the main table and the header stay in sync
grid.setSelectionModel(headerColumn.getSelectionModel());
headerColumn.setBorder(BorderFactory.createEtchedBorder());
headerColumn.setBackground(Color.lightGray);
headerColumn.setColumnSelectionAllowed(false);
headerColumn.setCellSelectionEnabled(false);
JViewport jv = new JViewport();
jv.setView(headerColumn);
jv.setPreferredSize(headerColumn.getMaximumSize());
//to make the table scroll properly
grid.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//have to manually attach row headers but after that, the scroll pane
//keeps them in sync
JScrollPane jsp = new JScrollPane(grid);
jsp.setRowHeader(jv);
jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader());
gridPanel.add(jsp, BorderLayout.NORTH);There a number of nice examples on JTable: http://www.senun.com/Left/Programming/Java_old/Examples_swing/SwingExamples.html
Hope you could find something suitable ...
Regards,
Anton. -
Table Rendering - Row level vs Column level
Normally renderers are specified for a given class of data or column of data.
So, how would you handle rendering requirements that are row or table dependent? For example, how do I:
a) color alternate lines in a table
b) change the border of the selected cell
Traditional Approach
Most answers in the forum would be something like "use a custom render". Sounds great, but what does it really mean? If all your data is displayed as a String then it really isn't too difficult to create a single renderer with the required logic and add it to the table as the default renderer.
However, what if you table contains, String's, Dates, Integer's, Double's and Boolean's and you want your cell to retain the default formatting of each data type in addition to the above requirement? Now you have two options:
a) render by class (multiple renderers). Each renderer would need to implement the default "formatting" of the data (dates: dd-MMM-yyy, numbers: right justified, etc) in addition to the "row/table" rendering requirements. So the answer really becomes "use five custom renderers". Now the "row/table" rendering code is found in 5 classes. Of course you could always move the "row/table" rendering code up to a common base class.
b) render by table (single renderer). A single custom renderer would be created and would need to implement the default "formatting" for all data types in the table, in addition to the "row/table" rendering. The benefit is that all the rendering code is in one class. An example solution is include for this approach.
Alternative Approach
I recently came across an approach where the "formatting" of the data is still done by the default renderers and the "row/table" rendering is done at the table level by overriding the prepareRenderer() method. This approach is much simpler, but the rendering is done in two different places. Is this a problem?
So, my question is which approach do you prefer:
a) Traditional Approach - multiple renderers
b) Triditional Approach - single renderer
c) Alternative Approach
Me, I like the alternative approach, but I'm more of a problem solver than I am a designer, so I don't know how the solution fits in a large scale application.
Hopefully your response will consider:
a) OO design principles
b) class reusability
c) class maintenance
d) anything else you can think of
import java.awt.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class TableRowRendering extends JFrame
JTable table;
Border selected = new LineBorder(Color.GREEN);
public TableRowRendering()
// Model used by both tables
Object[] columnNames = {"Type", "Date", "Company", "Shares", "Price"};
Object[][] data =
{"Buy", new Date(), "IBM", new Integer(1000), new Double(80.50)},
{"Sell",new Date(), "MicroSoft", new Integer(2000), new Double(6.25)},
{"Sell",new Date(), "Apple", new Integer(3000), new Double(7.35)},
{"Buy", new Date(), "Nortel", new Integer(4000), new Double(20.00)}
DefaultTableModel model = new DefaultTableModel(data, columnNames)
public Class getColumnClass(int column)
return getValueAt(0, column).getClass();
// Traditional Approach
table = new JTable( model );
table.setPreferredScrollableViewportSize(table.getPreferredSize());
getContentPane().add(new JScrollPane( table ), BorderLayout.WEST);
TableCellRenderer custom = new CustomRenderer();
table.setDefaultRenderer(Object.class, custom);
table.setDefaultRenderer(String.class, custom);
table.setDefaultRenderer(Date.class, custom);
table.setDefaultRenderer(Number.class, custom);
table.setDefaultRenderer(Double.class, custom);
// Alternative Approach
table = new JTable( model )
public Component prepareRenderer(
TableCellRenderer renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row, column);
if (!isRowSelected(row))
String type = (String)getModel().getValueAt(row, 0);
c.setBackground(row % 2 == 0 ? null : Color.LIGHT_GRAY );
if (isRowSelected(row) && isColumnSelected(column))
((JComponent)c).setBorder(selected);
return c;
table.setPreferredScrollableViewportSize(table.getPreferredSize());
getContentPane().add(new JScrollPane( table ), BorderLayout.EAST);
// Custom renderer used by Traditional approach
class CustomRenderer extends DefaultTableCellRenderer
DateFormat dateFormatter = SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
NumberFormat numberFormatter = NumberFormat.getInstance();
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
// Code for data formatting
setHorizontalAlignment(SwingConstants.LEFT);
if ( value instanceof Date)
setText(dateFormatter.format((Date)value));
if (value instanceof Number)
setHorizontalAlignment(SwingConstants.RIGHT);
if (value instanceof Double)
setText(numberFormatter.format(((Number) value).floatValue()));
// Code for highlighting
if (!isSelected)
String type = (String)table.getModel().getValueAt(row, 0);
setBackground(row % 2 == 0 ? null : Color.LIGHT_GRAY );
if (table.isRowSelected(row) && table.isColumnSelected(column))
setBorder(selected);
return this;
public static void main(String[] args)
TableRowRendering frame = new TableRowRendering();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}Before you make your final decision. What changes would be required for each solution in the following "what if " scenarios:
a) what if, you added a Boolean column to the table
b) what if, you added a second Double column to the table which should be formatted as a currency (ie. 1,234.5 --> $1,234.50).
Here is an example of a currency renderer:
class CurrencyRenderer extends DefaultTableCellRenderer
private NumberFormat formatter;
public CurrencyRenderer()
super();
formatter = NumberFormat.getCurrencyInstance();
setHorizontalAlignment( SwingConstants.RIGHT );
public void setValue(Object value)
if ((value != null) && (value instanceof Number))
value = formatter.format(value);
super.setValue(value);
}Well, here's a partila solution using technique from a link you cited in another thread.
import tests.basic.tables.ColorProvider;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.text.NumberFormat;
public class DecoratedTablePrepareRenderer extends JFrame {
JTable table;
private DefaultTableModel model;
public DecoratedTablePrepareRenderer() {
Object[] columnNames = {"Type", "Company", "Price", "Shares", "Closed"};
Object[][] data =
{"Buy", "IBM", new Double(80.50), new Double(1000), Boolean.TRUE},
{"Sell", "MicroSoft", new Double(6.25), new Double(2000), Boolean.FALSE},
{"Sell", "Apple", new Double(7.35), new Double(3000), Boolean.TRUE},
{"Buy", "Nortel", new Double(20.00), new Double(4000), Boolean.FALSE}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
if (isRowSelected(row))
c.setFont(c.getFont().deriveFont(Font.BOLD));
return c;
ColorProvider prov = new TransactionColorProvider();
ColorTableCellRenderer renderer = new ColorTableCellRenderer(table.getDefaultRenderer(Object.class),prov);
ColorTableCellRenderer boolrenderer = new ColorTableCellRenderer(table.getDefaultRenderer(Boolean.class),prov);
ColorTableCellRenderer doublerenderer = new ColorTableCellRenderer(table.getDefaultRenderer(Double.class),prov);
int priceIndex = model.findColumn("Price");
table.getColumnModel().getColumn(priceIndex).setCellRenderer( new EtchedBorderTableCellRenderer(new ColorTableCellRenderer(new CurrencyRenderer(),prov) ));
table.setDefaultRenderer(Object.class,new EtchedBorderTableCellRenderer(renderer));
table.setDefaultRenderer(Double.class,new EtchedBorderTableCellRenderer(doublerenderer));
table.setDefaultRenderer(Boolean.class, new EtchedBorderTableCellRenderer(boolrenderer));
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
class CurrencyRenderer extends DefaultTableCellRenderer {
private NumberFormat formatter;
public CurrencyRenderer() {
super();
formatter = NumberFormat.getCurrencyInstance();
setHorizontalAlignment(SwingConstants.RIGHT);
public void setValue(Object value) {
if ((value != null) && (value instanceof Number)) {
value = formatter.format(value);
super.setValue(value);
public static void main(String[] args) {
DecoratedTablePrepareRenderer frame = new DecoratedTablePrepareRenderer();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
class ColorTableCellRenderer implements TableCellRenderer{
protected TableCellRenderer delegate;
protected ColorProvider provider;
public ColorTableCellRenderer(TableCellRenderer delegate, ColorProvider provider) {
this.delegate = delegate;
this.provider = provider;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = delegate.getTableCellRendererComponent(table, value,isSelected,hasFocus,row, column);
c.setBackground(provider.getBackgroundColor(row, column));
return c;
class EtchedBorderTableCellRenderer implements TableCellRenderer{
protected TableCellRenderer delegate;
public EtchedBorderTableCellRenderer(TableCellRenderer delegate) {
this.delegate = delegate;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JComponent c = (JComponent)delegate.getTableCellRendererComponent(table, value,isSelected,hasFocus,row, column);
JPanel panel = new JPanel(new GridLayout(0,1));
panel.add(c);
panel.setBorder(BorderFactory.createEtchedBorder());
return panel;
class TransactionColorProvider implements ColorProvider {
private int keyIndex = 0;
private Color sellColor = Color.yellow;
private Color buyColor = Color.green;
public TransactionColorProvider() {
keyIndex = model.findColumn("Type");
public Color getBackgroundColor(int row, int column) {
if( model.getValueAt(row,keyIndex).equals("Sell")){
return sellColor;
else {
return buyColor;
public Color getForegroundColor(int row, int column) {
return Color.black;
}Boolean values are problematical since JCheckBox does seem to like borders, using a panel as I did in the Etched renderer seems to work. This solution need a little more work, this is submitted as a prototype
Cheers
DB -
How to display only Day value instead of DATE in Bex Report
Hi Experts,
We have a Month to date Report, in this report we need to display only day value instead of DATE value,
Like
if Date is 14.05.2010 we need to show only 14
Regards,
ChandraHi ,
Thanks for Quick Response
we does have the option to create the char(calday or ...) value variable replacement with char (calday or ...) info object, we can replace with Report r variable value only not with info object.
i hope we can replace the with info object only with formula variable with replacement.
My BEx Report is Designed like
Columns
0Calday
Rows
Plant
Keyfigures
Actual
Plan
Report output Looks like month to date
0CALDAY 01.06.2010 02.06.2010 03.06.2010
P1 ACTUAL 10 8 4
P1 PLAN 15 6 2
P2 ACTUAL 5 10 7
P2 PLAN 4 8 3
Report should be
0CALDAY 1 2 3
P1 ACTUAL 10 8 4
P1 PLAN 15 6 2
P2 ACTUAL 5 10 7
P2 PLAN 4 8 3
please let me know how can i achive this
Regards
Chandra
Maybe you are looking for
-
How can I add a User to the transport workflow
Hi all, I want to add one user to the transport workflow in BW Dev system? How can I do it, PLEASE. Thanks.
-
I am working on a project where the user enters a year. The string is then converted into an int and goes through a series of tests to see if it is a leap year or not. The problem I am having is when the user inputs letters when they are supposed to
-
Support for Headstart?/FRM-40735 Error
Hello, I am a consultant for Oracle, but I am very new to Oracle Applications and Headstart. I have a client with questions on Headstart, however this is outside the area of expertise of my group. I would like to ask 2 questions: 1. It is my understa
-
I can't load an icon to my application running in my webserver
why I cannot load an icon to my java application (jar application) that is running in my webserver. but the application is running just fine in my desktop. Need help on this. tnx in advance Nashstanley
-
Hd to sd-dvd: even vhs was better
Commercial dvd:s are sd, aren´t they? Still they look brilliant. Normal TV-broadcast is sd. It looks good to me. So: why are my dvd:s worse than my former VHS-tapes? I invested recently in hd-camcorder. I had an optimistic idea: high-quality original