I have a table that consists of three columns: Name | Date-Time | Description
The values for Date-Time are actually stored 2 separate fields in database table and (Outdated database - can't change, so have to work around it).
I have the following code applied:
tbNotes.setAutoCreateRowSorter(true); //tbNotes is the JTable
DefaultRowSorter sorter = ((DefaultRowSorter) tbNotes.getRowSorter());
ArrayList list = new ArrayList();
list.add(new RowSorter.SortKey(2, SortOrder.DESCENDING)); //column 2 because I have an invisible ID column
sorter.setSortKeys(list);
sorter.sort();
The result produced appears correct - the rows are sorted by date with older items appearing towards the bottom. However, sometimes I see this:
It is obvious that the sort looks at the first character in a string and assumes that 1 is bigger than 0 so 12/28/2011 is larger(newer) than 01/03/2012
How would I go about having a proper sort on my JTable by date?
Thank You
P.S. Here is the code for populating the JTable
try {
DefaultTableModel noteDataModel = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
tbNotes.setModel(noteDataModel);
Object[] objects = new Object[4];
ListIterator<Todonote> todoNoteListIterator = noteList.listIterator();
while (todoNoteListIterator.hasNext()) {
todoNoteEntity = todoNoteListIterator.next();
DateFormat noteDateFormatter = new SimpleDateFormat("MM/dd/yyyy");
String noteDateTime = noteDateFormatter.format(todoNoteEntity.getUserDate())
+ " - " + todoNoteEntity.getUserTime().substring(0, 2) + ":" + todoNoteEntity.getUserTime().substring(2);
objects[0] = todoNoteEntity.getPrimaryKey();
objects[1] = todoNoteEntity.getUserContact().getName();
objects[2] = noteDateTime;
objects[3] = todoNoteEntity.getNotes();
noteDataModel.addRow(objects);
}
Edit 1
I updated the table model with
#Override
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
}
}
return Object.class;
}
It seems to work now, but dates are showing up as Oct 26, 2012 instead of yyyy/MM/dd - HH:mm - how would I fix that?
I'm not sure, but if you want to display a Date object as appointed format like yyyy/MM/dd - HH:mm, why not try the Renderer?
Related
I have a working code, But the problem is it's putting even the column name in to my HashSet. Please let me know if there is any error in this code.
EXAMPLE EXCELL:
|PhoneNumber | name|
|1234567890 | xyz |
|2131242342 | zyx |
|2332233222 | yxa |
|7625423423 | abc |
public HashSet<String> getAllColumnValue(String columnName){
HashSet<String> rowList = new HashSet<String>();
int columnIndex = 0;
boolean flage = false;
String value=null;
for (Row row : spreadsheet) {
if(!flage){
for (Cell cell : row) {
cell.setCellType(CellType.STRING);
value = cell.getStringCellValue().trim();
if (value.equalsIgnoreCase(columnName)) {
columnIndex = cell.getColumnIndex();
flage = true;
}
}
}
if (flage && !columnName.equalsIgnoreCase(value)) {
Cell cell1 = row.getCell(columnIndex);
if(cell1!=null){
if(cell1.getCellTypeEnum() == CellType.NUMERIC){
if (DateUtil.isCellDateFormatted(cell1)) {
DateFormat df = new SimpleDateFormat("MMM/dd/yyyy");
Date date = cell1.getDateCellValue();
rowList.add(df.format(date));
} else {
cell1.setCellType(CellType.STRING);
rowList.add(cell1.toString());
}
} else {
cell1.setCellType(CellType.STRING);
rowList.add(cell1.toString());
}
}
}
}
return rowList;
}
Lets say, above is my excell which has Phone Number and name as Columns and specic set of values on each column. Now I'm trying to read the data in Phone Number column and So I'm calling getAllColumnValue(PhoneNumber). My expectation is to return a HashSet
[1234567890, 2131242342, 2332233222, 7625423423]
but when I get the result it will be
[1234567890, 2131242342, 2332233222, 7625423423, PhoneNumber]
Here I'm calling getAllColumnValue method from an other class file and this method should return me all the values in specific column based on the column I specify while calling the method. Unfortunately it even shows the column name on the Hashset when I print the Returned list.
I'm trying to load some data from a database (I use Oracle's SQL Developer) into a JTable in java. I put the data from the database in a Vector of Vector, this is my load method which I put in a class called DBJobs:
public Vector load() {
try {
Vector tableData = new Vector();
Conn con = new Conn();
con.openConn();
con.statement = con.dbConn.createStatement();
ResultSet rs = con.statement.executeQuery("Select * from Jobs");
while (rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("Job_ID"));
row.add(rs.getString("Job_Title"));
row.add(rs.getString("Parent_Job_ID_1"));
row.add(rs.getString("Parent_Job_ID_2"));
row.add(rs.getString("Description"));
tableData.add(row);
}
con.closeConn();
return tableData;
} catch (SQLException ex) {
ex.printStackTrace();
return null;
}
}
Then I tried populating them into a JTable which I've made with an editor in another class:
private void populateJobsTable() {
Vector<String> tableHeader = new Vector<String>();
tableHeader.add("Job ID");
tableHeader.add("Job Name");
tableHeader.add("Parent Job ID 1");
tableHeader.add("Parent Job ID 2");
tableHeader.add("Description");
Vector tableData = dbJobs.load();
tblJobs.setModel(new DefaultTableModel(tableData, tableHeader));
}
But all I can see is 1 row of data in the table. I've tried printing how many data the Vector has and how many rows the Table has and they're both returning 49, which is the amount of data I have in my database. So why is my table only showing 1 data?
Edit:
I think this is the code generated to make the JTable:
tblJobs = new javax.swing.JTable();
tblJobs.setFont(new java.awt.Font("Tempus Sans ITC", 0, 14)); // NOI18N
tblJobs.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null}
},
new String [] {
"Job Name"
}
) {
Class[] types = new Class [] {
java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblJobs.setPreferredSize(new java.awt.Dimension(225, 16));
jScrollPane5.setViewportView(tblJobs);
if (tblJobs.getColumnModel().getColumnCount() > 0) {
tblJobs.getColumnModel().getColumn(0).setResizable(false);
}
First of all that is NOT a MCVE. How is that code complete? How can we compile and test that code? Did you not read my comment???
I would suggest you get rid of the IDE and learn how to create GUIs manually. What is the point of the IDE generating JTable with a custom TableModel. That code is completely useless since you then use create your own TableModel and use the setModel(...) method which will replace the model created by the IDE.
tblJobs.setPreferredSize(new java.awt.Dimension(225, 16));
The above code looks suspicious. You should not be setting a preferred size on a Swing component. The size of the table looks like it will only display one row at a time.
It that is not the problem then I will have no more suggestion until a proper MCVE is posted. Every question should have a MCVE so we don't spend time guessing what you may or may not be doing.
This question already has answers here:
Change the background color of a row in a JTable
(5 answers)
Closed 8 years ago.
ANSWER:
Im not allowed to post answers... thumbs up stackoverflow!!!
But here it is:
Holy freakin'....
I made it, actualy it was easier than i have thought....
Here's my solution:
tbl_needaction = new javax.swing.JTable()
{
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Date d = new Date();
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
java.util.Date acdate = null;
Component c = super.prepareRenderer(renderer, row, column);
// Color row based on a cell value
if (!isRowSelected(row))
{
c.setBackground(getBackground());
int modelRow = convertRowIndexToModel(row);
String sd = "";
sd = (String)getModel().getValueAt(modelRow, 5);
try {
acdate = df.parse(sd);
} catch (ParseException ex) {
Logger.getLogger(EditApplicationJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
if (d.compareTo(acdate)>=0){
c.setBackground(Color.RED);
}
}
return c;
}
};
I had to edit this via NotePad++ because NetBeans dosn't allow me to edit the automaticly generated initComponents().
QUESTION:
I know, there are lots and lots examples and tutorials for this issue, but none of them seems to work for me....
Im getting data from a sql-database which i show in a JTable. There is a date called "ActionPoint". Now i want to mark every row red where the "ActionPoint" equals today oder is "smaller" than today.
My Code to conpare today with the "ActionPoint" for ebery row in my jTable:
for(int row = 0;row < dbApplicantsTableModel.getRowCount();row++) {
String sd = "";
sd = (String) dbApplicantsTableModel.getValueAt(row, 5);
try {
acdate = df.parse(sd);
} catch (ParseException ex) {
Logger.getLogger(EditApplicationJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
if (acdate.compareTo(d)<=0){
}
}
So i should have my "row" which now should be painted red.
Can anyone provide a Method which simply gets a row, and then sets the background of this certain row red?
EDIT:
Now my code looks like this:
for(int row = 0;row < dbApplicantsTableModel.getRowCount();row++) {
String sd = "";
sd = (String) dbApplicantsTableModel.getValueAt(row, 5);
try {
acdate = df.parse(sd);
} catch (ParseException ex) {
Logger.getLogger(EditApplicationJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
if (acdate.compareTo(d)<=0){
dbApplicantsTableModel.setRowColour(row, Color.RED);
}
But ist doesnt set any backgrounds red!
Sadly i need a reputation of 10 to post images -.-
i want to mark every row red where the "ActionPoint" equals today oder is "smaller" than today.
Check out Table Row Rendering for an easy approach to solve this problem. The approach overrides the prepareRenderer(...) method of the JTable, so you can add you logic in one place with a simple "if statement".
I want to retrieve some data from a filtered row.
This is how i filter my table :
String makeText = makeFilterCombo.getSelectedItem().toString();
if (makeText == "All") {
makeText = "";
}
String numar = getEssRegex();
String impact = impactBox.getSelectedItem().toString();
if (impact == "All") {
impact = "";
}
TableModel model;
model = jTable1.getModel();
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
jTable1.setRowSorter(sorter);
List<RowFilter<Object, Object>> rfs = new ArrayList<RowFilter<Object, Object>>(2);
rfs.add(RowFilter.regexFilter(makeText, 2));
rfs.add(RowFilter.regexFilter(numar, 5));
rfs.add(RowFilter.regexFilter(impact, 9));
RowFilter<Object, Object> af = RowFilter.andFilter(rfs);
sorter.setRowFilter(af);
And this is how i try to get a value from a filtered row:
int f = search(connectedCarIndex);
connectedImage1 = jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(f), 10).toString();
connectedImage2 = jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(f), 11).toString();
connectedImage3 = jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(f), 12).toString();
System.out.println(connectedImage1 + "-------" + connectedImage2 + "------" + connectedImage3);
But none of this works ?
Can anybody help me ?
The code works and i can see the connected image name if the rows are shown
int f = search(connectedCarIndex);
I have no idea what the search(...) method does.
If you are searching the data that is displayed in the table then you would just use:
table.getValueAt(...);
If you are searching all the data that is stored in the TableModel then you would use:
table.getModel().getValueAt(...);
there is no need to convert the index if you know what you are searching.
I'm currently getting the value of my jTable as everybody does:
String d = jTable1.getModel().getValueAt( jTable1.getSelectedRow() , row ).toString();
The thing is that now I'm sorting my jTable with a rowsorter:
sorter = new TableRowSorter<TableModel>(modelo);
jTable1.setRowSorter(sorter);
private void filterTable(){
//If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter("(?iu)"+jFilter.getText(),0,1,2,3,4);//no filtrar la columna con imágenes porque hace cualquiera
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rf);
}
THE PROBLEM:
Once the table is filtered, the function getSelectedRow returns the correct row, but the getModel function returns the original model, not the one after filtering...
THE QUESTION:
How to get the correct value from the table when it is filtered?
You probably need to convert your "row" value to a model index value, using convertRowIndexToModel.
String d = Table1.getModel().getValueAt(convertRowIndexToModel(jTable1.getSelectedRow()) , column ).toString();
For future wanderers:
The problem was on the way of getting the value from the jTable:
This is wrong when you have a rowsorter:
String d = jTable1.getModel().getValueAt( jTable1.getSelectedRow() , row ).toString();
This is what you should be doing:
String d = jTable1.getValueAt( jTable1.getSelectedRow() , row ).toString();