Changing source of JTable in Netbeans and updating it - java

I am working on a GUI that will feature a table that has been manually connected to a database. Above this table there are 3 radio buttons that will "decide " what criteria is to be used when fetching the data( All rows have a boolean value, depending on the button pressed it is supposed to return either 1, 0 or both).
This is the code for the table(NOTE i am using netbeans gui designer)
ServiceTable = new javax.swing.JTable();
int radiovalue = 0;
if (RadioActive.isSelected()) radiovalue = 0;
else if (RadioAll.isSelected()) radiovalue = 1;
else if (RadioFinished.isSelected()) radiovalue = 2;
Object[][] DataAct = null;
try {
DataAct = SQL.MYSQL_FETCH_OMNI_DATA(radiovalue);
} catch (Exception ex) {
Logger.getLogger(MainforAdmin.class.getName()).log(Level.SEVERE, null, ex);
}
String[] Colnombs = SQL.MYSQL_ROW_NOMBER();
ServiceTable.setAutoCreateRowSorter(true);
ServiceTable.setModel(new javax.swing.table.DefaultTableModel( DataAct, Colnombs ));
TableContainer.setViewportView(ServiceTable);
This works as it should and the 2 external functions return arrays that make the table display what it should display (Which is as the program starts all the "active " transactions)
However i want to be able to change the table so that it will evaluate if radioactive is equals to 0, 1 or 2 (The number is going to determined what data the function fetches). The program outputs the MYSQL tables trough System.out.print perfectly with the diffrent criterias. So I know my functions are working. But I can not figure out how I am to make the entire table "refresh" after another radiobutton is selected..
This is my event code for Mousepressed for a radio button.
TableRefresher();
System.out.println("Pressed");
And Pressed is outputed so i know this code has been summoned after clicking on the radio button. Here is the TableRefresher function.
Write.Echo("The TableRefresher method hath been summoned");
//This code is going to evaluate which button is selected as of now.
MainforAdmin table = new MainforAdmin();
if (table.RadioActive.isSelected()) radiovalue = 0;
else if (table.RadioAll.isSelected()) radiovalue = 1;
else if (table.RadioFinished.isSelected()) radiovalue = 2;
Object[][] DataAct = null; //This code is going to innitialize the tablecontents.
try {
DataAct = SQL.MYSQL_FETCH_OMNI_DATA(radiovalue);//This code assigns the table contents And i know this works because it correctly outputs the table with the diffrent where clause (where state = x or the status as you saw on the picture.)
} catch (Exception ex) {
Logger.getLogger(MainforAdmin.class.getName()).log(Level.SEVERE, null, ex);
}
String[] Colnombs = SQL.MYSQL_ROW_NOMBER(); //Assigns the column names and works is used as the table is created so this works.
table.TableContainer.remove(table.ServiceTable);
table.add(table.ServiceTable, null);
table.ServiceTable.setModel(new javax.swing.table.DefaultTableModel( DataAct, Colnombs ));
table.ServiceTable.revalidate();
table.ServiceTable.repaint();
table.TableContainer.setViewportView(table.ServiceTable);
Yet as this method is summoned(Which i know it is from the console output) nothing happens to the JTable in the GUI...It stays the same.
So how am i supposed to refresh the table after a different criteria for fetching the data has been applied ? I have looked at other suggestions here on this site but none of them worked or gave me what i needed.
Any answers would be very appreciated, and please forgive me if this is an easy question I am by no means a Programming deity.
If it makes any difference the JTable is in a Scrollpane..
Sincerly...
//Orville Nordström.

Just as a start:
If it makes any difference the JTable is in a Scrollpane.
That's correct and it must keep in this way. It makes no difference to solve the main problem though.
So how am i supposed to refresh the table after a different criteria for fetching the data has been applied?
Code quote:
table.TableContainer.remove(table.ServiceTable);
table.add(table.ServiceTable, null);
table.ServiceTable.setModel(new javax.swing.table.DefaultTableModel( DataAct, Colnombs ));
table.ServiceTable.revalidate();
table.ServiceTable.repaint();
table.TableContainer.setViewportView(table.ServiceTable);
Please note this is kind of spaghetti code and it's not clear which is the table to be updated. However the correct way to update a table is not removing / re-creating / re-locating it but working with / refreshing its table model instead. See examples here (includes SwingWorker to make database calls in a background thread), here and here. Please have a look to those answers, there are explanations to make the point clear.
Off-topic
Looking at the quoted lines above, I'd suggest you to avoid using static members. Those are intended to very specific cases (i.e.: constants) but not to general use, and often breaks the encapsulation principle. In this particular case they led to an unintelligible chain of calls that are probably wrong and causing an unexpected hard-to-debug (for us) behavior.

