Java - Modulus - Adding from one table to another - java

I have a JTable of which one column is pre-filled with 30min time slots (6.30-24.00).
Now I have another table which has a list of movie titles which contains a column with the duration of the movie (in minutes - e.g. 140 minutes).
Now I have a button that does this. I made a piece of code, which funnily enough, sometimes works and sometimes doesn't (after I add 3-4 titles). It adds to the time slots according to the math equation.It gives me :
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "DRAMA"
This is the code:
btnAddProg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int dur = Integer.parseInt(progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()+1).toString()) / 30;
int durT = Integer.parseInt(progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()+1).toString());
if(durT % 30 != 0)
{
dur += 1;
}
for(int i = 0; i < dur; i++)
{
String value = progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()).toString();
String value2 = progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()+2).toString();
channel1DataTitle.set(chOneTable.getSelectedRow()+i, value);
channel1DataGenre.set(chOneTable.getSelectedRow()+i, value2);
}
chOneTable.repaint();
} catch (IndexOutOfBoundsException f) {
JOptionPane.showMessageDialog(frame,
"Please select a row in the Channel table!",
"Channel row not selected",
JOptionPane.PLAIN_MESSAGE);
}
}
});
Can anyone tell me what's wrong?

It works when you click on the proper column and fails when you click on another, doesn't it? You have fixed logic (parsing the duration number) applied to a variable column (depending on the exact column the user clicked). Access the column with a fixed number, don't check for the selected column index.

You are trying to parse a String which does not translate into a number. It looks like the problem is you are working off of whatever the user has selected. You either need to restrict the data you are processing to be from certain columns in your table, or validate the data before trying to process it.

Related

Java Algorithm for retrieving and storing user dates using Firestore database

So I am trying to build this algorithm, what it will do is retrieve a reference (in this case a date), this date will be used to check against my firestore database to ensure that there are less than 3 employees who have booked this same date. So you will see here
startDateReference = 202131Thursday = Thursday, 1st of April, 2021
So I am running a loop, within this loop is a counter, this counter will take account the amount of times this reference is called in the loop. However, if it is looped 3 times the program will stop the loop, which is great, but I am unable to wrap my head around how to execute a condition if the loop has resolved as less than 3 iterations. For example, at the moment my database only has 2 of these reference stored, so I am successully able to call each iteration, but it does not take account that there is 1 more extra slot.
my code:
final Query query = db.collection("holidays").whereEqualTo("startDateReference",totalDateCode);
query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
//creating a map to obtain information
Map<String, Object> test = new HashMap<>();
//counter
int counter = 0;
boolean flag = false;
//retrieve data as a hashmap document
for (QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){
Note data = documentSnapshot.toObject(Note.class);
test.put("startDateReference", data.getStartDateReference());
Collection<Object> values = test.values();
//retrieve results as single values
for (Object string : values) {
do {
//System.out.println(string);
if (string.equals("202131Thursday")) {
counter++;
System.out.println("Checking for holidays" + counter);
} else if (counter == 3) {
System.out.println("could not save data it is packed");
} else {
System.out.println("storing details");
}
} while (counter == 3);
}
}
}
});
The results i get:
> I/System.out: 0
> Checking for holidays1 I/System.out: 1
> Checking for holidays2
But after this last result I expect this condition to execute as seen in the else condition within my code as there is a extra space (note i have not coded in my database store function i am using just string text to see how it would work right now and the database only has 2 of the reference, there is a extra slot which i am trying to store details in):
System.out.println("storing details");
Call another condition outside of all the loops and then after the loops have resolved you can use the counter as its final form to verify whether there is space or not using else if statements.

Java Jtable error with setting a value to a column after listener runs

