To get the unique id of the selected row in a JTable as in Database
Hi,
After fetching the recodrs from the Database, I have displayed them in a JTable. Though I fetched all the columns from db, I am displying only only 2 columns, say Name and Number neither of which is unique, however I have a unique ID for each record in the db. Now when I select some row in the JTable, I need to know its unique ID (the one which is in the db) which i have not displayed in the JTable.
Is there any API method that can store the unique ids of a table? Or how can this be done?
Thanks in Advance.
Although, if you don't want the Id visible in the table, then you need to remove its TableColumn from the TableColumnModel.
Then when you want to reference the id you need to use:
table.getModel.getValueAt(...);
Similar Messages
-
Getting the Selected Row from a JTable
hi,
how Can i get the Selected row from a JTable
thanks...You know that JTable class? Well, you see those methods in it called "getSelectedRow()" and "getSelectedRows()"...?
-
How to delete the selected rows in a JTable on pressing a button?
How to delete the selected rows in a JTable on pressing a button?
You are right. I did the same.
Following is the code where some of them might find it useful in future.
jTable1.selectAll();
int[] array = jTable1.getSelectedRows();
for(int i=array.length-1;i>=0;i--)
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.removeRow(i);
} -
To change the font of a selected row in a Jtable
Hello,
Is it possible to change the font of a selected row in a jtable?
i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font?
thank you.String will be left justified
Integer will be right justified
Date will be a simple date without the time.
As it will with this renderer.Only if your custom renderer duplicates the code
found in each of the above renderers. This is a waste
of time to duplicate code. The idea is to reuse code
not duplicate and debug again.
No, no, no there will be NO duplicated code.
A single renderer class can handle all types ofdata.
Sure you can fit a square peg into a round hole if
you work hard enough. Why does the JDK come with
separate renderers for Date, Integer, Double, Icon,
Boolean? So that, by default the rendering for common classes is done correctly.
Because its a better design then having code
with a bunch of "instanceof" checks and nested
if...else code.This is only required for customization BEYOND what the default renderers provide
>
And you would only have to use instanceof checkswhen you required custom
rendering for a particular classAgreed, but as soon as you do require custom
renderering you need to customize your renderer.
which you would also have to do with theprepareRenderer calls too
Not true. The code is the same whether you treat
every cell as a String or whether you use a custom
renderer for every cell. Here is the code to make the
text of the selected line(s) bold:
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;
}It will work for any renderer used by the table since
the prepareRenderer(...) method returns a Component.
There is no need to do any kind of "instanceof"
checking. It doesn't matter whether the cell is
renderered with the "Object" renderer or the
"Integer" renderer.
If the user wants to treat all columns as Strings or
treat individual columns as String, Integer, Data...,
then they only need to override the getColumnClass()
method. There is no change to the prepareRenderer()
code.
Have you actually tried the code to see how simple it
is?
I've posted my code. Why don't you post your solution
that will allow the user to bold the text of a Date,
Integer, and String data in separate column and then
let the poster decide.Well, I don't see a compilable, runnable demo anywhere in this thread. So here's one
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Vector;
public class TableRendererDemo extends JFrame{
String[] headers = {"String","Integer","Float","Boolean","Date"};
private JTable table;
public TableRendererDemo() {
buildGUI();
private void buildGUI() {
JPanel mainPanel = (JPanel) getContentPane();
mainPanel.setLayout(new BorderLayout());
Vector headerVector = new Vector(Arrays.asList(headers));
Vector data = createDataVector();
DefaultTableModel tableModel = new DefaultTableModel(data, headerVector){
public Class getColumnClass(int columnIndex) {
return getValueAt(0,columnIndex).getClass();
table = new JTable(tableModel);
// table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
table.setDefaultRenderer(String.class, new MyTableCellRenderer());
table.setDefaultRenderer(Integer.class, new MyTableCellRenderer());
table.setDefaultRenderer(Float.class, new MyTableCellRenderer());
table.setDefaultRenderer(Date.class, new MyTableCellRenderer());
JScrollPane jsp = new JScrollPane(table);
mainPanel.add(jsp, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
private Vector createDataVector(){
Vector dataVector = new Vector();
for ( int i = 0 ; i < 10; i++){
Vector rowVector = new Vector();
rowVector.add(new String("String "+i));
rowVector.add(new Integer(i));
rowVector.add(new Float(1.23));
rowVector.add( (i % 2 == 0 ? Boolean.TRUE : Boolean.FALSE));
rowVector.add(new Date());
dataVector.add(rowVector);
return dataVector;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
TableRendererDemo tableRendererDemo = new TableRendererDemo();
tableRendererDemo.setVisible(true);
SwingUtilities.invokeLater(runnable);
class MyTableCellRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if ( isSelected){
setFont(getFont().deriveFont(Font.BOLD));
else{
setFont(getFont().deriveFont(Font.PLAIN));
if ( value instanceof Date){
SimpleDateFormat formatter =(SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
setText(formatter.format((Date)value));
if(value instanceof Number){
setText(((Number)value).toString());
return this;
}Hardly a "bunch of instanceof or nested loops. I only used the Date instanceof to allow date format to be specified/ modified. If it was left out the Date column would be "18 Apr 2005" ( DateFormat.MEDIUM, which is default).
Cheers
DB -
The columns of a selected row in a JTable
Hello guys,
I am trying to loop through the columns of a selected row in a JTable. Any ideas how i can do that?
Thanks in advance for your replies.
Antana.there is getValueAt(int row, int column) method in JTable.
will this help you?
and please post swing related queries to swing forum.
--Azodious_ -
Reading text file and output (to stdout) a list of the unique words in the
Hi,
I have a main method as
main.java
package se.tmp;
public class Main
public static void main( String[] args )
WordAnalyzer.parse( args[0] );
and text file as
words.txt
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the requirement is like
I need create this WordAnalyzer class, implement the parse method, and then commit the file. This method takes a single parameter, the filename of the file to parse. The method should read this file and output (to stdout) a list of the unique words in the file along with the number of times each appears in the file.
Can anyone please help me on this?
Thanks.Where are you having problems?
-
Error while creating the Unique Index of the Primary Key of an Item
Hi all,
I have deployed a new item (CO_CONTRACTUNIT_PRODUCT) in my publication. The deploy appears to be successfull as the item can be seen in the repository through the Mobile Manager.
The problem occurs when i sync my local DB to get the item offline. While synchronizing, the following error appears, both in the sync window and the log file ol_sync.log.
"ERROR",POL-5130,"11/09/2010 11:43:52","table or view %s.%s not found:CO_CONTRACTUNIT_PRODUCT,CO_CONTRACTID,OD_PRODUCTID,CO_CONTRACTUNITID","DB_ROSHNI"
However, the debug file gives this other error regarding this table.
ALL_INDEX:CREATE UNIQUE INDEX "TPCO_CONTRACTUNIT_PRODUCT_PK" ON CO_CONTRACTUNIT_PRODUCT (CO_CONTRACTID,OD_PRODUCTID,CO_CONTRACTUNITID) -5130Error at C:\ADE\omeprod_ol103021\olite\db\build\win\ocapi\..\..\..\src\ocapi\allindexes.cpp line:329 rc:-5130
Build date Mar 29 2010
okErr=(table or view %s.%s not found)
mess=(CO_CONTRACTUNIT_PRODUCT,CO_CONTRACTID,OD_PRODUCTID,CO_CONTRACTUNITID)
AddLog(-5130 "ERROR",POL-5130,"11/09/2010 11:43:52","table or view %s.%s not found:CO_CONTRACTUNIT_PRODUCT,CO_CONTRACTID,OD_PRODUCTID,CO_CONTRACTUNITID","DB_ROSHNI")
But the index that is being created and is giving the error is the index created automatically with the Primary Key of the table, and so nothing has been modified in that.
The primary key of the table is created with the three columns that are part of the index that is returning the error.
As I could not solve the error, I tried to drop and re-create the item in the repository, but no luck. As a last option, i tried to remove the item from the repository to be able to sync properly again (just like before creating the item), but the error still happens.
Another weird point is that i have tried creating the item in another publication of another database (but with almost equal items), and the item could was downloaded to my local DB without any problem, which makes this problem still more bizarre.
What can it be?
Any help would be great!
Roshnihave you tried unistalling the client and reinstalling it?
schema evolution changes are not always handled correctly please check thread:
Modification of publication item into Mobile Server
i quote from rekounas instructions:
If you are just adding a field, you should only have to run the alter publication item API call.
Here is an old note on schema evolution on different scenarios. The names for the APIs that they use are now deprecated. Use the ConsolidatorManager class and call the method alterPublicationItem("PUBLICATION_ITEM_NAME", "SELECT STMT") :
A) Add column
1. Upload all client data. Clients should not add new data until they are told by the administrator to sync again!!
2. Stop Mobile Server listener
3. Change the Oracle8i/9i database schema (add column)
4. Create a Java program to call the Consolidator Admin API AlterPublicationItem()
5. Start Mobile Server
6. Execute a sync from the client
7. The new column should be seen on the client. Use MSQL to check snapshot definitions.
B) Drop column
1. Upload all client data. Clients should not add new data until they are told by the administrator to sync again!!
2. Stop Mobile Server listener
3. Delete column of the base table in the Oracle database schema
4. Create a Java program to call the Consolidator Admin API DropPublicationItem()
5. Create a Java program to call the Consolidator Admin API CreatePublicationItem() and AddPublicationItem().
6. Start Mobile Server
7. Execute a sync from the client
8. The new column should be seen on the cliet. Use MSQL to check snapshot definitions.
C) Change column datatype
Changing datatypes in a repliatated system is not an easy task. You have to follow certain procedures in order to make it to work. Use DropPublicationItem, CreatePublicationItem and AddPublicationItem methods from the Consolidator Admin API. You must stop/start Mobile Server listener to refresh the cache.
1. Client syncs. Clients should not add new data until they are told by the administrator to sync again!!
2. Stop Mobile Server listener
3. Drop/create column (do not use conversion procudures) at the base table
4. Call DropPublicationItem(). Check if the ErrorQueue and InQueue no longer exist.
5. Call CreatePublicationItem() and AddPublicationItem(). Check if the ErrorQueue and InQueue reflect the new column datatype
6. Start Mobile Server. This automatically resumes application
7. Client executes sync. This should drop the old snapshot and recreate the new snapshot. Use MSQL to check
snapshot definitions.
D) Drop table
1. Client syncs. Clients should not add new data until they are told by the administrator to sync again!!
2. Stop Mobile Server listener
3. Drop base table
4. Call DropPublicationItem(). Check if the ErrorQueue and InQueue no longer exist.
5. Start Mobile Server. This automatically resumes application
6. Client executes sync. This should drop the old snapshot. Use MSQL to check snapshot definitions.
E) Add table
1. Client syncs. Clients should not add new data until they are told by the administrator to sync again!!
2. Stop Mobile Server listener
3. Add new base table
4. Call CreatePublicationItem() and AddPublicationItem() method
5. Start Mobile Server. This automatically resumes application
6. Client executes sync. This should add the new snapshot. Use MSQL to check snapshot definitions.
F) Changing Primary Keys
Chaning PK is a severe operation which must be executed manually. A snapshot must be deleted and recreated to propagate the changes to the clients. This causes a full refresh on this snapshot.
1. Client syncs. Clients should not add new data until they are told by the administrator to sync again!!
2. Stop Mobile Server listener
3. Drop the snapshot using DropPublicationItem() method o
4. Alter the base table
5. Call CreatePublicationItem()and AddPublicationItem() methods for the altered table
6. Start Mobile Server. This automatically resumes application
7. Client executes sync. The old snapshot will be replaced by the new snapstot using a full refresh. Use MSQL to check snapshot definitions.
G) To Change a Table Weight =>
Follow the procedure below to change the Table Weight parameter. The table weight is used by the Mobile Server/Synchronization to determin the sequence in which client records are applied to the Oracle database.
1. Run MGP to apply any changes in the InQueue to the Oracle databse
2. Change table weight using SetTemplateItemMetadata() method
3. Add/change constraint on the the base table which reflects the change in table weight
4. Synchronize
gl m8 -
Overriding the SelectionForegroundColor of a selected row in a JTable
Hi
First, apologize for my poor English.
I looked for a similar topic in the forum, but coudn't find one.
What I want to achieve is this :
upon data contained in a column, I want the foreground color of the row to be gray. To do this, I write my own TableCellRenderer and it works perfectly except for the unique selected row of the table (single selection model) whose foreground color is the table's selectionForegroundColor.
I found a workaround...but the code is awful and leads to OutOfMemoryErrors.
Here is the code :
<
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
boolean isGrayColored = false;
// some process to set whether the foreground color should be gray
if (isGrayColored) {
//table.setSelectionForeground(Color.gray);
setForeground(Color.gray);
} else {
//table.setSelectionForeground(Color.black);
setForeground((isSelected) ? table.getSelectionForeground() : table.getForeground());
if (table != null && value == null && isSelected && hasFocus) {
return this;
} else {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
>
If I uncomment the lines "table.setSelectionForeground(..", I got the expected result.
Thanks for your help
Regards,Try this:
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected && hasFocus) {
setForeground(Color.black);
} else {
setForeground(Color.gray);
setText((value==null)?"":""+value);
return this;
};o)
V.V.
PS: If it helps, don't forget the dukes! -
Override the unique record of the table
friends
i am having a record in the table , and always i want the latest value in the table.
the record is with 4 fields.
mandt primary key
numb primary key
username
date
now in the program i read the numb from the ztable and after reading that
i want to update the field with +1 ie override the old record.
I tried with update and modify statement but they are inserting the new record,
i tried the where clause but that is not working.
when i am using modify statement i am using numb+1 , so it is inserting the new record.
How to handle this situation , please adviceHi,
As Number is primary key, After reading and adding Number then you need to delete the existing latest record and Insert the new record.
For EX
NUM USERNAME
0001 NAREN
0002 SATISH
0003 RAVI
Then last number is 0003 , add 1 then num is 0004.Then delete 0003 RAVI
and add 0004 RAVI
then DATA becomes
NUM USERNAME
0001 NAREN
0002 SATISH
0004 RAVI
Hope this will help you.
Thanks and Regards,
Narendra.Soma -
Selecting rows from a JTable using keys
Hi all, be very grateful for some help on this.
I want to provide functionality in an application where the user will be able to select multiple rows from a JTable by using the page up/ page down button.
Anybody know how this can be done?
ThanksJust add a KeyListener to the table which does what you want on pressing the relevant key.
it seems a bit odd though. If I pressed page up/down in a table I'd expect it to scroll and would be somewhat confused if it started selecting stuff. Generally it's best not to muck around with the default behaviour of UI components. -
Core Data: Get Managed Object by unique part of the objectID
In my Core Data application, I need to get the pointers to different managed objects whose CoreData objectIDs end with the number I provide. e.g.:
Get the Person object whose objectID ends with unique number 317. The whole ID is:
<x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A/Person/p317>
or I need to get Department object, which ends with 5; again full ID is:
<x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A/Department/p5>
These numbers are actually primary keys in the SQLite database's tables and I can see them if I open the database directly with sqlite3, and I can of course select the records using SQL query;
*but I can not figure out how to get these objects using CoreData. I guess I should create the NSPredicate for the fetch request; but I don't know how to write the predicate which will give me the exact object based on the unique part of the objectID*
As I understand, objectIDs are not object's "normal" attributes.
Please help. Thanks in advance.etresoft wrote:
DavidMan wrote:
*but I can not figure out how to get these objects using CoreData. I guess I should create the NSPredicate for the fetch request; but I don't know how to write the predicate which will give me the exact object based on the unique part of the objectID*
I think you are supposed to consider the entire ID to be unique. You can retrieve the associated object using "objectWithID:" from NSManagedObjectContext.
The problem is that I am parsing the text from another application and I have only the "unique part" at hand and not the whole objectID. So, I need to cope with that.
What I see is that the IDs of every entity start with the same text, e.g. here are the IDs of two different entities:
<x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A/Person/p317>
<x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A/Department/p5>
As you see, the difference is only in the end, after the entity names "Paper" and "Department". But this is my case and I am not completely sure that this will hold true for EVERY future installation on any system for every entity.
*Question: will the part like <x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A be constant for the particular installation, for every entity/object?*
If YES, then I will:
- after getting any/first object, extract the non-unique part, i.e. <x-coredata...749A which is the same for every object in this particular installation on this particular computer
- get the unique part, i.e. /Person/p317, /Person/p23, /Department/p5 etc.
- synthesize the "real ID" by appending these two strings
- ask managedObjectContext to return the object with this ID
- continue with the acquired object
How does it sound? Will this work on other computers?
P.S. FYI: the coredata of this program has only one store i.e. all the data are stored in single sqlite file. -
How to get the values of last selected row in Table?
Hi,
I have one editable table , where i have Create, Delete and Commit operation on it.
When i am clicking on Create button it add new row to my table.
But I want the value of my last selected row from the table in my Bean.
Can anyone suggest me please....... its urgent
Jdev:- 11.1.1.0.3
Thanks,
Ramitjust get this code empTable is the table binding
RowKeySet rks = new RowKeySetImpl();
CollectionModel model = (CollectionModel)empTable.getValue();
RowKeySet selectedRowKeys = empTable.getSelectedRowKeys();
if (selectedRowKeys != null)
Iterator iter = selectedRowKeys.iterator();
if (iter != null && iter.hasNext())
empTable.setRowKey(iter.next());
model.setRowIndex(empTable.getRowIndex());
Object key = model.getRowKey();
rks.add(key);
empTable.setSelectedRowKeys(rks);
AdfFacesContext.getCurrentInstance().addPartialTarget(empTable);
public void setEmpTable(RichTable empTable) {
this.empTable = empTable;
public RichTable getEmpTable() {
return empTable;
} -
Adding the unique validation on child vo attribute
Hi, I'm using Jdev 11.1.2.0 I have two tables, master child relationship. In master EO1, I have column Master_Id and in child EO2, I have columns Master_Id, child_id, child_name. i have created the assosiations in beteween EO1 and EO2 with the column Master_Id. and creatd vo's and viewlinks also. and when i drag and drop the master vo and child vo on to the page, if i select master vo first row, the correspodning child records are displayed perfectly. Now I want to apply the unique validation on the child vo columns child_id and child_name. like Child vo data;
Master_Id
Child_Id
Child_name
1
1
A
1
2
B
1
3
C
2
1
A
2
2
B
2
3
C
if I select 1 in master table, then in child table if i create a row and inserting the data, it should check for the duplicate data is there or not under that master_id. I did adding the Custom attribute validation on EO level, like checking the value is existed in the given rowset or not. Instead of adding this custom attibute validation, is there any other way to do it on the EO attribtue level, like selecting the generate unique key constraint. Any suggestion would be appreciated. Thanks.In this car you only can validate using have methods or groovy. Read http://docs.oracle.com/middleware/1212/adf/ADFFD/bcrules.htm#CIHBBDDB for more info about this.
However, if you have the relationship you should have the pk fk too.
Timo -
Print the selected rows in table
Hi All,
I have a one applications which shows the data in table (i.e multiple rows are displayed)
Now from this table user wants to select some selected rows and take the print out of those selected rows
I dont want to take the print out of entire table i want only print out of selected rows
How can we achieve this
Regards
SrinivasHi Srinivas,
I can't think of a way of doing it in VC. However, a kind of workaround can be done in EhP1 where you can export the table to Excel and there you can print whatever you want.
Regards,
Natty -
Changing the background color of the row of the selected cell in table view
How can I change the background color of the table row when user clicks on table cell in table view?
Edited by: a_brar on May 5, 2012 11:12 PMYou could apply the following css style (by defining a custom stylsheet with the following lines and loading it into your app).
The last color sets the background color of the selected row while the table-view has focus (in this case to orange).
.table-view:focused .table-row-cell:filled:focused:selected {
-fx-background-color: -fx-focus-color, -fx-cell-focus-inner-border, orange;
}There are quite a lot of subtleties in the css styling for the tableview (e.g. different colors for the selected row when the control has focus vs when it doesn't or when the user hovers over a selected row in an unfocussed tableview), which you may want to cater for when chaning the background color of the selected row in a table view. There is also alternate styling for when the tableview is in row selection vs cell selection mode. So you may want to look at customizing further based on the css styles in caspian.css in sdk/rt/lib/jfxrt.jar if you can understand the complex css there.
Maybe you are looking for
-
HT1320 iPod Nano 2nd Gen isn't detected by any computer using any cable
Hi all, Discovered a 2nd gen ipod nano while digging out the christmas decorations - it powers up and charges through the cable when plugged into either a power outlet or a computer, but the computer will not detect the device at all. I've tried two
-
My ipod has a white screen, have tried resetting and connecting to itunes, but nothing is working. Pls help
-
Identify high workload from awr report
Hi All, Yesterday, our well-tuned the batch ran very slowly. Most of jobs ran for 30 mins that usually cost 15-20mins. And the colletion of statistics took much longer than before. After reading the awr report, I noticed that all top SQLs didn't belo
-
All my dock settings, background pic, email setup is lost when restarted
I had my computer customized to my preferences such as dock on left side, choosen background pic, i used entourage for email, etc.....i went into finder and under the user name (which has the house icon) i simply changed the name and when i rebooted
-
is there an easy way to convert videos to playon the N95 but still be good quality? (320x240 atleast) Nokia N95-1 v30.0.015