if I understand your problem is that you can not "refresh" the table, in my programs I use this method (DefaultTableModel):
private void jButtonActionPerformed(java.awt.event.ActionEvent evt) { .......
..................
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object[][]{},
new String[]{
"CLMN1", "CLMN2", "CLMN3", "CLMN..."
}) {});
enter code here
model = (DefaultTableModel) jTable.getModel();
model.addRow(new Object[]{("YOUR ROW"}); ----> in a While(or FOR), for any rows
bye :)

Related

Get the count of code complexity due to type of control structures line by line into a table view

I have developed a desktop application using java swing using the netbeans IDE. The purpose of it is to measure the complexity of a program statement due to the type of control structures. For a program statement with "if", "for", "while" and "catch", a weight of 1, 2, 2, and 1 are assigned respectively. Additionally, a weight of "n" is assigned for a program statement with a "switch" statement with "n" number of cases. All other statements are assigned with a weight of zero.
I have implemented the solution for the above problem already, and I need to demonstrate the complexity "of each program statement" in a tabular format. I have used a jTable for that purpose with the column names "Line no", "Program statement" and "Complexity count".
Though I have taken the total count of complexity, I have no idea about getting the count line by line and display it in the jTable. The complexity count relevant for each program statement should be displayed against each line number and the statement.
Here is my code.
https://github.com/nirmaniPathiranage/Complexity-measuring-tool/blob/master/src/spm/FilesDemo.java
I have implemented the function of loading table data from the line 733 onwards. (action performed on jButton11).
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed{}
I expect the output of complexity for each program statement against each line number and program statement in a table view.
I can't seem to figure this out. Any help would be appreciated.
A possible issue i can see with implementing a jTable to show complexities for each line in a program is not knowing the number of lines before hand. But this too can be solved easily with a naive approach of using an ArrayList<> and a TableModel as in below.
//Names of the columns
String columns[] = {"Line no","Program statement","Complexity count"};
//Table model, initiate with 0 columns
DefaultTableModel tableModel = new DefaultTableModel(columns, 0);
JTable table = new JTable(tableModel);
To make things clearer, implementing a POJO class for contents to be showed in a table row would be ideal.
public class TableRow {
private int lineNo;
private String statement;
private int cmplxCount;
//You may implement the getters and setters as well
}
While the program iterates through each and every line calculating the complexity, make sure to create a new TableRow object and necessary data and add them to an ArrayList
ArrayList<TableRow> list = new ArrayList<TableRow>();
//Create an object each time a line is iterated for complexity calculations.
TableRow newRow = new TableRow(4,"for-loop",1);
list.add(newRow);
After the iteration is over, add those data in the ArrayList to an Object array and pass them to the jTable.
for (int i = 0; i < list.size(); i++){
int lineNo= list.get(i).getLineNo();
String statment = list.get(i).getStatement();
int cmplxCount= list.get(i).getCmplxCount();
Object[] data = {lineNo, statement , cmplxCount};
tableModel.add(data);
}

How could i make my app learn like a keyboard?