I am working on the TableModelListener for a JTable. Now the jtable can get the value fine. but when it comes down to setting the value of the last column of the selected row. It gets wonky, not sure what the error is it just hangs up. Not seeing any errors on netbeans so not sure what to think. Because of this I am not even sure if the if statements work at all in terms of setting values. Should I be using or doing something else for this to happen ?
Update: It does appear to be an infinite loop. edited the code to a suggestion to check for Update table events but still having the same problem.
Here is the code below:
public class MyListener implements TableModelListener {
#Override
public void tableChanged(TableModelEvent tme) {
if (tme.getType() == TableModelEvent.UPDATE)
{
int rowcount = jDetailSubmitTable.getSelectedRow();
// Initial return when table is starting to be filled.
if(rowcount == -1 )
{
return;
}
int com = tme.getColumn();
// Number being Validated.
if(jDetailSubmitTable.getModel().getValueAt(rowcount, com).toString().trim().isEmpty())
{
JOptionPane.showMessageDialog(null, "Invaid Number selected.");
jDetailSubmitTable.getModel().setValueAt("0", rowcount, com);
return;
}
try
{
Double.parseDouble(jDetailSubmitTable.getModel().getValueAt(rowcount, com).toString().trim());
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Invaid Number selected.");
jDetailSubmitTable.getModel().setValueAt("0", rowcount, com);
return;
}
// Adjusted amount is calculated below.
double nur = Double.parseDouble(jDetailSubmitTable.getModel().getValueAt(rowcount, 9).toString().trim());
double our = Double.parseDouble(jDetailSubmitTable.getModel().getValueAt(rowcount, 8).toString().trim());
double diff = nur - our;
double nunits = Double.parseDouble(jDetailSubmitTable.getModel().getValueAt(rowcount, 11).toString().trim());
double ans = diff * nunits;
jDetailSubmitTable.getModel().setValueAt(ans, rowcount, 12);
}
}
}
The following line will get the selected row index, that index being a view index since you ask this from the JTable instance:
int rowcount = jDetailSubmitTable.getSelectedRow();
Later on you use this view index to index the model:
jDetailSubmitTable.getModel().getValueAt(rowcount, com)
You should first convert this view index to a model index using JTable.convertRowIndexToModel:
int selrowid = jDetailSubmitTable.getSelectedRow();
selrowid = jDetailSubmitTable.convertRowIndexToModel(selrowid);
[...]jDetailSubmitTable.getModel().getValueAt(selrowid, com)[...]
I gave a longer explanation about view vs model and the need to convert indexes in this answer on SO.
Update: #camickr made the correct observation that you should be using the data that comes with the TableModelEvent, i.e. TableModelEvent.getFirstRow(), TableModelEvent.getLastRow() and TableModel.getColumn(). These methods return model indexes.

Select ComboBox Item with only part of the Item

For a Java Schoolproject I would like to have a table from witch you can select a Item that then shows up on a new window. In that window you can change things like ComboBoxes and others. My only problem is, that I dont know how to select the Item of the ComboBox I need. All the ComboBoxItems are Objects and I dont know how to handle this.
My ComboBoxItem looks like this:
Apprentice [person=Person, DB ID: 9, Kappa Kappa, Kappastrasse 21,
CityID: 4521, kappa.kappa#kappa.ch, idpersonen=9,
vertragsstart=2020-01-02, ausbildungsct=2, id=6]
Now, my Question is, how do I select the ComboBoxitem where the id=6, all the things I found needed the whole Object to select a special Item. How would you guys go at this problem?
Good luck and thanks for the Help.
Bono
All I had to do was a really simple while with a for and a if.
int trys = 0;
while (0 == apprenticeComboBoxZeugnis.getItemCount() && trys < 10000) {
System.out.println(apprenticeComboBoxZeugnis.getItemCount());
for (int i = 0; i < apprenticeComboBoxZeugnis.getItemCount(); i++) {
apprenticeComboBoxZeugnis.setSelectedIndex(i - 1);
int spacko = getApprenticeCombo();
if (spacko == lehrlingsid) {
TableFilterListenerZeugnis tableFilterListenerZeugnis = new TableFilterListenerZeugnis(
this);
tableFilterListenerZeugnis.updateNoten();
break;
}
}
trys++;
}
This first trys until the number of Objects is not = 0 and after that looks at every object, cuts out the id with getApprenticeCombo() and compares it with my id I allready have. If they match it breaks out and is done with it.

Split an excel content and display in console ignore Blank Cell

