Multiple Search Results, One GUI - java

I am searching through an array and matching the users entered date with ones stored in the array.
The code is working fine and finds dates or gives appropriate error messages perfectly, the only issue is due to the nature of my program it leaves the possibility of multiple records having the same date.
Now, I only have one form displaying each search result in this format:
lbl txtField
lbl txtField
etc, if the date is matched, it will display the REST of the data matching the record in the text fields.
Now, how would it be possible to display every record's data that has matched a date?
My Code:
public void searchDay() {
String idInputString = JOptionPane.showInputDialog(null, "Please enter the Date you're searching for using the format: DD/MM/YYYY");
for (int i = 0, count = 0; i < orderID.length; i++) {
if (idInputString.equals(startDate[i])) {
txtOrderID.setText(orderID[i]);
txtOrderForename.setText(customerForename[i]);
txtOrderSurname.setText(customerSurname[i]);
txtOrderAddress1.setText(address1[i]);
txtOrderAddress2.setText(address2[i]);
txtOrderTown.setText(town[i]);
txtOrderCounty.setText(county[i]);
txtOrderPost.setText(postCode[i]);
txtOrderCarModel.setText(carModel[i]);
txtOrderCarReg.setText(carReg[i]);
txtOrderStartDate.setText(startDate[i]);
txtOrderStartTime.setText(startTime[i]);
txtOrderSerial.setText(serialNum[i]);
count++;
}
if(i == orderID.length - 1 && count==0){
JOptionPane.showMessageDialog(null, "Order ID Doesn't Exist", "Error!", JOptionPane.WARNING_MESSAGE);
break;
}
}
}
Thank you.

Create more text fields on the fly, or drop results into a JTable.

The final UI could have a JList at the PAGE_START of the GUI that lists the orders for a day or range, but only displays the 'order number'. Then have a JPanel that contains a group of labels and field in the CENTER to display the details of an order selected in the list.
A JTable as suggested by #Ray might be a viable alternative, but I sometimes feel the data is more complex than can be well presented in a single table row (using one row per order).

Related

Getting an object from JTable

I want to get information about user from the JTable. Everything is okay, but when I sort the array by name, the objects get read wrong. Example:
Here is everything ok
Above everything is ok. I choose 4 value from the table, shows me 4 items from the Users list. Two books are displayed. But now I sort by 'number of loans', and i choose user with two loans. But the array reads as 'you chose the first value' and shows the first value from the User list.
After sorting
I'd like to receive a specific user after selecting from the board. Thanks.
My code:
tablicaWypozyczen.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int row = tablicaWypozyczen.rowAtPoint(e.getPoint());
int col = tablicaWypozyczen.columnAtPoint(e.getPoint());
if (row >= 0 && col >= 0) {
JOptionPane.showMessageDialog(null, Dane.uzytkownicyZWypozyczeniami.get(row).toString(), "Informacje o użytkowniku", 1);
System.out.println(tablicaWypozyczen.getSelectedRow());
}
}
}
});
but when I sort the array by name,
Why are you sorting the Array?
Data is stored in the TableModel. The sorting should be done on the table, not on data in some external array. You don't want data in two places, it is too hard to keep the data in sync.
Read the section from the Swing tutorial on Sorting and Filtering for more information.
If you want to get the sorted value from the table you use:
table.getValueAt(table.getSelectedRow(), theColumn);

JTable stop cell editing without user click