So I've made an app that makes sentences, much like a keyboard of words and pictures, what I'd like to achieve is a kind of predictive text where if a user chooses X they are shown Y and Z, user doesnt want either of these and chooses A.
The next time the user picks X they are shown A, Y and Z, so it learns like your keyboard would, my words are stored in a database and right now i have a crude solution where if the user chooses X they are shown Y and Z, and I also track how many times each card is clicked and show them too but it has no context of full sentences or previously made sentences, i hope this is making sense as I've no idea where to start I've been looking at maybe a hashmap full of essentially TAGS as key value pairs and adding to it but I need to research this, I've also looked at candidate view but that would mean declaring my app as an Input Method I believe and I need the normal keyboard for other things, but I'm not sure how that works or if it's remotely viable so I'm hoping someone can educate me here or point to a better solution.
Below I'll post excerpts of what I'm doing thus far
//Check what card was pressed and update predictedCardActivityDB example
//to carry on like this would mean a lot of typing
//and not a lot of smart results
if (cardsChoice.predictive == true) {
String item = cardWriter.getCardSpeech();
switch(item){
case " I":
String[] I_String = {"LIKE","LOVE","WANT"};
predictedCardActivityDB.prepareCardData
(I_String,getActivity(),prefString);
break;
case " I'm":
String[] Im_String =
{"HAPPY","SAD","ANGRY","HUNGRY","FEELING"};
predictedCardActivityDB.prepareCardData
(Im_String,getActivity(),prefString);
break;
And this is the prepareCardData method excerpt nothing to see here just updates the lists based on the string array
public static void prepareCardData
(String[] predictionArray, Context context ,String prefString){
//boring database stuff
DaoMaster.DevOpenHelper helper =
new DaoMaster.DevOpenHelper(context, "ADD_NEW_CARD", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession daoSession = daoMaster.newSession();
addNewCardDao leaseDao = daoSession.getAddNewCardDao();
QueryBuilder qb = leaseDao.queryBuilder()
.orderDesc(addNewCardDao.Properties.Clicked);
QueryBuilder qb2 = leaseDao.queryBuilder()
.orderDesc(addNewCardDao.Properties.Clicked);
predictsList.clear();
String[] strings1 = {"ORIGINAL","SIMPLE","PHOTOS", "USER"};
switch (prefString){
case "PHOTOS":
if (predictionArray != null){
//qb gets any card clicked >2
//qb gets all favourites tagged by a boolean
qb.where(addNewCardDao.Properties.CardIconType.in(strings1),
qb.or(addNewCardDao.Properties.Clicked.ge(2),
addNewCardDao.Properties.Fav.ge(true)));
predictsList = qb.list();
//qb2 gets any card that matches a word from the passed in
//string array predictionArray
qb2 = leaseDao.queryBuilder();
qb2.where(addNewCardDao.Properties.CardIconType.in(strings1),
qb2.or(addNewCardDao.Properties.CardName.in(predictionArray),
addNewCardDao.Properties.CardTitle.in(predictionArray)));
temptList = qb2.list();
db.close();
temptList.addAll(predictsList);
predicts_card_adapter.notifyItemInserted(predictedCardActivityDB.temptList.size());
predicts_card_adapter.notifyDataSetChanged();
predicts_card_adapter = new predictsCardAdapter(temptList,itemTouchListener);
predictsrecyclerView.setAdapter(predicts_card_adapter);
}else{
qb.where(addNewCardDao.Properties.CardIconType.in(strings1),
qb.or(addNewCardDao.Properties.Clicked.ge(2),
addNewCardDao.Properties.Fav.ge(true)));
predictsList = qb.list();
//this should work
predicts_card_adapter.notifyDataSetChanged();
predicts_card_adapter = new predictsCardAdapter(predictsList,itemTouchListener);
predictsrecyclerView.setAdapter(predicts_card_adapter);
db.close();
System.out.println("else, predictsList size " + predictsList.size());
}
break;
}
//should be able t delete this and use the two commented out piecess of code above
//the result being the predicted cards coming first in the list
/*
predicts_card_adapter.notifyItemInserted(predictedCardActivityDB.temptList.size());
predicts_card_adapter.notifyDataSetChanged();
predicts_card_adapter = new predictsCardAdapter(temptList,itemTouchListener);
predictsrecyclerView.setAdapter(predicts_card_adapter);
*/
}

Multiple Search Results, One GUI

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).

How to submit multiple vales from form control to the database

I have 8 MC questions in a panel. When submitted, I want all the selected answer to be recorded in the database. However, my code is only recording 1 question. Here is the code. (Note: All the jRadioButton names are not same since they are in one panel together.)
Here is the code :
public void submitButtonClicked(){
for(int i=1;i<9;i++){
username = "Smith";
questionID = i;
if(jRadioButton1.isSelected()){answer = jRadioButton1.getText();}
else if(jRadioButton2.isSelected()){answer = jRadioButton2.getText();}
if(jRadioButton3.isSelected()){answer = jRadioButton3.getText();}
else if(jRadioButton4.isSelected()){answer = jRadioButton4.getText();}
// and So on until the question 8.
}
Consider creating an array or ArrayList of the ButtonGroups for each JRadioButton cluster. You can then use a for loop to get the selection from each ButtonGroup which is the model of the JRadioButton selected, and if not null, get its actionCommand String.
For example, please look at my code here.
In your solution only one value is recorded because if one if statement is executed then it will bypass all other else if statements.
You could create a array of jradiobuttons and then use them in for loop,traversing each button one by one and then recording its answer.

how to Save a jpanel containing combo-boxes and text-boxes in java netbeans?

I am creating an application which helps solving problems of an accounting book. The application has 12 chapters. All chapters contains 15-20 problems. The problem is displayed in a JPanel containing various combo-boxes and formatted-text boxes. suppose i solved a problem half and want to save so that next time i can load that half solved question.
Saving should be done by clicking save from menubar. And loading by load from the menubar
All menubars and problem sheet are working but i am not able to save any thing. I was using jFilechooser...
Is their any way to do that?
How to save a panel with filled combo-boxes items and text-boxes. And is their any way to know that user has made any changes in any items so that on closing the problem i can again ask to save it first and then exit.
Thanks in advance.
Some of my codes:
private void openBtnMouseClicked(java.awt.event.MouseEvent evt) {
opening();
}
public void opening() {
JFileChooser chooser=new JFileChooser();
int choice=chooser.showOpenDialog(this);
javax.swing.JComboBox[] sourceALE = {aaCombo, baCombo, caCombo, daCombo, eaCombo, faCombo, gaCombo, haCombo, iaCombo, jaCombo, kaCombo,
alCombo, blCombo, clCombo, dlCombo, elCombo, flCombo, glCombo, hlCombo, ilCombo, jlCombo, klCombo,
aeCombo, beCombo, ceCombo, deCombo, eeCombo, feCombo, geCombo, heCombo, ieCombo, jeCombo, keCombo};
javax.swing.JTextField[] sourceP = {aeval1, beval, ceval, deval, eeval, feval, geval, heval, ieval, jeval, keval};
String [] comboboxes={"aaCombo", "baCombo", "caCombo", "daCombo", "eaCombo", "faCombo", "gaCombo", "haCombo", "iaCombo", "jaCombo", "kaCombo","alCombo", "blCombo", "clCombo", "dlCombo", "elCombo", "flCombo", "glCombo", "hlCombo", "ilCombo", "jlCombo","klCombo","aeCombo", "beCombo", "ceCombo", "deCombo", "eeCombo", "feCombo", "geCombo", "heCombo", "ieCombo", "jeCombo", "keCombo"};
if(choice==JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
System.out.println("Hey");
Scanner scanner = new Scanner(new FileReader(file));
while ( scanner.hasNextLine() ){
Scanner scan = new Scanner(scanner.nextLine());
scan.useDelimiter("=");
if ( scan.hasNext() ){
String item=scan.next();
int value=scan.nextInt();
String color=scan.next();
for(int g=0;g<comboboxes.length;g++){
if(item.equals(comboboxes[g])) {
if(value<3)
sourceALE[g].setSelectedIndex(value);
if(color.equals("red"))
sourceALE[g].setForeground(red);
if(color.equals("green"))
sourceALE[g].setForeground(green);
if(color.equals("blah"))
sourceALE[g].setForeground(blah);
}
}
}
scan.close();
}
scanner.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(q1.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void opening() {
JFileChooser chooser=new JFileChooser();
int choice=chooser.showOpenDialog(this);
javax.swing.JComboBox[] sourceALE = {aaCombo, baCombo, caCombo, daCombo, eaCombo, faCombo, gaCombo, haCombo, iaCombo, jaCombo, kaCombo,
alCombo, blCombo, clCombo, dlCombo, elCombo, flCombo, glCombo, hlCombo, ilCombo, jlCombo, klCombo,
aeCombo, beCombo, ceCombo, deCombo, eeCombo, feCombo, geCombo, heCombo, ieCombo, jeCombo, keCombo};
javax.swing.JTextField[] sourceP = {aeval1, beval, ceval, deval, eeval, feval, geval, heval, ieval, jeval, keval};
String [] comboboxes={"aaCombo", "baCombo", "caCombo", "daCombo", "eaCombo", "faCombo", "gaCombo", "haCombo", "iaCombo", "jaCombo", "kaCombo","alCombo", "blCombo", "clCombo", "dlCombo", "elCombo", "flCombo", "glCombo", "hlCombo", "ilCombo", "jlCombo","klCombo","aeCombo", "beCombo", "ceCombo", "deCombo", "eeCombo", "feCombo", "geCombo", "heCombo", "ieCombo", "jeCombo", "keCombo"};
if(choice==JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
System.out.println("Hey");
Scanner scanner = new Scanner(new FileReader(file));
while ( scanner.hasNextLine() ){
Scanner scan = new Scanner(scanner.nextLine());
scan.useDelimiter("=");
if ( scan.hasNext() ){
String item=scan.next();
int value=scan.nextInt();
String color=scan.next();
for(int g=0;g<comboboxes.length;g++){
if(item.equals(comboboxes[g])) {
if(value<3)
sourceALE[g].setSelectedIndex(value);
if(color.equals("red"))
sourceALE[g].setForeground(red);
if(color.equals("green"))
sourceALE[g].setForeground(green);
if(color.equals("blah"))
sourceALE[g].setForeground(blah);
}
}
}
scan.close();
}
scanner.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(q1.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("OUT");
}
}
1) It is good design to separate your data from the presentation. Are you doing this already? What I mean is you should be looking to store answers in an object outside of the jPanel class. (As 'Hovercraft Full Of Eels' suggested)
2) Consider making the data objects Serializable objects. If you're not planning on storing the data across a network or anything complicated/peculiar this should work out for you as it will facilitate save/load operations
3) Once you have your data separate from the GUI a check for changes becomes very easy. Assume that on any operation that takes you away from the page it "saves" its state. If the current state is different from the saved state then prompt the user to save (if it doesn't by default)
I have to wonder if you've created this program primarily as a NetBeans-generated GUI without first creating the non-GUI guts of the program. So first I have to ask, have you divided out your program logic from your GUI code a la MVC (model-view-controller) or one of its many variants? If not then this should be your first order of business, since in truth the saving and recovery of the data should have nothing to do with its GUI representation.
The key to solving your problem is going to be good object-oriented programming design. Consider for instance creating a non-GUI Question class that has several fields including a String question field, an ArrayList of possibleAnswers and a field String for the correctAnswer. Consider having an ArrayList of these Questions (ArrayList) for each chapter and a collection of the Chapters. Then you will need to figure out the best way for you to save the questions and the users answers. This may be via serialization, XML (JAXB?), or my recommendation: a database.
Only after you've figured out all of this should you worry about how to integrate a GUI around your non-GUI logic code which will be the GUI's "model".
Edit
Replies to your comments:
Sorry i havent provided enough info of my project. I m doing it in NETBEANS 7 GUI.I guess netbeans java programs are MVC
Sorry, no. If all you do is create a GUI with NetBeans you will be creating an unwieldy god-class. To have good MVC you must design it that way from the beginning. Again that means creating your program logic before creating the GUI which in your case includes creating multiple non-GUI classes as I've indicated above. There is no "automatic" MVC in NetBeans.
I may be wrong as i dont know much about MVC.
Yes, unfortunately you're wrong. Please read about it: Model-View-Controller. This will help you with your current and future design.
As of now i am able to save and retrieve. But i want your suggestion on that. It is quite hardcoded for each question.
And that should probably be fixed as you do not be hard-coding the questions. In fact the question text shouldn't even be part of the code but part of the data. Consider having the question in a comma-delimited text file or database.
i tried to answer 5 components and save it in notepad. And on loading it i am able to get all those components filled. Its working. But its quite hard coded and yes of course bad programming. But i have some time limitations so can you suggest anything similar to this logic. if by some function or method i could know all the components variable name present in my JPanel. like all the 15-20 combo-box and same no of text-box. I could make a function which can be common for all
Sorry, I wish I could, but I can't, not unless you first fix your design issues. Good luck!

Categories