In my Excel cell I've data as below. And it is in a single cell.
01/2015 to present
02/2010 - 04/2010
01/2008 - 12/2009
I want to split this cell and display result as
Date 1 - 01/2015 to present
Date 2 - 02/2010 - 04/2010
Date 3 - 01/2008 - 12/2009
I'm not sure of how many different lines of data will be in a single cell. There may be up to 10 Lines, then it should print the same like in the below format
Date (counter) - (Date Value)
Thanks for the hint #Saurabh
I'm using the below code now. and able to print the dates in the above format.
if (!covDate.equals(null) || !(covDate == "")|| !(covDate == null) || !covDate.equals(""))
{
String[] date = covDate.split("\\n");
for(int i=0;i<parts.length; i++){
System.out.println("Date "+ i + " - "+date[i])
}
}
else{
System.out.println("Dates Missing");
}
Here Basically I've 2 columns in my Excel and in the second column I've these dates. And there are instances where in there is data in first column but data is missing in Dates column. And there it is throwing me a null pointer Exception Also in my eclipse my else block is showing error as a dead block
please let me know how can i fix these.
Thanks
I have simplified your test expression below, the date variable inside the for loop is replaced with parts :
if (covDate != null && !covDate.equals(""))
{
String[] parts = covDate.split("\\n");
for(int i=0;i<parts.length; i++){
System.out.println("Date "+ i + " - "+parts[i])
}
}
else{
System.out.println("Dates Missing");
}
Firstly, you should not such a long ternary operator, instead you can use, StringUtils.isEmpty(object) ..
This is available in org.apache.maven.shared.utils.StringUtils. Once you have this, you can read the object to this method, and perform accordingly.
Secondly, coming to second column, you can try, if(StringUtils.isEmpty(cellValue)) if this gives you true, then go ahead and split the string, else continue.

Verifying row is not empty before adding new row

I'm developing a tool which is supposed to save the content from a JTable to a CSV file, I have this "add row" button to add a new row, but I need the last row to be filled on every cell and then be allowed to add a new row.
Here is the code I have, but this doesn't create the new row nor throw any errors on console.
private void btnAddRowActionPerformed(java.awt.event.ActionEvent evt) {
for(int i=0;i<=jTable1.getColumnCount();i++){
if(jTable1.isRowSelected(jTable1.getRowCount())){
do{
model.insertRow(jTable1.getRowCount(), new Object[]{});
} while(jTable1.getValueAt(jTable1.getRowCount(), i).equals(""));
}
}
}
Okay, so what you seem to be saying is, the user should not be allowed to add a new row until the last row is fully completed...
You existing loop doesn't make sense, basically, for each column, you are checking to see if the last row is selected, and inserting a new row for each column which is blank ("")...?
Remember, generally Java is zero indexed, this means, the last row is actually jTable1.getRowCount() - 1, so, it's unlikely that your if isRowSelected would be true, which is actually a good thing, cause otherwise you would have had a real mess...
Assuming I understand your question correctly (as it's a little vague), you could try something more like this...
boolean rowCompleted = true;
int lastRow = jTable1.getRowCount() - 1;
if (jTable1.isRowSelected(lastRow)) {
for (int col = 0; col < jTable1.getColumnCount(); col++) {
Object value = jTable.getValueAt(lastRow, col);
if (value == null || value.toString().trim().isEmpty()) {
rowCompleted = false;
break;
}
}
}
if (rowCompleted) {
// Insert new row...
} else {
// Show error message
}
Maybe use a TableModelListener.
Every time a cell is updated on the last row of the table you check to make sure all columns have data. If all columns have data you enable the "Add Row" button, otherwise you disenable the button.
I was checking this post and I used the code posted by MadProgrammer, but I made a few modifications and I got this working properly according to your need. If you want you can ask me for the project and I can happily provide it to you
private void btnAddRowActionPerformed(java.awt.event.ActionEvent evt) {
boolean rowCompleted;
int lastRow = jTable1.getRowCount()-1;
if(jTable1.isRowSelected(lastRow)){
for(int col=0;col<jTable1.getColumnCount();col++){
Object value = jTable1.getValueAt(lastRow, col);
if(value == null || value.toString().trim().isEmpty()){
rowCompleted=false;
}
else{
rowCompleted=true;
}
if(rowCompleted==true){
model.insertRow(jTable1.getRowCount(), new Object[]{});
}
else{
JOptionPane.showMessageDialog(null, "Something went worng. Try this:\n - Please select a row before adding new row.\n - Please verify there are no empty cells","Processing table's data",1);
}
break;
}
}
else{
JOptionPane.showMessageDialog(null, "Something went wrong. Verify this:\n - There is not any row selected.\n - You can only create new rows after last row","Processing table's data",1);
}
}
I hope this could help you, but first say thanks to MadProgrammer :D

Categories

Resources