Set the selected Jtree Node to JTable - java

The function need to be accomplished is:
Select main group
Select from sub-group (TEST NAME)
Click >> button which means move the selection to Jtable
Show the slected (Test) with corresponding price on Jtable
conditions:
if the selected node (test name) alread has been selected and added to the Jtable show message say: Test name already added.
we can select and add many test name
Demo image
impotant to say that JTree data come from two tables main-group and sub-group
Here the code: of >> button
try {
DefaultMutableTreeNode selectedElement = (DefaultMutableTreeNode) TestTree.getSelectionPath().getLastPathComponent();
Object[] row = {selectedElement};
DefaultTableModel model = (DefaultTableModel) myTests_table.getModel();
System.out.println(String.valueOf(row).toString() + "Hi");
if (selectedElement.isLeaf() == true) {
//model.addRow(row);
// retrive date from DB price
String sql = "SELECT sub_group.name AS 'name', sub_group.price AS 'price'"
+ "FROM sub_group \n"
+ "where sub_group.name = '" + row + "' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
while (rs.next()) {
myTests_table.setModel(DbUtils.resultSetToTableModel(rs));
}
} else {
JOptionPane.showMessageDialog(null, "Please Choose Test name!", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
Dears
where is the error?
Thanks

Add a TreeSelectionListener to your JTree, as shown here. In the listener, update the TableModel of your JTable; the listening table will update itself accordingly, when your implementation of setValueAt() fires the relent TableModelEvent. Your table model should extend AbstractTableModel, as shown here, and contain a Set<Row>. Your Row class should hold the name and price. If Row implements Comparable<Row>, as shown in the example cited here, then Set<Row> will automatically exclude duplicates when you invoke add().

if the issue is that the new TableModel is not being reflected in the UI, use tableModel.fireTableDataChanged().

Related

How to get data to display when selecting items from a JComBox

I´m rather lost on how to get data to display in text fields when selecting something from a JComboBox. I got 2 tables in mysql which have a connection with a constraint of a foreign key (pelicula dirID and director dirID (pelicula and director are the tables)).
I got the directors names in a list so it can be displayed in the JComboBox from a mysql query but i don´t understand how i could get the text fields to change when choosing another director.
e.g
--- Titulo --- dur-genero-pais
--- Errementari 92 Horror Basque
String queryJOIN = "SELECT p.titulo, p.duracion, p.genero, p.pais, d.nombre, d.apellido"
+ " FROM filmoteca.pelicula p, filmoteca.director d"
+ " WHERE p.dirID = d.dirID";
List<String> comboBoxNames = new ArrayList<String>();
try {
Statement stmt = newBDD.con.createStatement();
ResultSet rs2 =stmt.executeQuery(queryJOIN);
while (rs2.next() ) {
String name = rs2.getString("nombre");
String lastname = rs2.getString("apellido");
comboBoxNames.add(name + " " + lastname);
}
newBDD.con.close();
}
catch (Exception exc) {
exc.printStackTrace();
}JComboBox comboBox = new JComboBox(comboBoxNames.toArray());
comboBox.setBounds(45,147,204,21);contentPane.add(comboBox);
When I add the columns with a setText it will appear but of course not change when i change the director in the combobox and that is where im having difficulties in finding a way to connect those two things so when one changes its value the other does as well.
e.g ´editorTitulo.setText(rs2.getString("titulo"));´
This is the GUI atm:

Returning column names from table in SQLite using Java GUI

I need to get column names from table, only difference is that I made a function that makes new column depending on users entry in txtbox. So for example if a user enters "3", column would be named "Sezonalni_utjecaj_3". Now when you saw that example I need to make a query that returns column names so I can put them inside my combobox, so everytime I enter a new column, the name of the column would be placed inside of the combobox (column names have something in common, and thats "Sezonalni_utjecaj_", but I have other columns too, not only ones that have "Sezonalni_utjecaj_" inside their name but I dont need their names ).
My Interface:
When i press "Ok" this is code behind it:
btnOk_2 = new JButton("Ok");
btnOk_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String kolumna=(String)textField.getText();
String upit="alter table Linearni_trend_s_sezonalnim_utjecajem add column 'Sezonalni_utjecaj_"+kolumna+"' float;";
PreparedStatement pst1 = konekcija.prepareStatement(upit);
pst1.execute();
pst1.close();
} catch (SQLException e) {
e.printStackTrace();
}
Actually Pragma can help you to get all columns name with type etc etc.PRAGMA_SQL
PRAGMA table_info(table_name);
Alternatively you may use another way like ;
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'

JSP - Checking if item is already in Cart

I would like to know how I can check if the item I clicked on is already in my Cart.
I used to make a table for that with jSessions and call with each "ADD TO CART" an Insert-Function to add it to the cart. Now I would like to have a 'smart' cart where I add the number I've chosen to the old value in the cart table via UPDATE.
That's what I got. I know I have to iterate somehow in the "if"-Function if the item is already in the cart-table, but f.e. (jSessionID == rsSelect.getString("jSession") AND productID == rsSelect.getInt("id")) won't work.
try {
// If item is already in jSession based Cart...
if (...) {
// change the value of set.
String sqlUpdate = "UPDATE `Cart` SET value = value + '"+set+"' WHERE productID ='"+id+"' AND jSession = '"+jSessionID+"'";
// PrepareStat. Object
PreparedStatement psUpdate = con.prepareStatement(sqlUpdate);
// Update set
psUpdate.executeUpdate();
} else {
// INSERT-Command for new Item
String sqlInsert = "INSERT INTO `Cart` (jSession, produktID, name, value, Preis) values('"+jSessionID+"','"+id+"','"+title+"','"+set+"','"+price+"')";
// PS-Statement
PreparedStatement psInsert = con.prepareStatement(sqlInsert);
// Insert new Item to Cart
psInsert.executeUpdate();
}
} catch(Exception e) {
e.printStackTrace();
}
You can do a select to search to find the existing items.
SELECT productId FROM cart
WHERE productID = ? AND jSession = ?
If this returns a tuple then you got a match.

confusion over using values in Java within SQL statements

I need to retrieve a list of vehicle registrations from an SQL database and put them into a dropdown list in the java GUI. Once a Vehicle Registration is selected (as part of a login sequence) from the list I want to use this in the "where" statement of subsequent SQL queries made to the database to get things like inventory statuses etc that are only for that vehicle.
I have done the first part i.e. retrieved the list from the database and displayed the veh regs in the dropdown for the user to select, I have managed to display this in an optional panel as well as display it in another class in a Jlabel box but I cannot seem to figure out how to use this selected veh reg in a seperate query class i.e as part of a select/where statement?
I have been trying to find a solution to this but am getting confused on whether to use an array list and put the registration number into this and then how to make this available to other classes so I can retrieve the value to use in the SQL statement. I am quite lost now so any advice in the right direction will be very helpful.
I am very new to Java and programming altogether so if you feel the need to make sarcastic (you are such a noob) type comments then don't bother posting!
This is the code that grabs the registrations from the database and adds them to the combo box in one GUI:
private void populateRegistration() {
try {
// create a connection to database
pst = conn.prepareStatement("SELECT VehicleRegistrationNumber FROM vehicle;");
// create a query to get vehicle regs
rs = pst.executeQuery();
// add vehicle regs to combobox
while (rs.next()) {
jComboBox1.addItem(rs.getString("VehicleRegistrationNumber"));
}
} catch (SQLException ex) {
Logger.getLogger(Login_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
This is the code In another GUI Class that shows this vehicle registration in a dialogue box and then shows it in a text field in the GUI:
public ArrayList<String> getTableContent()
{
DatabaseConnection db = new DatabaseConnection();
try {
//Sql Return Statement
String newQuery= "SELECT P.PatientFirstName, P.PatientLastName, P.PatientHouseNumber, P.PatientStreetName, P.PatientPostcode, P.PatientBreathing, P.ProblemInformation, C.AMPDSCategory, \n" +
"I.NumberHurt,T.TaskClosed, H.HospitalSpaceAvailable, H.HospitalName, H.HospitalPostcode, V.VehicleRegistrationNumber, EM.DateTimeReported\n" +
"FROM Patient AS P\n" +
"JOIN Category AS C\n" +
"ON C.Category_ID = P.CategoryID\n" +
"--AND P.Patient_ID = 2\n" +
"JOIN Incident AS I\n" +
"ON I.Incident_ID = P.IncidentID\n" +
"JOIN TASK AS T\n" +
"ON T.IncidentID = I.Incident_ID\n" +
"JOIN Hospital AS H\n" +
"ON H.Hospital_ID = T.HospitalID\n" +
"JOIN Vehicle AS V\n" +
"ON T.Task_ID = V.TaskID\n" +
"JOIN ECCPersonnel AS EC\n" +
"ON I.ECCPersonnelID = EC.ECCPersonnel_ID\n" +
"JOIN EmergencyCall AS EM\n" +
"ON EC.CallID = EM.Call_ID\n" +
"WHERE T.Task_ID=1" +
"--WHERE V.VehicleRegistrationNumber = '?'";
I know the SQL is ugly but it works so I will refine it later if I get time. I believe I need to define the ? but have no idea how to reference the ? to the vehReg value!!
First you should allways close what you have opened. So in populateRegistration() do not forget rs.close() and pst.close().
Next to reference the ? to the vehReg, you create a PreparedStatement and call its setString method (supposing vehReg is a String).
pst = conn.prepareStatement(newQuery);
pst.setString(1, vehReg);
rs = pst.executeQuery();
(try, catch, declarations, and actual read ommitted for brevity)
Remember that columns are numbered starting by 1.

How to insert data into swing table whose columns are dynamically defined (data from a mysql database)?

I have a table and on a opening of a frame the table receives its columns and their respective headers from a table in mysql database. How can i insert all the values from the sql database table into the swing table??
Here is my code...
DefaultTableModel dtm=(DefaultTableModel)jTable1.getModel();
String query1=null;
try {
query1="select * from "+Variables.table+";";
ResultSet rsft=st.executeQuery(query1);
Object o[]=new Object[x];
while(rsft.next()) {
for(int i=1;i<=x;i++){
o[i-1]=rsft.getString(i);
}
dtm.addRow(o);
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
In above code x is an integer denoting the number of colums in sql table.
And Variables.table is a static variable containing the table name.
Thank You
The problem is that getColumnCount will still return 0, despite that you added some rows. Just call setColumnCount as well.
You can verify this in the source code, or just perform a quick test, e.g.
import javax.swing.table.DefaultTableModel;
public class DefaultTableModelDemo {
public static void main( String[] args ) {
DefaultTableModel defaultTableModel = new DefaultTableModel();
defaultTableModel.addRow( new Object[]{"Test", "Test"} );
System.out.println( "defaultTableModel.getRowCount() = " +
defaultTableModel.getRowCount() );
System.out.println( "defaultTableModel.getColumnCount() = " +
defaultTableModel.getColumnCount() );
}
}
gives the following output
defaultTableModel.getRowCount() = 1
defaultTableModel.getColumnCount() = 0
It might be easier to just create a data vector first, and then create a new TableModel and replace the existing TableModel of the JTable.
Further remarks:
Since the dtm is already used for a JTable, you should only update it on the Event Dispatch Thread. But database connections/queries are typically "slow" and should not be performed on the EDT. You can avoid this by either wrap each of the addRow calls in a SwingUtilities#invokeXXX call or just construct a new TableModel on the background thread and replace the model in one go on the EDT. Consult the Swing concurrency tutorial for more information.
Do not forget to close the ResultSet in a finally block

Categories