I'm trying to solve a strange problem with my program. This program creates a series of GUI's and JTables that give a user the ability to generate an XML file. One of these tables is for creating the "statements". I won't get into detail as far as that except to say that the data is stored in multiple 2D arrays which are in turn stored in a hash map.
Here is what happens. When a user enters the Statement screen a JTable is generated using the contents from the 2D array. This data populates the cell's which the user is able to modify. One of these cells (and the most important) is the amount. The amounts they set for the rows much match another amount from another class.
At the bottom of the table is a "finished" button. When the user clicks this button the logic will check to see if the money amounts match. If they do then the program will update the 2D array with any changed values and dispose of the JTable.
My problem is that once a user updates a cell and clicks "finished" the last updates made do not work. Essentially the user must first click somewhere else in the table and THEN hit finished. I would like this action to happen automatically so that when the user clicks "finished" cell editing is stopped. Here is the code for the finished button:
finishedButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
//Creates another table model for the finished button logic.
DefaultTableModel dm = (DefaultTableModel)StatementGUI.tbl.getModel();
//Gets the total number of table rows.
int rows = dm.getRowCount();
//Creates a variable to store the statement transaction total.
double statementTransactionTotal=0;
//For each row in the table.
for(int i = 0; i < dm.getRowCount(); i++){
//Gets the total of all transactions in the table.
String currentTotal = tbl.getValueAt(i, 3).toString();
Double currentTotalDouble = Double.parseDouble(currentTotal);
statementTransactionTotal=statementTransactionTotal+currentTotalDouble;
}
//Creates a decimal format and applies the statement total.
DecimalFormat df = new DecimalFormat("0.00");
String currentTotalDF = df.format(statementTransactionTotal);
//Stops editing on the table so that the data can be used.
if(null != tbl.getCellEditor()){
tbl.getCellEditor().stopCellEditing();
}
//If the statement total matches the transaction total..
if(currentTotalDF.matches(ClearedMainGUI.currentTransactionAmount)){
//For each row in the table..
for(int i = 0; i < dm.getRowCount(); i++){
//Will replace the hash/array value with the table value.
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][0]=tbl.getValueAt(i, 0).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][1]=tbl.getValueAt(i, 1).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][2]=tbl.getValueAt(i, 2).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][3]=tbl.getValueAt(i, 3).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][4]=tbl.getValueAt(i, 4).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][5]=tbl.getValueAt(i, 5).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][6]=tbl.getValueAt(i, 6).toString();
ClearedMainGUI.Transactions.get(ClearedMainGUI.selectedRow)[i][7]=tbl.getValueAt(i, 7).toString();
}
//For each row in the table..
for(int i = rows - 1; i >=0; i--){
//Removes the current row so the table will be empty next time.
dm.removeRow(i);
}
//Removes the frame and goes back to the previous GUI.
frame.dispose();
//If the statement total and transaction total do not match..
}else{
JOptionPane.showMessageDialog(null, "The statement total entered: $"+statementTransactionTotal+" " +
"does not match the transaction total of: $"+ClearedMainGUI.currentTransactionAmount);
}
}
});
I think my problem is with this line:
if(null != tbl.getCellEditor()){
tbl.getCellEditor().stopCellEditing();
}
This only seems to work once the user has clicked another area of the table after editing a cell.
I appreciate the help!
My problem is that once a user updates a cell and clicks "finished" the last updates made do not work.
Check out Table Stop Editing for two approaches:
You can either:
Add code to the ActionListener:
if (table.isEditing())
table.getCellEditor().stopCellEditing();
or set a property on the table:
JTable table = new JTable(...);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
Edit:
When the user clicks finished all the cell data will be saved to a 2D array.
Why? All the data is already stored in the TableModel.
In any case you need to stop editing BEFORE you attempt to copy data from the TableModel to the Array.

Select A row from Jtable based on Jtextfield Input

