Cant get the last row in jtable
Hello all.
I am trying to get the last row from the table but get "" from it.
my table has 6 rows and i can get all rows right but the last line I have a problem.
//creating the table
for (i=0;i<this.rows;i++)
model.insertRow(i,new Object[]{"input Y1:",""});
for ( i=i;i<this.Amount+this.rows;i++)
model.insertRow(i,new Object[]{"input Amount:",""});
//end of creatingthis code creats the table that i need and its works right.
for(i=0;i<rows;i++){
fObj.fullData[i] = Double.valueOf(GetData(table, 1, i).toString()).doubleValue();
int j=0;
String s=GetData(table, 1, 4).toString();
//the problem line
String s1=GetData(table, 1, 5).toString();
public Object GetData(JTable table, int col_index, int row_index){
return table.getModel().getValueAt(row_index, col_index);
}this line i get ""
String s1=GetData(table, 1, 5).toString();
Edited by: vitaly87 on 00:41 08/04/2011
vitaly87 wrote:
Hello all.
I am trying to get the last row from the table but get "" from it.
my table has 6 rows and i can get all rows right but the last line I have a problem.
this line i get ""
String s1=GetData(table, 1, 5).toString();Looks right to me, given that your insert ismodel.insertRow(i,new Object[]{"input Amount:",""});(Hint: indexes start at *0* ).
If it hadn't found the row, I expect you would have got an Exception
Winston
Similar Messages
-
How to get the last row of a database table.
HI ,
I want to get record exactly from the last row of a database table.
How is that possible?Hi,
To fetch last record from an internal table, just do find the number of records in it and read using index.
DESCRIBE TABLE ITAB LINES L_LINES.
READ TABLE ITAB INDEX L_LINES.
You can also use LOOP .. ENDLOOP but the above method is better (performance wise).
using LOOP .. ENDLOOP.
LOOP AT ITAB.
**do nothing
ENDLOOP.
**process ITAB (Header record of ITAB).
**after ENLOOP, ITAB will have the last record of the internal table.
[here ITAB is internal table as well as header record.]
But what is the requirement?
If you are looking for the current record of an employee then you can use ENDDA = HIGH_DATE.
My advice is to review your requirement again and try to fetch only that record which you need.
Mubeen -
How to get the last row in a resultset or query
Hi All
Say If I have a complex query which returns a resultset say 15 rows. Now I want to limit the output showing only the last row.
How can we do thisKeep in mind Oracle does not keep "row" order as such. Unlike a graphical type db like Access, Oracle will not always give you back the results in order.
Even if you were to use a sequence, your query is never guaranteed to give back the results in the order you are expecting. You must then give an order by statement to all queries expecting the order.
Your definition of last row too is vague - if it is in fact the greatest amount, use the inline view suggestion. If you simply want to see the last inserted row, consider adding a last_update_date column inserting the sysdate (by a trigger perhaps). This would then allow you to see the last inserted row.
Enjoy! -
I have 10 rows in my table and I have to retrive last row using rownum.
For this I use
SELECT * from <table_name>
where rownum<=10
minus
SELECT * from <table_name>
where rownum<=9
The result is no rows selected
In the same case if I use
SELECT rownum from <table_name>
Where rownum <= 10
minus
SELECT rownum from <table_name>
where rownum <=9
The result is 10
Why this happend.
If the result is 10, then why the row whose rowid is 10 is not retrivedAll
Please bear in mind that ROWNUM is an attribute of the query NOT the table. The last row returned by an unORDERed SELECT statement may be the most recently inserted row but is not guaranteed to be so.
The only way of assuring yourself of returning the most recent row is either to timestamp all your tables with a date_created column or to use a primary key with an ascending value.
rgds, APC -
Trying to get the last row from a resultset
Hi,
I'm trying to do a query to postgreSQL and have it return the last updated value, (last row).
My prepared statement is returning the correct results, but i'm having a problem getting the latest value.
I'm using a comboBox to drive a textfield, to load the last entered values in depending on which item in the comboBox is selected.
I've tried a variety of things and most seem to return the first row, not showing the updated values.
Or, if it does work, it takes to long to load, and i get an error.
here is the working code;
Object m = machCBX.getSelectedItem():
try { PreparedStatment last = conn.prepareStatement("SELECT part, count FROM production WHERE machine = ?",
ResultSet.TYPE_SCROLL_INSENSITIVE, //tried both INSENSITIVE and SENSITIVE
ResultSet.CONCUR_READ_ONLY);
last.setString(1, String.valueOf(m));
rs. = last.executeQuery();
if(rs.isAfterLast) == false ) {
rs.afterLast();
while(rs.previous()) {
String p = rs.getString("part");
int c = rs.getInt("count");
partJTX.setText(p);
countJTX.setText(c);
}this grabs values, but they are not the last entered values.
Now if i try to use rs.last() it returns the value i'm looking for but takes to long, and i get:
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space I also know using ra.last() isn't the best way to go.
I'm just wondering if there is another way other than getting into vectors and row count? or am i better off to go with the later?
thanks
-PDOK, you've got a major misunderstanding...
The relational database model is built on the storage of sets - UNORDERED sets. In other words, when you hand a database a SELECT statement without an ORDER BY clause, the database is free to return the results in any order.
Now it so happens that most databases will happen to return data retrieved by an unordered SELECT, at least for a while, in the same order that it was inserted, especially if no UPDATE or DELETE activity has occured, and no database maintenance has occured. However, eventually most tables have some operation that creates a "space" in the underlying storage, or causes a row to expand and have to be moved or extended, or something. Then the database will start returning unordered results in a different order. If you (or other people) never ever ever UPDATE or DELETE a table, then on some databases the data might well come out in insertion order for a very very long time; given human nature and the way projects tend to work, relying on that is a sucker's bet, IMHO.
In other words, if you want the "most recent" something, you need to store a timestamp with your data. (With some databases, you might be able to take advantage of some non-standard feature to get "last updates" or "row change timestamps", but I know of no such for Postgres.
While this won't solve your major problem, above, your issue with rs.last is probably occuring because Postgres by default will prefetch your entire ResultSet. Use Statement.setFetchSize() to change that (PreparedStatement inherits the method, of course). -
When I tried to import from my camera, the last day did not import, I keep retrying, but will not import. Could it have anything to do with the date Feb 29, 2012 as it was Leap Year?
OK Texas, so nothing strange with the calendar (unless you folk have seceded since the last time I checked the news )
Image Capture is an Apple App that comes with the OS. Allows you to do a bunch of things. Import pictures from your camera is one. Open the app with your camera connected. If you have Aperture set to open when the camera is connected just close Aperture and then open Image Capture.
You'll see the camera and it should show you the images on the camera card. See if the images from the 29th show up.
post the results.
regards -
Group by clause get the last row of max occurence
Table 1
Division Incident
1 xyz
2 abc
3 efg
1 klo
2 jkl
I want to have an sql query which groups the occurrences of (division) in the table. If two grouping counts are same, it should give largest division.. division 1 and 2 have 2 occurrences each.
select div, count(*) FROM TABLE1 GROUP by division is not giving the result.
I am trying to get division 2 as the answer. No other rows should be present in the returnmat wrote:
Table 1
Division Incident
1 xyz
2 abc
3 efg
1 klo
2 jkl
I want to have an sql query which groups the occurrences of (division) in the table. If two grouping counts are same, it should give largest division.. division 1 and 2 have 2 occurrences each.
select div, count(*) FROM TABLE1 GROUP by division is not giving the result.
I am trying to get division 2 as the answer. No other rows should be present in the return
select division
from
select division, incident, row_number() over (order by count_per_div desc, division desc) as rn
from
select division, incident, count(*) over (partition by division) as count_per_div
from <your_table>
where rn = 1;Would be one way (not tested since you didn't provide sample data I could run this against).
You could probably combine that in to less steps, but as is it shows you the steps to take.
Cheers, -
HELP! How te retrieve the last row in MYSQL database using Servlet!
Hi ,
I am new servlets. I am trying to retireve the last row id inserted using the servlet.
Could someone show me a working sample code on how to retrieve the last record inserted?
Thanks
MY CODE
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class demo_gr extends HttpServlet {
//***** Servlet access to data base
public void doPost (HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
String url = "jdbc:mysql://sql2.njit.edu/ki3_proj";
String param1 = req.getParameter("param1");
PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
String semail, sfname, slname, rfname, rlname, remail, message;
int cardType;
sfname = req.getParameter("sfname");
slname = req.getParameter("slname");
rfname = req.getParameter("rfname");
rlname = req.getParameter("rlname");
semail = req.getParameter("semail");
remail = req.getParameter("remail");
message = req.getParameter("message");
//cardType = req.getParameter("cardType");
cardType = Integer.parseInt(req.getParameter("cardType"));
out.println(" param1 " + param1 + "\n");
String query = "SELECT * FROM greeting_db "
+ "WHERE id =" + param1 + "";
String query2 ="INSERT INTO greeting_db (sfname, slname ,semail , rfname , rlname , remail , message , cardType ,sentdate ,vieweddate) values('";
query2 = query2 + sfname +"','"+ slname + "','"+ semail + "','"+ rfname + "','"+ rlname + "','"+ remail + "','"+ message + "','"+ cardType + "',NOW(),NOW())";
//out.println(" query2 " + query2 + "\n");
if (semail.equals("") || sfname.equals("") ||
slname.equals("") || rfname.equals("") ||
rlname.equals("") || remail.equals("") ||
message.equals(""))
out.println("<h3> Please Click the back button and fill in <b>all</b> fields</h3>");
out.close();
return;
String title = "Your Card Has Been Sent";
out.println("<BODY>\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" );
out.println("\n" +
"\n" +
" From " + sfname + ", " + slname + "\n <br> To "
+ rfname + ", " + rlname + "\n <br>Receiver Email " + remail + "\n<br> Your Message "
+ message + "\n<br> <br> :");
if (cardType ==1)
out.println("<IMG SRC=/WEB-INF/images/bentley.jpg>");
else if(cardType ==2) {
out.println("<IMG SRC=/WEB-INF/images/Bugatti.jpg>");
else if(cardType ==3) {
out.println(" <IMG SRC=/WEB-INF/images/castle.jpg>");
else if(cardType ==4) {
out.println(" <IMG SRC=/WEB-INF/images/motocross.jpg>");
else if(cardType ==5) {
out.println(" <IMG SRC=/WEB-INF/images/Mustang.jpg>");
else if(cardType ==6) {
out.println("<IMG SRC=/WEB-INF/images/Mustang.jpg>");
out.println("</BODY></HTML>");
try {
Class.forName ("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
( url, "*****", "******" );
Statement stmt = con.createStatement ();
stmt.execute (query2);
//String query3 = "SELECT LAST_INSERT_ID()";
//ResultSet rs = stmt.executeQuery (query3);
//int questionID = rs.getInt(1);
System.out.println("Total rows:"+questionID);
stmt.close();
con.close();
} // end try
catch (SQLException ex) {
//PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
while (ex != null) {
out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException ();
} // end while
} // end catch SQLException
catch (java.lang.Exception ex) {
//PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
out.println ("Exception: " + ex.getMessage ());
} // end doGet
private void printResultSet ( HttpServletResponse resp, ResultSet rs )
throws SQLException {
try {
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<head><title>jbs jdbc/mysql servlet</title></head>");
out.println("<body>");
out.println("<center><font color=AA0000>");
out.println("<table border='1'>");
int numCols = rs.getMetaData().getColumnCount ();
while ( rs.next() ) {
out.println("<tr>");
for (int i=1; i<=numCols; i++) {
out.print("<td>" + rs.getString(i) + "</td>" );
} // end for
out.println("</tr>");
} // end while
out.println("</table>");
out.println("</font></center>");
out.println("</body>");
out.println("</html>");
out.close();
} // end try
catch ( IOException except) {
} // end catch
} // end returnHTML
} // end jbsJDBCServletI dont know what table names and fields you have but
say you have a table called XYZ which has a primary
key field called keyID.
So in order to get the last row inserted, you could
do something like
Select *
from XYZ
where keyID = (Select MAX(keyID) from XYZ);
Good Luckwhat gubloo said is correct ...But this is all in MS SQL Server I don't know the syntax and key words in MYSQL
This works fine if the emp_id is incremental and of type integer
Query:
select *
from employee e, (select max(emp_id) as emp_id from employee) z
where e.emp_id = z.emp_id
or
select top 1 * from employee order by emp_id descUday -
How to get the last value edited by users from JTable?
Hi.
I have a JDialog that includes an editable JTable. This table is used to set up field caption and font for a report program. I found only when cursor is moved to another cell, the value in current cell being edited will be transferred to Table Model. So if the user don�t move cursor to another cell after editing the value of a cell but click OK button directly, Table Model cannot get the last value edited by the user, I wonder if there is a way to fire JTable to transfer the value being edited to Table model.
By the way, I found if the TableCellEditor is using JCheckBox or JComboBox instead of JTextField, there is no this problem.
Thank you for any reply.I guess you can make use of the following methods on your table model to inform it make it getValueAt bcos table data has changed.
fireTableCellUpdated
Notifies all listeners that the value of the cell at [row, column] has been updated.
fireTableChanged
Forwards the given notification event to all TableModelListeners that registered themselves as listeners for this table model.
fireTableDataChanged
Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.
But when to call these methods??
-- When OK button is pressed, do this as the first thing!!
OR
-- Call this on every key event!!
regds,
CA -
JTable: How to get the last value entered ?
I have a JTable, with 2 columns and 3 rows that I need to fill..
If I don't press the Enter key after filling each cell, and if I call the foloowing method
void readTable()
String[][] myarray = new String[3][2];
for (int i = 0 ; i<3;i++)
for (j=0 ; j<2; j++)
myrray[i][j] = (String) table.getValueAt(i, j);
}the last returned value is null.
Is it possible to simulate the Enter key by program (or any other way) to make sure to get the last edited cell value, whether or not the user press the enter key before clicking on a button (for example) to execute the above code. ?
Thanks a lot for help
GegeThanks Camikr, using
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);works fine. It's exactly what I was looking for.
Thanks again.
Gege -
How to get the last transaction in a row in SQL Developer?
What syntax would I use to get the last transaction of a row in SQL developer?
The way I have my query set-up currently it is not returning the correct data, here is my current syntax:
select ssn, max(tran_id), chng_type,tran_id
from pda_tran
where ssn = 'xxx-xxx-0011'
and chng_type = 'C'
group by ssn, chng_type,tran_id;
It returns a 'C' chng_type but it is not the last one. when I query on this ssn this is what I get:
ssn tran_id chng_type
xxx-xxx-0011 001 A
xxx-xxx-0011 002 E
xxx-xxx-0011 003 C
xxx-xxx-0011 004 S
xxx-xxx-0011 005 C
xxx-xxx-0011 006 T
I only want to return the ssn's with a last transaction chng_type of 'C'. How can I get the correct information returned. Please advise.From what I see and read... there is one to many group by
You wrote
select ssn, max(tran_id), chng_type,tran_id
from pda_tran
where ssn = 'xxx-xxx-0011'
and chng_type = 'C'
group by ssn, chng_type,tran_id;
If you want the max(tran_id), remove it from the "group by"
select ssn, chng_type, max(tran_id)
FROM
(SELECT 'xxx-xxx-0011' ssn, '001' tran_id, 'A' chng_type FROM DUAL UNION
SELECT 'xxx-xxx-0011' ssn, '002' tran_id, 'E' chng_type FROM DUAL UNION
SELECT 'xxx-xxx-0011' ssn, '003' tran_id, 'C' chng_type FROM DUAL UNION
SELECT 'xxx-xxx-0011' ssn, '004' tran_id, 'S' chng_type FROM DUAL UNION
SELECT 'xxx-xxx-0011' ssn, '005' tran_id, 'C' chng_type FROM DUAL UNION
SELECT 'xxx-xxx-0011' ssn, '006'tran_id, 'T' chng_type FROM DUAL )
where ssn = 'xxx-xxx-0011'
and chng_type = 'C'
group by ssn, chng_type; -
Get rows where the last row finish off
Hi, i have two tables AND would LIKE TO get data BY combining both.
here IS my data
WITH hist AS
SELECT To_Date('4/23/2010','mm/dd/yyyy') dt, 999 alias, 'PROC' dom FROM dual UNION ALL
SELECT To_Date('4/27/2010','mm/dd/yyyy') dt, 999 alias, 'LON' dom FROM dual UNION all
SELECT To_Date('4/1/2010','mm/dd/yyyy') dt, 111 alias, 'SOC' dom FROM dual UNION all
SELECT To_Date('4/10/2010','mm/dd/yyyy') dt, 111 alias, 'NAO' dom FROM dual UNION ALL
SELECT To_Date('3/23/2010','mm/dd/yyyy') dt, 222 alias, 'PSE' dom FROM dual
final AS
SELECT To_Date('2/26/2010','mm/dd/yyyy') dt, 999 alias FROM dual UNION ALL
SELECT To_Date('4/22/2010','mm/dd/yyyy') dt, 999 alias FROM dual UNION all
SELECT To_Date('4/26/2010','mm/dd/yyyy') dt, 999 alias FROM dual UNION ALL
SELECT To_Date('4/30/2010','mm/dd/yyyy') dt, 999 alias FROM dual UNION ALL
SELECT To_Date('2/25/2010','mm/dd/yyyy') dt, 111 alias FROM dual UNION ALL
SELECT To_Date('2/26/2010','mm/dd/yyyy') dt, 222 alias FROM dual UNION ALL
SELECT To_Date('4/22/2010','mm/dd/yyyy') dt, 222 alias FROM dual UNION all
SELECT To_Date('4/26/2010','mm/dd/yyyy') dt, 222 alias FROM dual
the output should be as follow(without the extra blank line of course)
DT ALIAS DOM
2/26/2010 999 PROC
4/22/2010 999 PROC
4/26/2010 999 LON
4/30/2010 999 LON
4/27/2010 999 LON
4/23/2010 999 PROC
2/25/2010 111 SOC
4/1/2010 222 SOC
4/10/2010 222 NAO
2/26/2010 222 PSE
4/22/2010 222 PSE
4/26/2010 222 PSEso what i am doing here is as follow, take one row in hist table (4/23) and join with final table and give me all rows in final table
where dt <= to the row in hist table and include the row from hist table.
this logic will give me rows 2/26/2010,4/22/10 4/23/2010
then the second row in hist table (4/27/2010) wiill get all rows
in final table that is <= to the current row and pick up the rows starting from the row > than the last row where the 4/23/2010 finished off
in this case the output will be 4/26/10, 4/27/2010(we need to include row from hist)
since there is no row in hist that is greater than 4/30/2010, this date will still be display and dom column value should be taking from the max date in hist
which is 4/27/2010. see output above
this sound a little confusing to explain but look at output of what to expect as output. the other ids should follow the same logic
can someone help write a query for this? thanksHi,
Devx wrote:
Frank, thanks again, i ran the query in oracle 11g and oracle 9i. 11g runs ok but 9i doesnt. it looks like the ignore null option is not supported in 9i. That's right: IGNORE NULLS was new in Oracle 10. You should always mention your Oracle version whenever you ask a quiestion, especially if it's as old as Oracle 9.
i will be running this query in 9i. is there any alternative to re-write this query without using last value since ignore null is not supported and the output is not as i expected when i take that keyword out.
i really appreciate your help. please let me know how would i re-write the query. thanksOne work-around is to use LEAD or LAG instead of LAST_VALUE. This means you have to know exactly where (how many rows away) the most recent non-NULL value is, which in turn requires other analytuic funtions, such as ROW_NUMBER, and more sub-queries:
WITH combined_tables AS
SELECT dt, alias, NVL (dom, '_?_') AS dom FROM hist
UNION
SELECT dt, alias, NULL AS dom FROM final
, got_r_num AS
SELECT dt, alias, dom
, ROW_NUMBER () OVER ( PARTITION BY alias
ORDER BY dt
) AS r_num
, COUNT (*) OVER ( PARTITION BY alias
) AS alias_cnt
FROM combined_tables
, got_skip_cnts AS
SELECT dt, alias, dom, r_num
, r_num - MAX (CASE WHEN dom IS NOT NULL THEN r_num END)
OVER ( PARTITION BY alias
ORDER BY r_num
) AS skip_before
, MIN (CASE WHEN dom IS NOT NULL THEN r_num END)
OVER ( PARTITION BY alias
ORDER BY r_num DESC
) - r_num AS skip_after
FROM got_r_num
, got_next_dom AS
SELECT dt, alias, dom, r_num, skip_before
, LEAD (dom, skip_after) OVER ( PARTITION BY alias
ORDER BY r_num
) AS next_dom
FROM got_skip_cnts
SELECT dt
, alias
, NULLIF ( COALESCE ( next_dom
, LAG (dom, skip_before) OVER ( PARTITION BY alias
ORDER BY r_num
) AS dom
FROM got_next_dom
ORDER BY alias
, dt
;You should be able to calculate bot LEAD and LAG in the same query, but there seems to be a bug that only calculates one of them correctly in this case. The sub-query got_next_dom gets around that, by doing the LEAD in a separate sub-query. -
JTable problem : how to get the last value entered by user + event lost
Hi all,
I have 2 problems with Jtable class.
1 => To get the last value entered by user in a cell,
it seems that we must change the selected cell.
That is to say we can only have the previous cell's value.
Is there a simple way to get the current value of any cell ?
2 => To resolve the problem i store the values of each cell in a vector and i intercept keyboard event (!)
BUT, when i do a double click with the mouse on the Jtable, i loose keyboard events. Then, i can't intercept them.
Is it a bug of swing or am i following a wrong way ?
Thanks by anticipation for your help.You have to fire the "TableCellUpdatedEvent"
and override the getCellEditorValue in TableCellEditor to return the current value -
JTable cell Render on the last row column one help please
Hi All
I am hoping that someone will be able to help me with this....
I want to render the last row and column one of the table with this render
thanks for any help
Craig
public class MyRenderer2 extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
ImageIcon icon = new ImageIcon(image_pics.SMALL_BLUE);
setIcon(icon);
return this;
}it still renders every row
any Ideas ??
I just want the last row column 0 to be rendered
I a call a method set table
then I call for the data
//TableModel
public void setClientTableModel() {
clientModel = new DefaultTableModel(coloumHeaderObject, 0) {
public boolean isCellEditable(int row, int column) {
return false;
TableSorter sorter = new TableSorter(clientModel); //ADDED THIS
sorter.setTableHeader(phoneList.getTableHeader()); //ADDED THIS
phoneList.setModel(sorter);
// phoneList.setTableHeader(null);
setTable();
revalidate();
public void setTable() {
// phoneList.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
phoneList.getColumnModel().getColumn(1).setCellRenderer(new MyRenderer1());
phoneList.getColumnModel().getColumn(4).setCellRenderer(new MyRenderer2());
phoneList.getColumnModel().getColumn(0).setMinWidth(20);
phoneList.getColumnModel().getColumn(0).setMaxWidth(20);
phoneList.getColumnModel().getColumn(0).setPreferredWidth(20);
phoneList.getColumnModel().getColumn(1).setMinWidth(20);
phoneList.getColumnModel().getColumn(1).setMaxWidth(20);
phoneList.getColumnModel().getColumn(1).setPreferredWidth(20);
phoneList.getColumnModel().getColumn(2).setMinWidth(80);
phoneList.getColumnModel().getColumn(2).setMaxWidth(80);
phoneList.getColumnModel().getColumn(2).setPreferredWidth(80);
phoneList.getColumnModel().getColumn(3).setMinWidth(150);
phoneList.getColumnModel().getColumn(3).setMaxWidth(150);
phoneList.getColumnModel().getColumn(3).setPreferredWidth(150);
phoneList.getColumnModel().getColumn(4).setMinWidth(20);
phoneList.getColumnModel().getColumn(4).setMaxWidth(20);
phoneList.getColumnModel().getColumn(4).setPreferredWidth(20);
phoneList.setOpaque(false);
phoneList.setGridColor(Color.lightGray);
phoneList.setRowHeight(18);
phoneList.setShowVerticalLines(false);
phoneList.setIntercellSpacing(new Dimension(0, 0));
phoneList.setFont(new java.awt.Font("Lucida Grande", 0, 11));
phoneList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (ALLOW_COLUMN_SELECTION) { // false by default
if (ALLOW_ROW_SELECTION) {
phoneList.setCellSelectionEnabled(true);
phoneList.setColumnSelectionAllowed(true);
ListSelectionModel colSM = phoneList.getColumnModel().getSelectionModel();
colSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())return;
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
int row = phoneList.getSelectedRow(), col = 3;
int rowID = phoneList.getSelectedRow(), colID = 5;
if (lsm.isSelectionEmpty()) {
} else {
int selectedCol = lsm.getMinSelectionIndex();
if (selectedCol == 4) {
phoneNumber = (String) phoneList.getValueAt(row, col).toString();
main.setPhoneNumber(phoneNumber);
main.openLargePhone();
lsm.clearSelection();
if (selectedCol == 5) {
ID = (String) phoneList.getValueAt(row, col).toString();
// main.setID(ID);
// main.deleteContact();
lsm.clearSelection();
//set table data
public void setTest() {
setClientTableModel();
Object[] data = {" ", " ", "Work", "03 9841-8247", " "};
clientModel.addRow(data);
Object[] data1 = {" ", " ", "Fax", "03 9842-0360", " "};
clientModel.addRow(data1);
phoneList.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
} -
Sort rows in JTable except the last row
Hi All,
I have a JTable, which contains columns with numbers. The last row contains column sums.
I want to be able to sort rows, but the last row with sums must remain motionless.
Does anyone know the solution of this problem?
Thanks in advance.These two posts are my example. It works pretty good but there is one significant niggle - when moving a column the 'total' table does not move smoothly but it does move. I look forward to 'camickr' reducing this to about 1 line.
Part A.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.text.DecimalFormat;
import java.util.Comparator;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class Sabre20090331
static private class TotalizingTableComponent extends JScrollPane
private TotalizingTableComponent(final TableModel tableModel)
final SecondaryTableModel secondaryTableModel = new SecondaryTableModel(tableModel);
final JTable secondaryTable = new JTable(secondaryTableModel);
for (int i = 1; i < secondaryTableModel.getColumnCount(); i++)
secondaryTable.getColumnModel().getColumn(i).setCellRenderer(new NumberCellRenderer());
secondaryTable.getColumnModel().getColumn(0).setCellRenderer(new TitleCellRenderer());
final TableColumnModel secondaryTableColumnModel = secondaryTable.getColumnModel();
secondaryTable.setRowSelectionAllowed(false);
final JTable primaryTable = new JTable(tableModel);
for (int i = 1; i < tableModel.getColumnCount(); i++)
primaryTable.getColumnModel().getColumn(i).setCellRenderer(new NumberCellRenderer());
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
final DoubleComparator doubleComparator = new DoubleComparator();
for (int i = 1; i < tableModel.getColumnCount(); i++)
sorter.setComparator(i, doubleComparator);
primaryTable.setRowSorter(sorter);
primaryTable.getColumnModel().addColumnModelListener(new TableColumnModelListener()
@Override
public void columnAdded(TableColumnModelEvent e)
// System.out.println("columnAdded()" + e);
@Override
public void columnRemoved(TableColumnModelEvent e)
// System.out.println("columnRemoved()" + e);
@Override
public void columnMoved(TableColumnModelEvent e)
//System.out.println("columnMoved()" + e);
secondaryTableColumnModel.moveColumn(e.getFromIndex(), e.getToIndex());
@Override
public void columnMarginChanged(ChangeEvent e)
//System.out.println("columnMarginChanged()" + e);
final TableColumnModel cm = (TableColumnModel) e.getSource();
for (int i = 0; i < cm.getColumnCount(); i++)
secondaryTableColumnModel.getColumn(i).setPreferredWidth(cm.getColumn(i).getWidth());
@Override
public void columnSelectionChanged(ListSelectionEvent e)
//System.out.println("columnSelectionChanged()" + e);
final JTableHeader primaryHeader = primaryTable.getTableHeader();
JPanel inner = new JPanel(new BorderLayout());
this.setColumnHeaderView(primaryHeader);
this.setViewportView(inner);
inner.add(primaryTable, BorderLayout.NORTH);
inner.add(secondaryTable, BorderLayout.CENTER);
public static void main(String[] args)
final JFrame frame = new JFrame("Totalizing JTable Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final TableModel tableModel = new PrimaryTableModel();
frame.setContentPane(new TotalizingTableComponent(tableModel));
frame.pack();
frame.setVisible(true);
}Edited by: sabre150 on Apr 1, 2009 9:21 AM
Changed the layout of the inner panel so that the secondary table is now in the CENTER. This stops the secondary table becoming detached from the primary when one expands the frame beyond the prefferred size.
Maybe you are looking for
-
Win 8 - How to use StereoMix and Headphones Mic at the same time?
I am using Windows 8 64 bit and believe I may have an IDT driver problem. I need to enable StereoMix and my Headphones Mic at the same time. I know this was previously possible with windows xp and windows 7. What happens is If I enable either Headpho
-
Slow network printing (cups)
hi, i have a Brother HL-2150N Laserprinter connected via a crossover cable directly to my laptop. (KDE4, Kernel 26-2.6.29.1-3, cups 1.3.9-4). Printer is configured as HP LaserJet Series PCL 6 CUPS (URI: lpd://192.168.10.2/binary_p1) Printer works fin
-
Class extends JComponent how to use custom methods?
I have a class Block which extends JPanel code is hereprivate class Block extends JLabel{ boolean top; Block(int a,Color c){ setSize(40 + a*10,20); setBorder(BorderFactory.createMatteBorder(40+a*10,0,
-
Changing Cost Estimation ( ML activated)
Hi All, We have ML activated and we have Price Control as "S" for all ROH, HALB & FERT Materials. The intention was to have one Cost Estimation per year and difference to be posted to variance. The Material Valuation Strategy is 1. Valuation Price
-
Stop motion animation using iMovie by a child
Hi. My six year old granddaughter has just become interested in stop motion animation. How good is iMovie for this and what are the best learning tools / tutorials?