GetSelectedRow( ) for JTable is returning a value of -1?
getSelectedRow( ) for JTable is returning a value of -1?
May I know what is the reason for this and what we can do to rectify it.
I am selecting a row on the GUI side, but this method is returning -1. Post a SSCCE that demonstrates this.
db
Similar Messages
-
In DEV system, this piece of code is working fine. However when it moves to Testing system it dump due to cl_fpm_factory=>get_instance( ) return initial value. What could be the reason for this? Thanks!
data lo_fpm type ref to if_fpm.
lo_fpm = cl_fpm_factory=>get_instance( ).
wd_this->go_message_manager = lo_fpm->mo_message_manager.Hi Anthony,
how sure are you that the DEV and Test system running the same Netweaver SP versions ?. My doubt is that the test system is not NW7.01 (Ehp-1) . Or some thigs are not enabled in the configuration.
Regards
Senthi -
Comma separated values for input and return multiple values
Hello everyone,
I have this simple package. Can someone suggest a way to accept multiple empno as input (comma separated) and to return set of salary values for the set of employee numbers (compatible to work with lower Oracle versions). Thanks much!
CREATE OR REPLACE PACKAGE test_multi IS
FUNCTION GET_sal(P_empno IN emp.empno%TYPE) RETURN NUMBER;
END test_multi;
CREATE OR REPLACE PACKAGE BODY test_multi IS
FUNCTION GET_sal(P_empno IN emp.empno%TYPE) RETURN NUMBER IS
V_sal NUMBER(10,2);
MSG VARCHAR2(200);
BEGIN
SELECT sal
INTO V_sal
FROM emp
WHERE empno = p_empno;
RETURN V_sal;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No data found.');
IF (V_sal IS NULL OR V_sal = 0) THEN
V_sal := 0;
END IF;
RETURN V_sal;
WHEN OTHERS THEN
MSG := SUBSTR(SQLERRM, 1, 70);
DBMS_OUTPUT.PUT_LINE(MSG);
END GET_sal;
END test_multi; -- End packageA way to do this in 10g or above...
SQL> ed
Wrote file afiedt.buf
1 with e as (select '7499,7698,7654,7902' as enos from dual)
2 --
3 select empno, sal
4 from emp
5 where empno in (select regexp_substr(enos,'[^,]+',1,rownum)
6 from e
7* connect by rownum <= length(regexp_replace(enos,'[^,]'))+1)
SQL> /
EMPNO SAL
7902 3000
7698 2850
7654 1250
7499 1600
SQL>As for Oracle 8, .... well.... like Oracle, I no longer use unsupported versions, so I'd recommend you upgrade to something that is supported. -
XDisplayHeight for Trusted JDS returning correct value?
Does XDisplayHeight for Trusted JDS take into account the trusted path security bar?
This applies to developing applications on Trusted JDS in Solaris 10 5/08 x86 with Trusted Extensions. The XDisplayHeight returns two different values for Trusted CDE and Trusted JDS. The values are:
1024 x 744 for Trusted CDE
1024 x 768 for Trusted JDS
It seems that XDisplayHeight in TJDS does not subtract the trusted path bar height from the total. Is this correct. Is this associated with the fact that the trusted path bar should always be on top?
Thank you
Josh
Edited by: fcbseci on Oct 6, 2008 9:35 AMThis issue has been answered here: http://www.opensolaris.org/jive/thread.jspa?threadID=77800&tstart=0. The following bugs are also associated with this issue. Sun has been working this issue for some time now however a final decision has not be made on how to resolve it.
6607645 [tjds] trusted stripe can sometimes cover the panel on logging into tjds
6700652 [tjds][vermillion] trusted stripe moves to bottom of screen on changing screen resolution
6617487 [nevada] trusted stripe disappears on changing resolution
6699741 [vermillion tjds] creating new panel disappears behind stripe, cannot be moved
6573285 TJDS Trusted Stripe should be at the bottom of the screen (configurable)
Thanks Josh -
What is the reson for Fun SAP_WAPI_WORKITEMS_TO_OBJECT returns no value
Hi All
call function 'SAP_WAPI_WORKITEMS_TO_OBJECT'
EXPORTING
objtype = 'ZAR'
objkey = v_objkey
top_level_items = c_set
selection_status_variant = 0001
text = c_set
language = sy-langu
TABLES
worklist = i_worklist
message_lines = i_message_lines.
I am using Function SAP_WAPI_WORKITEMS_TO_OBJECT by passing object type and object key and looking for top level items . I get values for i_worklist[] all the time but for one AR i dont see a value in i_worklist[] .
I know that Functional ppl had messed up with the workflow status in IMA2N transaction by changing the status....
I want to know what is the reason for not getting any value in i_worklist[] for some ARS and works fine for other ARS.
I can see the work id in workflow header table but i dont get workid when i use this function .
Could you all tell me whats the reason for not getting ,i appreciate all your help
ThanksWith parameter selection_status_variant = 0001, you will only get a list of active instances.
The parameter can have the following values:
0000 All Instances
0001 Active Instances (Running, Ready, Committed,...)
0002 Finished Instances (Completed, Cancelled)
0003 Active Instances (All)
Cheers,
Ramki Maley. -
How to return multiple values in a single field in oracle 10g reports
I have written a formula column using cursor for loop which returns 3 values. But whenever i am assigning the formula column as the source of a field which is inside a repeating frame the field in only showing the first value returned from the formula column. The rest two values are not shown. Please help what to do.
User11238124 (please include your name)
If I understand your issue, you should set the vertical elasticity of the repeating frame to 'Variable' or 'Expand'. It is likely set to 'Fixed'.
Hope this helps,
Monty -
Return multiple values for the popup LOV
Hi folks,
I have one challange. I have a search engine and there is an popup lov and its having three Display and 3 Retun value such as
select
p.A || ', ' || pi.B|| ', ' || km.C|| ' ' d, p.A || ', ' || pi.B|| ', ' || km.C|| ' ' r
from tableA km,tableB p,tableC pi
where km.col1=p.id and km.col1=pi.id and km.C is not null
when i click on the pop lov it will display 3 values shuch as SAP+DBA+HR and in popup lov iteam its will return 3 values
such as SAP+DBA+HR this return values are from 3 cloumn names from same table ie. A column, B column, C column
and when i click on submit button this return values from 3 columns values should assign to the 3 column such as
A=SAP, B=DBA and C=HR and search fetchs the result in a Report.
Its some thing new, is it possible..:)
ok will be waiting for your reply..:D
Regards,
Suri
Edited by: user634694 on Feb 25, 2009 3:14 AMHi Varad,
am facing problems i wrote dynamic sql its working fine for 2 and 3 fields like (SAP+ORCL) and (SAP+ORCL+HRA) but for the single value like SAP the results are not comming properly. my code is
If (:P25_TEST Is not Null ) THEN
V_Sql := V_Sql||q'!
And
(multipleInstr1(R.Pillar,:P25_TEST)>0 )
or INSTR ( '+' || Upper(:P25_TEST) || '+', Upper(R.Pillar))>0 ) and
((multipleInstr1(R.Product_Line,:P25_TEST)>0 )
or INSTR ( '+' || Upper(:P25_TEST) || '+', Upper(R.Product_Line))>0) and
((multipleInstr1(R.Category,:P25_TEST)>0 ) or (R.Category is null)
or INSTR ( '+' || Upper(:P25_TEST) || '+', Upper(R.Category))>0 )
End If;
where multipleInstr1 is a function created to search results even its delimited by '+' it ignors '+' delimiter and
:p25_test is the popup iteam which takes values like SAP+ORCL+HRA or SAP+ORCL or SAP how its possible to get this results.
Its turning too complicated for cheking condetion for a single popup iteam, can we get any solution for this or not..
Hope will do respond
Thanks and Regards,
Suri -
Pl/sql package for use with workflow will not return a value
hi all,
just trying to intercept a requisition being turned into an order if it uses a certain cost code. so i have amended the workflow and created a package to check what cost centre a requisition is using. how over the workflow stops on the function that calls the package witha a status of complete as if the package is not returning any values.
the package is as below:
CREATE OR REPLACE PACKAGE APPS.xxhccWFcapitalcheck AS
procedure XXHCC_CHECK_CAPITAL(itemtype in varchar2,
itemkey in varchar2,
actid in number,
funcmode in varchar2,
resultout out NOCOPY vARCHAR2);
END xxhccWFcapitalcheck;
CREATE OR REPLACE PACKAGE BODY APPS.xxhccWFcapitalcheck AS
procedure XXHCC_CHECK_CAPITAL(itemtype in varchar2,
itemkey in varchar2,
actid in number,
funcmode in varchar2,
resultout out NOCOPY varchar2 ) is
x_progress varchar2(100);
x_resultout varchar2(30);
l_doc_mgr_return_val VARCHAR2(1);
l_doc_string varchar2(200);
l_preparer_user_name varchar2(100);
doc_manager_exception exception;
p_test varchar2(100);
l_req_id varchar2(30);
CURSOR p_line_id IS
SELECT
codes.segment2 cost_center
FROM
po_requisition_headers_all headers,
po_requisition_lines_all lines,
po_req_distributions_all dist,
gl_code_combinations_v codes
WHERE
headers.requisition_header_id = lines.requisition_header_id
AND
lines.requisition_line_id = dist.requisition_line_id
AND
dist.code_combination_id = codes.code_combination_id
AND
headers.segment1 = l_req_id;
line_rec p_line_id%rowtype;
BEGIN
-- Do nothing in cancel or timeout mode
--if (funcmode <> wf_engine.eng_run) then
-- resultout := wf_engine.eng_null;
-- return;
-- end if;
l_req_id := wf_engine.GetItemAttrNumber (itemtype => itemtype,
itemkey => itemkey,
aname => 'DOCUMENT_NUMBER');
--FOR line_rec in p_line_id
---loop
open p_line_id;
fetch p_line_id into l_doc_string;
close p_line_id;
IF p_line_id= 'Q9DEF'
dbms_output.put_line p_line_id;
Then resultout := 'COMPLETE:F';
return;
p_test := 'USE DIFFERENT CODE';
ELSE
resultout := 'COMPLETE:T';
return;
END IF;
END LOOP;
end;
END xxhccWFcapitalcheck;
any help would be great!Hi Community, first of all, english is not my native language and im not sure to use the correct terms for PowerCenter - so if im wrong please help me correct and make clear what we need. We have a kind of 3-steps ToDo. First step: Load data from an external source into a "local" datastore (its an oracle db on a server in our "hands")Second step: Check data against several verifications, this is done with a PL/SQL Package. The PL/SQL Package shall be called with an Interfacename who is set in the First PowerCenter Mapping. Our current thoghts are to do this via a stored procedure, which runs as "Target Post Load" and gets a variable "Interface Name".Is that possible? Im not quite sure about it. About the last part its even more unclear how we can solve it:Third part should be switch back to PowerCenter now - and the package (or to be correct a function in the package) should return a value for "okay everything fine => workflow continue" or "something happened => workflow is stopped" Im not sure how i can handle this. I hope my explanations are good enough so you can provide some help?!If there are any questions please ask! Thank you alot, best regards, Christian
-
Will a sequence return same value for two different sessions?
Is there a possibility that a sequence will return same value to two different sessions when it is referred exactly at the same instance of time?
@Justin... Thanks for your insight; indeed, we too feel this shouldn't ever happen and never heard of it either, but there it is. (No, we haven't logged a TAR yet -- whatever that is -- partly because it didn't occur to us and partly because we only recently came across the issue and sensibly want to do some testing before we cry foul.)
However, the code is pretty straight-forward, much like this (inside a FOR EACH ROW trigger body):
SELECT <seqname>.NEXTVAL INTO <keyvar> FROM DUAL;
INSERT INTO <tblname> (<keyfield>, <... some other fields>)
VALUES(<keyvar>, <... some other values> );
(where <tblname> is NOT the table on which the trigger is fired). This is the only place where the sequence is ever accessed. The sequence state is way below its limits (either MAXVALUE or <keyfield>/<keyvar> datatype size).
In this setup, end users sometimes got an out-of-the-blue SQL error to the effect that uniqueness constraint has been violated -- as I said, we used to have a unique index on <keyfield> -- which leads us to assume that the sequence generated a duplicate key (only way for the constraint to be violated, AFAIK). We released the constraint and indeed, using a simple SELECT <keyfield>, COUNT(*) FROM <tblname> GROUP BY <keyfield> HAVING COUNT(*)>1 got us some results.
Unfortunately, the <tblname> table gets regularly purged by a consumer process so it's hard to trace; now we created a logger trigger, on <tblname> this time, which tracks cases of duplicate <keyfield> inserts... We'll see how it goes.
@Laurent... winks at the CYCLE thing Our sequence is (needless to say) declared as NOCYCLE and the datatype is large enough to hold MAXVALUE. -
Revision: 18471
Revision: 18471
Author: [email protected]
Date: 2010-11-05 10:22:11 -0700 (Fri, 05 Nov 2010)
Log Message:
bug fix for 2749575 The API -- mx.messaging.messages.MessagePerformanceUtils; associated attributes/properties like totalTime are returning negative values
Change adding set method for receive time to avoid it override the value set by detecting it is an OUT infoType
BlazeDS checkintests pass
Modified Paths:
flex/sdk/branches/3.x/frameworks/projects/rpc/src/mx/messaging/messages/MessagePerformanc eInfo.asDear Pallavi,
Very useful post!
I am looking for similar accelerators for
Software Inventory Accelerator
Hardware Inventory Accelerator
Interfaces Inventory
Customization Assessment Accelerator
Sizing Tool
Which helps us to come up with the relevant Bill of Matetials for every area mentioned above, and the ones which I dont know...
Request help on such accelerators... Any clues?
Any reply, help is highly appreciated.
Regards
Manish Madhav -
Hello,
I have a report that uses apex_item.checkbox(...) to generate checkbox. This report correctly displays a checkbox for each row. The source code generated in the html page is:
<input type="checkbox" name="f01" value="202" id="P1_CHECKBOX" />
<input type="checkbox" name="f01" value="220" id="P1_CHECKBOX" />
<input type="checkbox" name="f01" value="210" id="P1_CHECKBOX" />
I want to use the javascript function $v() to get the values of the checked checkbox. I thought that this function return the values of all the checked checkbox separated by ':' but I notice that my code alert($v('P1_CHECKBOX')); returns each time only the value of the first checkbox if it is checked.
It returns '202' if the first checkbox is checked but nothing if only the second checkbox is checked and '202' if the first and second checkbox are checked.Hi,
first of all, $v, $x and $s are suppose to only work for page items and not for tabular form columns or manually generated HTML elements.
Second, I think your HTML code is not correct, because each of your checkboxes has the same ID. But the ID has to be unique in the browser DOM tree. So the different checkbox elements should actually be named P1_CHECKBOX_1 .. P1_CHECKBOX_3. Just have a look what is actually generated for a real checkbox page item. BTW, I think you shouldn't name these checkbox elements like a page item, because they are actually not page items. I think that could be confusing for other developers.
Hope that helps
Patrick
My Blog: http://www.inside-oracle-apex.com
APEX 4.0 Plug-Ins: http://apex.oracle.com/plugins
Twitter: http://www.twitter.com/patrickwolf -
Hi how will get subquery returns multiple values for main query
Hi all ;
here i given one sql query
1)select decode(a.FLG,'Y','yes','N','no','null')||'] '||a.p_type||' : '|| initcap(replace(substr(b.mgr,0,instr(b.mgr,'@')-1),'.',' '))||' - '||
b.name||' ('|| substr(a.name,0,instr(a.name,'-')-1)||')'
from table1 a
join table3 c on c.emptype = a.emptype
left outer join table2 b on a.name = b.name
where a.mgrid = 100;
if i run this above query returning multiple values depend on sa.mgr values.
like output coming like this
yes:2000-anbarasan
yes:2700-anb
yes:2000-rasan
yes:2807-anbarasan
yes:2700-anbanu
yes:2000-null
2) this sub query i am passing with main query
select sa.mgrid,sa.sal,(select decode(a.FLG,'Y','yes','N','no','null')||'] '||a.p_type||' : '||
initcap(replace(substr(b.mgr,0,instr(b.mgr,'@')-1),'.',' '))||' - '||
b .name||' ('|| substr(a.name,0,instr(a.name,'-')-1)||')'
from table1 a
join table3 c on c.emptype = a.emptype
left outer join table2 b on a.name = b.name
where a.mgrid = 100)" test " from table4 sa,table5 te ,table6 ft where sa.id(+)=te.id and sa.mgr=ft.mgr;
my final out put required like this:
mgrid sal test
100 20000 yes:2000-anbarasan
yes:2700-anb
yes:2000-rasan
yes:2807-anbarasan
yes:2700-anbanu
yes:2000-null
but i am getting erro:
1)missing paranths
2)single row subquery return more then one row.
hi kindly give me answer to me as soon as possible
Edited by: anbarasan on Sep 29, 2008 9:48 PMI refuse to read all of that code and guess what error message you are getting. Apparently others feel the same way.
Run the final SQL statement and then cut and paste the code and full error statement into a post.
Also include your full version number to three decimal places.
My refusal is not an unwillingness to help you but rather an unwillingness to spend 10 minutes reconstructing what you could have pasted in in a fraction of a second. We are all volunteers here and there are many people that need help. I hope you understand. -
firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
* Created on 03-Aug-2005
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
* @author Administrator
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import java.io.*;
public class NodesTable extends JFrame implements TableModelListener, ActionListener {
JTable jt;
DefaultTableColumnModel dtcm;
TableColumn column[] = new TableColumn[100];
DefaultTableModel dtm;
JLabel Name,m1,w1,m2,w2;
JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
float x=0,y=0,tMark=0,z = 0;
float j=0;
int i;
JButton DelButton;
JButton AddButton;
JScrollPane scrollPane;
JPanel mainPanel,buttonPanel;
JFrame frame;
Object[][] data =
{"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
{"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
{"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
{"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
public NodesTable() {
super("Student Marking Spreadsheet");
this.AddNodesintoTable();
setSize(400,250);
setVisible(true);
public void AddNodesintoTable(){
// Create a vector object and load them with the data
// to be placed on each row of the table
dtm = new DefaultTableModel(data,c);
dtm.addTableModelListener( this );
jt = new JTable(dtm){
// 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();
// The Cost is not editable
public boolean isCellEditable(int row, int column)
int modelColumn = convertColumnIndexToModel( column );
return (modelColumn == 5) ? false : true;
//****************************User Input**************************
//Add another node
//Creating and setting the properties
//of the panel's component (panels and textfields)
Name = new JLabel("Name");
Name.setForeground(Color.black);
m1 = new JLabel("Mark1");
m1.setForeground(Color.black);
w1 = new JLabel("Weigth1");
w1.setForeground(Color.black);
m2= new JLabel("Mark2");
m2.setForeground(Color.black);
w2 = new JLabel("Weight2");
w2.setForeground(Color.black);
NameTF = new JTextField(5);
NameTF.setText("Node");
m1TF = new JTextField(5);
w1TF = new JTextField(5);
m2TF=new JTextField(5);
w2TF=new JTextField(5);
//creating the buttons
JPanel buttonPanel = new JPanel();
AddButton=new JButton("Add Row");
DelButton=new JButton("Delete") ;
buttonPanel.add(AddButton);
buttonPanel.add(DelButton);
//adding the components to the panel
JPanel inputpanel = new JPanel();
inputpanel.add(Name);
inputpanel.add(NameTF);
inputpanel.add(m1);
inputpanel.add(m1TF);
inputpanel.add(w1);
inputpanel.add(w1TF);
inputpanel.add(m2);
inputpanel.add(m2TF);
inputpanel.add(w2TF);
inputpanel.add(w2);
inputpanel.add(AddButton);
inputpanel.add(DelButton);
//creating the panel and setting its properties
JPanel tablepanel = new JPanel();
tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
getContentPane().add(tablepanel, BorderLayout.CENTER);
getContentPane().add(inputpanel, BorderLayout.SOUTH);
//Method to add row for each new entry
public void addRow()
Vector r=new Vector();
r=createBlankElement();
dtm.addRow(r);
jt.addNotify();
public Vector createBlankElement()
Vector t = new Vector();
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
return t;
// Method to delete a row from the spreadsheet
void deleteRow(int index)
if(index!=-1) //At least one Row in Table
dtm.removeRow(index);
jt.addNotify();
// Method that adds and deletes rows
// from the table by pressing the
//corresponding buttons
public void actionPerformed(ActionEvent ae){
Float z=new Float (m2TF.getText());
String Name= NameTF.getText();
Float x= new Float(m1TF.getText());
Float y= new Float(w1TF.getText());
Float j=new Float (w2TF.getText());
JFileChooser jfc2 = new JFileChooser();
String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
String.valueOf(z),String.valueOf(j)};
Object source = ae.getSource();
if(ae.getSource() == (JButton)AddButton)
addRow();
if (ae.getSource() ==(JButton) DelButton)
deleteRow(jt.getSelectedRow());
//method to calculate the total mark in the TotalMark column
//that updates the values in every other column
//It takes the values from the column 1,2,3,4
//and changes the value in the column 5
public void tableChanged(TableModelEvent e) {
System.out.println(e.getSource());
if (e.getType() == TableModelEvent.UPDATE)
int row = e.getFirstRow();
int column = e.getColumn();
if (column == 1 || column == 2 ||column == 3 ||column == 4)
TableModel model = jt.getModel();
float q= ((Float)model.getValueAt(row,1)).floatValue();
float w= ((Float)model.getValueAt(row,2)).floatValue();
float t= ((Float)model.getValueAt(row,3)).floatValue();
float r= ((Float)model.getValueAt(row,4)).floatValue();
Float tMark = new Float((q*w+t*r)/(w+r) );
model.setValueAt(tMark, row, 5);
// Which cells are editable.
// It is only necessary to implement this method
// if the table is editable
public boolean isCellEditable(int row, int col)
{ return true; //All cells are editable
public static void main(String[] args) {
NodesTable t=new NodesTable();
}There are too many mistakes in your program. It looks like you are new to java.
Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
Here is the updated code: Do the diff and u will know my changes
* Created on 03-Aug-2005
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
* @author Administrator
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
public class NodesTable extends JFrame implements TableModelListener,
ActionListener {
JTable jt;
DefaultTableColumnModel dtcm;
TableColumn column[] = new TableColumn[100];
DefaultTableModel dtm;
JLabel Name, m1, w1, m2, w2;
JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
"TotalMark" };
float x = 0, y = 0, tMark = 0, z = 0;
float j = 0;
int i;
JButton DelButton;
JButton AddButton;
JScrollPane scrollPane;
JPanel mainPanel, buttonPanel;
JFrame frame;
public NodesTable() {
super("Student Marking Spreadsheet");
this.AddNodesintoTable();
setSize(400, 250);
setVisible(true);
public void AddNodesintoTable() {
// Create a vector object and load them with the data
// to be placed on each row of the table
dtm = new DefaultTableModel(c,0);
dtm.addTableModelListener(this);
jt = new JTable(dtm) {
// The Cost is not editable
public boolean isCellEditable(int row, int column) {
int modelColumn = convertColumnIndexToModel(column);
return (modelColumn == 5) ? false : true;
//****************************User Input**************************
//Add another node
//Creating and setting the properties
//of the panel's component (panels and textfields)
Name = new JLabel("Name");
Name.setForeground(Color.black);
m1 = new JLabel("Mark1");
m1.setForeground(Color.black);
w1 = new JLabel("Weigth1");
w1.setForeground(Color.black);
m2 = new JLabel("Mark2");
m2.setForeground(Color.black);
w2 = new JLabel("Weight2");
w2.setForeground(Color.black);
NameTF = new JTextField(5);
NameTF.setText("Node");
m1TF = new JTextField(5);
w1TF = new JTextField(5);
m2TF = new JTextField(5);
w2TF = new JTextField(5);
//creating the buttons
JPanel buttonPanel = new JPanel();
AddButton = new JButton("Add Row");
AddButton.addActionListener(this);
DelButton = new JButton("Delete");
DelButton.addActionListener(this);
buttonPanel.add(AddButton);
buttonPanel.add(DelButton);
//adding the components to the panel
JPanel inputpanel = new JPanel();
inputpanel.add(Name);
inputpanel.add(NameTF);
inputpanel.add(m1);
inputpanel.add(m1TF);
inputpanel.add(w1);
inputpanel.add(w1TF);
inputpanel.add(m2);
inputpanel.add(m2TF);
inputpanel.add(w2TF);
inputpanel.add(w2);
inputpanel.add(AddButton);
inputpanel.add(DelButton);
//creating the panel and setting its properties
JPanel tablepanel = new JPanel();
tablepanel.add(new JScrollPane(jt,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
getContentPane().add(tablepanel, BorderLayout.CENTER);
getContentPane().add(inputpanel, BorderLayout.SOUTH);
//Method to add row for each new entry
public void addRow() {
Float z = new Float(m2TF.getText());
String Name = NameTF.getText();
Float x = new Float(m1TF.getText());
Float y = new Float(w1TF.getText());
Float j = new Float(w2TF.getText());
String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
String.valueOf(z), String.valueOf(j) };
dtm.addRow(newdata);
// Method to delete a row from the spreadsheet
void deleteRow(int index) {
if (index != -1) //At least one Row in Table
dtm.removeRow(index);
jt.addNotify();
// Method that adds and deletes rows
// from the table by pressing the
//corresponding buttons
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (ae.getSource() == (JButton) AddButton) {
addRow();
if (ae.getSource() == (JButton) DelButton) {
deleteRow(jt.getSelectedRow());
//method to calculate the total mark in the TotalMark column
//that updates the values in every other column
//It takes the values from the column 1,2,3,4
//and changes the value in the column 5
public void tableChanged(TableModelEvent e) {
System.out.println(e.getSource());
//if (e.getType() == TableModelEvent.UPDATE) {
int row = e.getFirstRow();
int column = e.getColumn();
if (column == 1 || column == 2 || column == 3 || column == 4) {
TableModel model = jt.getModel();
float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
Float tMark = new Float((q * w + t * r) / (w + r));
model.setValueAt(tMark, row, 5);
// Which cells are editable.
// It is only necessary to implement this method
// if the table is editable
public boolean isCellEditable(int row, int col) {
return true; //All cells are editable
public static void main(String[] args) {
NodesTable t = new NodesTable();
} -
Can You Help Me ABout getSelectedRow in JTable
Can you help me on how to solve my problem about the getSelectedRow .....
I have one JComboBox and a SearchButton
... Once I selected an Item in a JComboBox, I will press the SearchButton
and then it will look up to the database and display it in the JTable..........
i used the getSelectedRow to print the value that I selected in the table...
like this...
public void mouseClicked(MouseEvent e) {
// Ilabas yung form
if(e.getClickCount() == 1 ) {
System.out.println(table1.getSelectedRow());
In the first press in the SearchButton and then clicking the row
, It will print the selected row...... but when i press again the SearchButton then clicking a row again........
there is a problem occured....... selectedRow is always -1, can you help me to solve this.....import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;
import javax.swing.plaf.metal.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.text.*;
import java.beans.*;
public class OpenProject extends JDialog {
ResultSet rs, rs1, rs2, rs3;
JFrame JFParentFrame; // create a JFrame
JFrame OwnerFrame; // create a JFrame
public JLabel proj_name;
public JLabel proj = new JLabel("Project Name:");
public JLabel form = new JLabel("Form Name");
public JLabel lang = new JLabel("Language");
public JComboBox form_lang = new JComboBox();
public JComboBox form_name = new JComboBox();
public JButton edit = new JButton("Edit");
public JButton reload = new JButton("Search");
public JButton def = new JButton("Set Text Default");
public JButton langs = new JButton("Add Language");
public JButton exit = new JButton("Exit");
public JPanel panel1 = new JPanel ();
public JTable table1, table2, table3,table4;
public JScrollPane scrollPane1, scrollPane2, scrollPane3, scrollPane4;
public JTabbedPane UITab,UITab1;
Container c = getContentPane();
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
public String column[][];
public String strRow;
public String strCol;
public String strForm;
public String strGetProj_id;
public String strForm_lang;
public String strForm_name;
private boolean DEBUG = false;
public int getLang;
public int getForm;
public int getDef_id;
public int count2 = 0,count3 = 0,count4 = 0;
public int row2 = 0,row3 = 0,row4 = 0;
public int selectedRow1 = 0, selectedRow2 = 0;
public DbBean db = new DbBean();
public OpenProject(JFrame OwnerForm, String getProj_id) {
super(OwnerForm,true);
strGetProj_id = getProj_id;
try{
db.connect();
} catch(SQLException sqlex) {
} catch(ClassNotFoundException cnfex) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
// Para ito sa paglalagay sa dalawang combo box ng value.......
try {
rs = db.execSQL("Select * from mst_form where form_proj_id = "+strGetProj_id+"");
while(rs.next()) {
form_name.addItem(rs.getString("form_name"));
//System.out.println(strForm);
} catch(SQLException sqlex) {
try {
rs = db.execSQL("Select distinct from mst_form where form_proj_id = "+strGetProj_id+"");
while(rs.next()) {
form_name.addItem(rs.getString("form_name"));
//System.out.println(strForm);
} catch(SQLException sqlex) {
try {
int counts;
rs = db.execSQL("Select * from mst_project where proj_id = "+strGetProj_id+"");
while(rs.next()) {
counts = rs.getInt("proj_lang_id");
System.out.println(counts);
rs1 = db.execSQL("Select * from mst_language where lang_id = "+counts+"");
while (rs1.next()) {
form_lang.addItem(rs1.getString("lang_name"));
} catch(SQLException sqlex) {
edit.setActionCommand("edit");
edit.addActionListener(actions);
reload.setActionCommand("load");
reload.addActionListener(actions);
def.setActionCommand("default");
def.addActionListener(actions);
langs.setActionCommand("lang");
langs.addActionListener(actions);
exit.setActionCommand("exit");
exit.addActionListener(actions);
proj_name = new JLabel();
proj_name.setBackground(new Color(255,255,255));
form_name.setMaximumRowCount(5);
form_name.setBackground(new Color(255,255,255));
form_lang.setMaximumRowCount(5);
form_lang.setBackground(new Color(255,255,255));
proj.setBounds(20, 20,100,20);
proj_name.setBounds(120, 20,250,20);
form.setBounds(20, 50,100,20);
form_name.setBounds(120, 50,150,20);
lang.setBounds(300, 50,100,20);
form_lang.setBounds(380, 50,150,20);
reload.setBounds(560,50,80, 20);
edit.setBounds(110,360,115,20);
def.setBounds(230,360,115,20);
langs.setBounds(350,360,115,20);
exit.setBounds(470,360,115,20);
panel1.add(getTable());
panel1.setLayout(null);
panel1.setBackground(Color.white);
panel1.add(proj);
panel1.add(proj_name);
panel1.add(form);
panel1.add(form_name);
panel1.add(lang);
panel1.add(form_lang);
panel1.add(reload);
panel1.add(def);
panel1.add(langs);
panel1.add(exit);
panel1.add(edit);
c.add(panel1);
setSize(680,420);
setTitle("Open Project");
setLocation((screen.width - 590)/2,((screen.height - 280)/2) - 45);
public JTabbedPane getTable() {
UITab = new JTabbedPane();
strForm_lang = form_lang.getSelectedItem().toString();
strForm_name = form_name.getSelectedItem().toString();
int count1=0;
int row1=0;
try {
rs = db.execSQL("Select * from mst_default where def_proj_id = '"+strGetProj_id+"' AND def_category = 'Title'" );
while(rs.next()) {
count1 += 1;
getDef_id = rs.getInt("def_id");
column = new String[count1][2];
rs1 = db.execSQL("Select form_id from mst_form WHERE form_name = '"+strForm_name+"'");
while(rs1.next()) {
getForm = rs1.getInt("form_id");
System.out.println("getForm");
rs2 = db.execSQL("Select lang_id from mst_language WHERE lang_name = '"+strForm_lang+"'");
while(rs2.next()) {
getLang = rs2.getInt("lang_id");
System.out.println("getLang");
rs3 = db.execSQL("Select * from mst_default a, mst_translation b WHERE a.def_form_id = '"+getForm+"' AND b.trans_lang_id = '"+getLang+"' AND a.def_proj_id = '"+strGetProj_id+"' AND b.trans_def_id = '"+getDef_id+"' AND a.def_category = 'Title' " );
while(rs3.next()) {
column[row1][0] = "" + rs3.getString("display_name"); // rowNum ay kung ilan ang row na ilalabas
column[row1][1] = "" + rs3.getString("translation"); // Default yung isang array ng column ko, kaya fixed
row1++;
row1 = 0;
} catch(SQLException sqlex) {
sqlex.printStackTrace();
System.exit(1);
// End
table1 = new JTable(new MyTableModel()){
scrollPane1 = new JScrollPane(table1);
UITab.setBounds(30,100,610,250);
UITab.add("Title",scrollPane1);
return UITab;
class MyTableModel extends AbstractTableModel {
// Pagawa ng header Coloumn
String ColumnHeaderName[] = {
"Default Text",""+strForm_lang+" Translation"
//End
public int getColumnCount() {
//System.out.println("The Column Count is" + ColumnHeaderName.length);
return ColumnHeaderName.length;
public int getRowCount() {
//System.out.println("The Row Count is" + column.length);
return column.length;
public String getColumnName(int col) {
//System.out.println("The Column Name is" + ColumnHeaderName[col]);
return ColumnHeaderName[col];
public Object getValueAt(int row,int col) {
System.out.println("The value at row and column = " + column[row][col]);
return column[row][col];
public int getSelectedRow() {
System.out.println("Integer" + column.length);
return column.length;
ActionListener actions = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String source = ae.getActionCommand();
if (source == "load") {
table1.clearSelection();
panel1.add(getTable());
table1.addNotify();
repaint();
} else if (source == "default") {
dispose();
TextDefaultForm form = new TextDefaultForm(OwnerFrame,JFParentFrame);
form.setVisible(true);
} else if (source == "lang") {
dispose();
CreateProject lang = new CreateProject(JFParentFrame);
lang.setVisible(true);
} else if (source == "exit") {
dispose();
} else if (source == "edit") {
if (table1.getValueAt(table1.getSelectedRow(),table1.getSelectedColumn()) != null){
formLang lang = new formLang(OwnerFrame,strCol,strRow, strGetProj_id);
lang.setVisible(true);
MouseListener MouseTableListener = new MouseListener() {
public void mouseClicked(MouseEvent e) {
// Ilabas yung form
if(e.getClickCount() == 2 ) {
dispose();
int col_a = 0;
int col_b = 1;
selectedRow1 = table1.getSelectedRow();
Object objColumn1 = table1.getValueAt(selectedRow1, col_a);
Object objRow1 = table1.getValueAt(selectedRow1, col_b);
strCol = objColumn1.toString();
strRow = objRow1.toString();
formLang lang = new formLang(OwnerFrame,strCol,strRow,strGetProj_id);
System.out.println(selectedRow1);
System.out.println(strCol);
System.out.println(strRow);
lang.txtProj.setText(strCol);
lang.txtLang.setText(strRow);
lang.show();
} else if (e.getClickCount() == 1) {
table1.setSelectionBackground(Color.blue);
table1.setColumnSelectionAllowed(false);
table1.setRowSelectionAllowed(true);
table1.setFocusable(true);
int a = table1.getRowCount();
System.out.println("Row Count = " + a);
int sel = table1.getSelectedRow();
//if (sel == -1) return;
System.out.println("Selected Row = " + sel);
System.out.println(table1.isRowSelected(sel));
public void mouseReleased(MouseEvent e) {
public void mouseExited(MouseEvent e) {
public void mouseEntered(MouseEvent e) {
public void mousePressed(MouseEvent e) {
//public static void main(String leo[]) {
//OpenProject open = new OpenProject();
} -
Must click then click and drag for JTable Drag and Drop
Hi All,
I've been using Java 1.4 to drag and drop data between two tables in our application. Basically I need to drag the data from individual rows of the source table and insert it into one of the cells in the new table. This works absolutely fine and has made a huge improvement to this portion of our app. I've included example source code below that does a similar thing by transferring data from one table and inserting it into another (it's quite big and also not as well done as the example in our real app but unfortunately I can't send the source for that).
The thing I've noticed though is that in order to start dragging data I need to click to select it and then press and hold the mouse button to start dragging, whereas under W**dows and just about every other OS you can just press and hold and start dragging straight away. If you try this with a JTable though it just changes the rows you have selected so the drag and drop works but feels a bit clunky and amateurish. I'd like to do something about this such that it works like Windows Explorer (or similar) where you can just press the mouse button and start dragging.
Any help would be greatly appreciated - and if anybody finds the code useful you're more than welcome to it. Note that the business end of this is CustomTransferHandler.java - this will show you how to insert data at a specific position in a JTable, it's a bit of a faff but not too bad once you've got it sussed.
Thanks,
Bart Read
===============================================================
TestFrame.java
* TestFrame.java
* Created on October 21, 2002, 4:59 PM
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.util.TooManyListenersException;
import javax.swing.*;
* @author readb
public class TestFrame extends javax.swing.JFrame
private static final String [] NAMES = {
"John", "Geoff", "Madeleine", "Maria", "Flanders",
"Homer", "Marge", "Bart", "Lisa", "Weird Baby" };
private JTable source;
private JTable dest;
private MyTableModel sourceModel;
private MyTableModel destModel;
private Clipboard clipboard;
/** Creates a new instance of TestFrame */
public TestFrame()
clipboard = getToolkit().getSystemClipboard();
Container c = getContentPane();
c.setLayout( new BorderLayout( 40, 40 ) );
source = new MyJTable();
sourceModel = new MyTableModel();
source.setModel( sourceModel );
source.setDragEnabled( true );
CustomTransferHandler handler = new CustomTransferHandler( "Source handler" );
source.setTransferHandler( handler );
try
source.getDropTarget().addDropTargetListener( handler );
catch ( TooManyListenersException tmle )
tmle.printStackTrace();
dest = new MyJTable();
destModel = new MyTableModel();
dest.setModel( destModel );
dest.setDragEnabled( true );
handler = new CustomTransferHandler( "Dest handler" );
dest.setTransferHandler( handler );
try
dest.getDropTarget().addDropTargetListener( handler );
catch ( TooManyListenersException tmle )
tmle.printStackTrace();
c.add( new JScrollPane( source ), BorderLayout.WEST );
c.add( new JScrollPane( dest ), BorderLayout.EAST );
populate();
private void populate( MyTableModel model )
for ( int index = 0; index < NAMES.length; ++index )
model.setRow( index, new DataRow( index + 1, NAMES[ index ] ) );
private void populate()
populate( sourceModel );
populate( destModel );
public static void main( String [] args )
TestFrame app = new TestFrame();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent we )
System.exit( 0 );
app.pack();
app.setSize( 1000, 600 );
app.show();
private class MyJTable extends JTable
public boolean getScrollableTracksViewportHeight()
Component parent = getParent();
if (parent instanceof JViewport)
return parent.getHeight() > getPreferredSize().height;
return false;
}=====================================================================
MyTableModel.java
* MyTableModel.java
* Created on October 21, 2002, 4:43 PM
import java.util.ArrayList;
* @author readb
public class MyTableModel extends javax.swing.table.AbstractTableModel
private static final int NUMBER = 0;
private static final int NAME = 1;
private static final String [] COLUMN_HEADINGS = { "Number", "Name" };
private ArrayList data;
/** Creates a new instance of MyTableModel */
public MyTableModel()
super();
data = new ArrayList();
public int getColumnCount()
return COLUMN_HEADINGS.length;
public String getColumnName( int index )
return COLUMN_HEADINGS[ index ];
public Class getColumnClass( int index )
switch ( index )
case NUMBER:
return Integer.class;
case NAME:
return String.class;
default:
throw new IllegalArgumentException( "Illegal column index: " + index );
public int getRowCount()
return ( null == data ? 0 : data.size() );
public Object getValueAt( int row, int column )
DataRow dataRow = ( DataRow ) data.get( row );
switch ( column )
case NUMBER:
return new Integer( dataRow.getNumber() );
case NAME:
return dataRow.getName();
default:
throw new IllegalArgumentException( "Illegal column index: " + column );
public void addRow( DataRow row )
int rowIndex = data.size();
data.add( row );
fireTableRowsInserted( rowIndex, rowIndex );
public void addRows( DataRow [] rows )
int firstRow = data.size();
for ( int index = 0; index < rows.length; ++index )
data.add( rows[ index ] );
fireTableRowsInserted( firstRow, data.size() - 1 );
public void setRow( int index, DataRow row )
if ( index == data.size() )
data.add( row );
else
data.set( index, row );
fireTableRowsUpdated( index, index );
public void insertRows( int index, DataRow [] rows )
for ( int rowIndex = rows.length - 1; rowIndex >= 0; --rowIndex )
data.add( index, rows[ rowIndex ] );
fireTableRowsInserted( index, index + rows.length - 1 );
public DataRow getRow( int index )
return ( DataRow ) data.get( index );
public DataRow removeRow( int index )
DataRow retVal = ( DataRow ) data.remove( index );
fireTableRowsDeleted( index, index );
return retVal;
public boolean removeRow( DataRow row )
int index = data.indexOf( row );
boolean retVal = data.remove( row );
fireTableRowsDeleted( index, index );
return retVal;
public void removeRows( DataRow [] rows )
for ( int index = 0; index < rows.length; ++index )
data.remove( rows[ index ] );
fireTableDataChanged();
}=====================================================================
DataRow.java
* DataRow.java
* Created on October 21, 2002, 4:41 PM
import java.io.Serializable;
* @author readb
public class DataRow implements Serializable
private int number;
private String name;
/** Creates a new instance of DataRow */
public DataRow( int number, String name )
this.number = number;
this.name = name;
public int getNumber()
return number;
public String getName()
return name;
public String toString()
return String.valueOf( number ) + ": " + name;
}======================================================================
CustomTransferHandler.java
* CustomTransferHandler.java
* Created on October 22, 2002, 8:36 AM
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.*;
import java.awt.event.InputEvent;
import java.io.IOException;
import java.util.Arrays;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.TransferHandler;
* @author readb
public class CustomTransferHandler
extends TransferHandler
implements Transferable, ClipboardOwner, DropTargetListener
public static final DataFlavor ROW_ARRAY_FLAVOR = new DataFlavor( DataRow[].class, "Multiple rows of data" );
private String name;
private ImageIcon myIcon;
private DataRow [] data;
private boolean clipboardOwner = false;
private int rowIndex = -1;
/** Creates a new instance of CustomTransferHandler */
public CustomTransferHandler( String name )
this.name = name;
public boolean canImport( JComponent comp, DataFlavor [] transferFlavors )
System.err.println( "CustomTransferHandler::canImport" );
if ( comp instanceof JTable && ( ( JTable ) comp ).getModel() instanceof MyTableModel )
for ( int index = 0; index < transferFlavors.length; ++index )
if ( ! transferFlavors[ index ].equals( ROW_ARRAY_FLAVOR ) )
return false;
return true;
else
return false;
protected Transferable createTransferable( JComponent c )
System.err.println( "CustomTransferHandler::createTransferable" );
if ( ! ( c instanceof JTable ) || ! ( ( ( JTable ) c ).getModel() instanceof MyTableModel ) )
return null;
this.data = null;
JTable table = ( JTable ) c;
MyTableModel model = ( MyTableModel ) table.getModel();
Clipboard cb = table.getToolkit().getSystemClipboard();
cb.setContents( this, this );
clipboardOwner = true;
int [] selectedRows = table.getSelectedRows();
Arrays.sort( selectedRows );
data = new DataRow[ selectedRows.length ];
for ( int index = 0; index < data.length; ++index )
data[ index ] = model.getRow( selectedRows[ index ] );
return this;
public void exportAsDrag( JComponent comp, InputEvent e, int action )
super.exportAsDrag( comp, e, action );
Clipboard cb = comp.getToolkit().getSystemClipboard();
cb.setContents( this, this );
protected void exportDone( JComponent source, Transferable data, int action )
System.err.println( "CustomTransferHandler::exportDone" );
if ( TransferHandler.MOVE == action && source instanceof JTable && ( ( JTable ) source ).getModel() instanceof MyTableModel )
JTable table = ( JTable ) source;
MyTableModel model = ( MyTableModel ) table.getModel();
int [] selected = table.getSelectedRows();
for ( int index = selected.length - 1; index >= 0; --index )
model.removeRow( selected[ index ] );
public void exportToClipboard( JComponent comp, Clipboard clip, int action )
System.err.println( "CustomTransferHandler::exportToClipboard" );
public int getSourceActions( JComponent c )
System.err.println( "CustomTransferHandler::getSourceActions" );
if ( ( c instanceof JTable ) && ( ( JTable ) c ).getModel() instanceof MyTableModel )
return MOVE;
else
return NONE;
* I've commented this out because it doesn't appear to work in any case.
* The image isn't null but as far as I can tell this method is never
* invoked.
// public Icon getVisualRepresentation( Transferable t )
// System.err.println( "CustomTransferHandler::getVisualRepresentation" );
// if ( t instanceof CustomTransferHandler )
// if ( null == myIcon )
// try
// myIcon = new ImageIcon( getClass().getClassLoader().getResource( "dragimage.gif" ) );
// catch ( Exception e )
// System.err.println( "CustomTransferHandler::getVisualRepresentation: exception loading image" );
// e.printStackTrace();
// if ( null == myIcon )
// System.err.println( "CustomTransferHandler::getVisualRepresentation: myIcon is still NULL" );
// return myIcon;
// else
// return null;
public boolean importData( JComponent comp, Transferable t )
System.err.println( "CustomTransferHandler::importData" );
super.importData( comp, t );
if ( ! ( comp instanceof JTable ) )
return false;
if ( ! ( ( ( JTable ) comp ).getModel() instanceof MyTableModel ) )
return false;
if ( clipboardOwner )
return false;
if ( !t.isDataFlavorSupported( ROW_ARRAY_FLAVOR ) )
return false;
try
data = ( DataRow [] ) t.getTransferData( ROW_ARRAY_FLAVOR );
return true;
catch ( IOException ioe )
data = null;
return false;
catch ( UnsupportedFlavorException ufe )
data = null;
return false;
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException
System.err.println( "MyTransferable::getTransferData" );
if ( flavor.equals( ROW_ARRAY_FLAVOR ) )
return data;
else
throw new UnsupportedFlavorException( flavor );
public DataFlavor[] getTransferDataFlavors()
System.err.println( "MyTransferable::getTransferDataFlavors" );
DataFlavor [] flavors = new DataFlavor[ 1 ];
flavors[ 0 ] = ROW_ARRAY_FLAVOR;
return flavors;
public boolean isDataFlavorSupported( DataFlavor flavor )
System.err.println( "MyTransferable::isDataFlavorSupported" );
return flavor.equals( ROW_ARRAY_FLAVOR );
public void lostOwnership( Clipboard clipboard, Transferable transferable )
clipboardOwner = false;
/** Called while a drag operation is ongoing, when the mouse pointer enters
* the operable part of the drop site for the <code>DropTarget</code>
* registered with this listener.
* @param dtde the <code>DropTargetDragEvent</code>
public void dragEnter(DropTargetDragEvent dtde)
/** Called while a drag operation is ongoing, when the mouse pointer has
* exited the operable part of the drop site for the
* <code>DropTarget</code> registered with this listener.
* @param dte the <code>DropTargetEvent</code>
public void dragExit(DropTargetEvent dte)
/** Called when a drag operation is ongoing, while the mouse pointer is still
* over the operable part of the drop site for the <code>DropTarget</code>
* registered with this listener.
* @param dtde the <code>DropTargetDragEvent</code>
public void dragOver(DropTargetDragEvent dtde)
/** Called when the drag operation has terminated with a drop on
* the operable part of the drop site for the <code>DropTarget</code>
* registered with this listener.
* <p>
* This method is responsible for undertaking
* the transfer of the data associated with the
* gesture. The <code>DropTargetDropEvent</code>
* provides a means to obtain a <code>Transferable</code>
* object that represents the data object(s) to
* be transfered.<P>
* From this method, the <code>DropTargetListener</code>
* shall accept or reject the drop via the
* acceptDrop(int dropAction) or rejectDrop() methods of the
* <code>DropTargetDropEvent</code> parameter.
* <P>
* Subsequent to acceptDrop(), but not before,
* <code>DropTargetDropEvent</code>'s getTransferable()
* method may be invoked, and data transfer may be
* performed via the returned <code>Transferable</code>'s
* getTransferData() method.
* <P>
* At the completion of a drop, an implementation
* of this method is required to signal the success/failure
* of the drop by passing an appropriate
* <code>boolean</code> to the <code>DropTargetDropEvent</code>'s
* dropComplete(boolean success) method.
* <P>
* Note: The data transfer should be completed before the call to the
* <code>DropTargetDropEvent</code>'s dropComplete(boolean success) method.
* After that, a call to the getTransferData() method of the
* <code>Transferable</code> returned by
* <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to
* succeed only if the data transfer is local; that is, only if
* <code>DropTargetDropEvent.isLocalTransfer()</code> returns
* <code>true</code>. Otherwise, the behavior of the call is
* implementation-dependent.
* <P>
* @param dtde the <code>DropTargetDropEvent</code>
public void drop(DropTargetDropEvent dtde)
System.err.println( "CustomTransferHandler::drop" );
Component c = dtde.getDropTargetContext().getDropTarget().getComponent();
if ( ! ( c instanceof JComponent ) )
dtde.rejectDrop();
return;
JComponent comp = ( JComponent ) c;
if ( ! ( c instanceof JTable ) || ! ( ( ( JTable ) c ).getModel() instanceof MyTableModel ) )
dtde.rejectDrop();
return;
dtde.acceptDrop( TransferHandler.MOVE );
// THIS is such a mess -- you can't do the following because
// getTransferable() throws an (undocumented) exception - what's that
// all about.
// Transferable t = dtde.getTransferable();
// if ( !t.isDataFlavourSupported( ROW_ARRAY_FLAVOR ) )
// dtde.rejectDrop();
// return false;
// TransferHandler handler = comp.getTransferHandler();
// if ( null == handler || ! handler.importData( comp, t ) )
// dtde.rejectDrop();
// return;
Point p = dtde.getLocation();
JTable table = ( JTable ) comp;
rowIndex = table.rowAtPoint( p );
// So you have to do this instead and use the data that's been
// stored in the data member via import data. Total mess.
if ( null == data )
dtde.rejectDrop();
return;
MyTableModel model = ( MyTableModel ) table.getModel();
if ( rowIndex == -1 )
model.addRows( data );
else
model.insertRows( rowIndex, data );
dtde.acceptDrop( TransferHandler.MOVE );
/** Called if the user has modified
* the current drop gesture.
* <P>
* @param dtde the <code>DropTargetDragEvent</code>
public void dropActionChanged(DropTargetDragEvent dtde)
}Hi again,
Well I've tried using the MouseListener / MouseMotionListener approach but it doesn't quite seem to work, although it does get the events correctly. I think the reason is that it doesn't interact correctly with the Java DnD machinery which is something that V.V hinted at. It's something that I may need to look into if / when I have more time available.
I have to say though that I haven't had any problems with scrollbars - we're making fairly heavy use of large tables and if you drag over a table with a scroll bar and move to the top or bottom then it scrolls as you would expect and allows you to drop the data where you like. For this situation I've used pretty much the same approach as for the toy example above except that I've implemented separate source and destination TransferHandlers (the source table is read-only, and it really doesn't make sense to allow people to drag from the destination table so I've essentially split the functionality of the example handler down the middle).
I'm not actually particularly in favour of messing too much with the mechanics of DnD, more because of lack of time than anything else. Guess I'll just have to put up with this for the moment. Doesn't help that DnD is so poorly documented by Sun.
Thanks for all your help.
Bart
Maybe you are looking for
-
Safari won't open after updating to 6.0.3
Hey, after I had updated my Safari to the latest version (6.0.3), Safari is unable to open itself and shows an instant crash window after clicking on it. I have deleted my extensions already, but that didn't help. I was hoping if someone would be abl
-
Sent email to be shown on more than 1 computer in the same premise
there is small business company that has got 4 computer on same network and every computer has mozilla thunderbird installed. My question is that if i send mail from one computer it does not show the sent mail in another computer's sent folder. why i
-
I have been trying for 2 weeks now to update Adobe Muse (and now other Adobe programs as well) via the Creative Cloud application manager. It notifies me that I have 2 new updates available, Muse and also now ReFlow, but whenever I click 'update' the
-
BPS initial value at Planning Level
Hello All I am getting error while using BW Hierarchy at planning level. i find the solution at Including # initial value using hierachy but its not working i am getting this error "Characteristic Funds Center does not contain the initial value in t
-
Show-through image at slide change
I've placed a white image on part of a slide background to cover up part of the original image, and then embedded the white image into the background. It seems to be fine while I'm in edit mode. I've done this with several slides. When I run the movi