I have a JTable displaying contents in this format:
Part Number Quantity Price
SD1131 7 1,000
SD6534 6 2,000
On the same frame I have a JTextfield(txtNo). I need it such that when the user types the Part Number on the JTextfield, the corresponding record is selected on the JTable. So far I have only been able to select records based on the row number like this:
txtNo.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
int index1 = 0;
int index2 = 0;
try {
index1 = Integer.valueOf(txtNo.getText());
tbStore.setRowSelectionInterval(index2, index1);
} catch (Exception ae) {
ae.printStackTrace();
}
}
});
How can I implement the same method to select the JTable row based on the input of the JTextfield?
You will need to find the item in your table for which the part number is equal to the part number entered in the textfield. Steps to take:
Read the contents of your textfield
Search the index of the matching element in the TableModel
Convert that index to the corresponding row index in the JTable using the convertRowIndexToView method (to take in account sorting, filtering, ... )
Use the setRowSelectionInterval method of the JTable to select that row
As an alternative, you can use the JXTable of the SwingX project which has searching capabilities built-in. The SwingX library also includes a component which allows to search such a JXTable (see JXSearchPanel and JXSearchField)
You should interrogate the TableModel and find out which row contains the part number you are looking for:
for(int i=0;i<tbStore.getRowCount();i++) {
// 0 is for the column Part number
if(tbStore.getValueAt(i, 0).equals(Integer.valueOf(txtNo.getText())) {
tbStore.setRowSelectionInterval(i, i);
break;
}
}
Caveats: I haven't tested this code, but it should give you at least the basic idea.

Preserve selected model row in sorted JTable across model update

I'm having difficulties getting the following code to preserve the logically selected row in the model if the JTable has been sorted.
It works as intended when no sorting is applied.
private void updateAccountTable() {
accountsTable = guiFrame.getAccountsTable();
// Preserve selected model row
String accountNumber = "";
int selectedRow = accountsTable.getSelectedRow();
if(selectedRow >= 0){
accountNumber = (String)accountsTable.getValueAt(selectedRow, 0);
}
// Preserve sort order
// Keep eclipse happy. better way??
List <? extends SortKey> keys = accountsTable.getRowSorter().getSortKeys();
// Update displayed accounts
DefaultTableModel model = (DefaultTableModel) accountsTable.getModel();
model.getDataVector().clear();
Object[][] tableContents = accountList.getAccountsAsArray(true);
model.setDataVector(tableContents, tableHeaders);
model.fireTableDataChanged();
// reset sort order
accountsTable.getRowSorter().setSortKeys(keys);
// If updated model contains previously selected account, reselect
if (!accountNumber.equals("") && null != accountList.getAccount(accountNumber)){
for (int row=0; row<accountsTable.getRowCount(); row++){
String an = (String)accountsTable.getValueAt(row, 0);
if (an.equalsIgnoreCase(accountNumber)){
accountsTable.setRowSelectionInterval(row, row);
break;
}
}
}
else {
accountsTable.clearSelection();
}
}
Unfortunately setRowSelectionInterval() doesn't updated the selected row as expected, despite being called with the correct view row number. It seems to do nothing.
.....So,
Why is setRowSelectionInterval() failing to updated the selection, or what have I missed?
The row obtained from getSelectedRow() is in view coordinates, while the model coordinates have been changed by the intervening update. Quoting from the relevant tutorial section:
This distinction does not matter unless your viewed data has been rearranged by sorting, filtering, or user manipulation of columns.
You will need to use the conversion methods described near the end of Sorting and Filtering, which suggests:
When using a sorter, always remember to translate cell coordinates.
When you click on Jtable header to sort it, and click on a row (ex. 3rd row), you will get the value of unsorted JTable's row. To avoid this situation, use this LOC.(ik this is irrelvant to what you're trying to do but for others w/ similar problems)
int row = tblUser.getSelectedRow();
//Without below line, the value you get would be the row before sorting
int correctModel = tblUser.convertRowIndexToModel(row);
//Get username and use it to find its corresponding tuple
String username = (tblUser.getModel().getValueAt(correctModel, 1)).toString();
My table looks like this and Im trying to get the username of the selected row and w/o the 2nd LOC, I'd get the unsorted JTable's row value even after sorting it:
---------------------
| id | username |
---------------------
| | |

how to select the ages which are less than or greater than from drop down in grails and groovy

I have a requirement that should have one drop down containing some conditions on age.
like less than 10days,between 10 to 30 days,between 1 month to 3 months,between 4 month to 12 months,between 1yr to 2 yr.
I have domain class containing one property age(integer).and i am calculating age form dob to current date and storing in DB.I have search criteria to search based on age in search page,So how can i display these condition vales in drop down and when i select one option how to display the result based on age.
presently i am displaying all ages in drop down form the DB, please find the code and help me in doing this, if its not clear please write the comments so that i can explain u.
this is my drop down contaning all dobs
<td><span id="availableAge" ></span></td>
This is my script to get dobs from controller with an ajax call
function generateAge(data){
var list ="<select style='width:100px' id='age' name='age'><option value=''>-Select-</option>";
var opt;
for(var i=0; i<data.ageDetails.length; i++){
opt = "<option value="+data.ageDetails[i].age+">";
opt = opt+data.ageDetails[i].age;
opt = opt+"</option>";
list = list+opt;
}
list = list+"</select>";
var listObj = document.getElementById("availableAge");
if(listObj){
listObj.innerHTML = list;
}
}
It's a bad idea to store age in DB, as it changes all the time - better stick with DOB.
As the option set is fixed, make something like an enum for it, use its values() to render a select
enum AgeCriteriaEnum { NONE, LESS_THAN_10, BETWEEN_10_AND_30, ... so on }
and just do a switch() like:
AgeCriteriaEnum ageEnum = AgeCriteriaEnum.valueOf(params.ageEnum)
Date today = new Date()
Patient.withCriteria {
switch(ageEnum) {
case AgeCriteriaEnum.NONE:
break;
case AgeCriteriaEnum.LESS_THAN_10:
ge('dob', today-10)
break;
case AgeCriteriaEnum.BETWEEN_10_AND_30:
lt('dob', today-10)
ge('dob', today-30)
break;
//... so on
}
}

Categories