JTree database node select and display in textfield in java - java

I have a JTree populated with a list of tasks from a database, I am trying to create a mouse clicked listener so that when a node is clicked, the id and task are displayed into JTextfields,
below is my code
private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
Object nodeInfo = node.getUserObject();
try {
String query = "select * from Task where task=" + nodeInfo + "";
pst = con.prepareStatement(query);
rs = pst.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
String task = rs.getString("task");
parentIdTxt.setText("" + id);
childTxt.setText("" + task);
}
} catch (Exception e) {
}
}
My problem is that even tho my program runs without any issues, whenever I click the node nothing happens? any help in pointing out what I missed will be appreciated

In fact you get an error but you don't see it, because you don't print it, you can check the error using :
} catch (Exception e) {
e.printStackTrace();
}
String should be between 'nodeinfo' so instead you have to use :
String query="select * from Task where task= '" + nodeInfo + "'";
But you don't implement PreparedStatement correctly you can use this :
String query="select * from Task where task = ?";
insert.setString(1, nodeinfo);
rs = pst.executeQuery();
...

You have to repaint the textfields or update their layout so they have enough space to show the contents. Try adding the following code after setting the contents of your textfields:
parentIdTxt.validate();
parentIdTxt.repaint();
childTxt.validate();
childTxt.repaint();

Firstly you need to check if you get the task and the id correctly using Debug mode or just by printing them into the console.
I recomended you to test just this code in the `JTree1MouseClicked.
private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {
childTxt.setText(jTree1.getLastSelectedPathComponent().toString());
}
that should display the selected node, that should work, then you need to check your request, I think that the problem is there

Related

JComboBox error blocking another field display

I have a problem with JComboBox. It's blocking another field in a frame meant to display another value that is linked through a foreign key in a database, a value that depends on the combo box already pop out. But somehow, after the user clicks the combo box it is blocking another field. The app is using MySql.
Here's the code:
ComboBox method to fill value from DB
public void comboBoxBerat(){
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
try {
sql = "SELECT * FROM weight_of_services";
rs = stat.executeQuery(sql);
while (rs.next()) {
jComboBoxBerat.addItem(rs.getString("weight"));
}
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
Action when selection is made from combo box, its get the value that linked with foreign key
private void jComboBoxBeratActionPerformed(java.awt.event.ActionEvent evt) {
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
String item = (String)jComboBoxBerat.getSelectedItem();
String sql = "SELECT price FROM weight_of_services WHERE weight = ?";
try {
pst = con.prepareStatement(sql);
pst.setString(1, item);
rs = pst.executeQuery();
if (rs.next()) {
String price = rs.getString("price");
txtHargaBerat.setText(price); //put value from combobox to txtField
}
con.close();
} catch (Exception e) {
}
}
The problem after I select from the box its blocking another field.
This is the combo box problem in the frame
It's solved. This because i am using jpanel for customizing color for the frame. Its just so messed up with the stacking one panel on top of the other one. That's why my dropdown list get blocked. So what I did, removed all the panel. Custom and sorting it more carefully and tidy from the start.

How can you get a JTextField to work in a SQLite Select statement?

I am working on a program which will when finished allow the end user to keep track of there sound packs in a database through SQLite. The newest problem I am running into is that I can not get the Select statement to take a JTextField input. The reason that I want to do this is that I already have the text fields linked through the insert method. I have tried switching the variable types in the readAllData method and I am not entirely sure what other way to fix it.
The fields are as follows
PackId
PackName
VendorName
PackValue
what I want to happen is when I hit the Update button I want the data in the database to print out to the console (for now) and I am also going to be adding a select specified records method as well.
Here is the code I do apologize in advance this is a very long project:
public void readAllData() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:sqlite:packsver3.db");
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM packs";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
String PackId = PackId.getText();
String PackName = PackName.getText();
String VendorName = VendorName.getTextField();
String PackValue = rs.getTextField;
System.out.println("All Packs\n");
System.out.println("PackId: " +PackId);
System.out.println("PackName: " +PackName);
System.out.println("VendorName: " +VendorName);
System.out.println("PackValue: " +PackValue+"\n\n");
}
} catch (SQLException e) {
System.out.println(e.toString());
}finally {
try {
assert rs != null;
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
System.out.println(e.toString());
}
Console Output

Java JDBC - Navigate Through Records Within Database

I am having some trouble in returning the NEXT record within the database, my code currently only returns the last record entered. I have tried creating an instance of a List/ArrayList, tried adding statements to my createStatement(); and just tried everything. I've searched the web, however, I always seem to get the last value returned. I was hoping as to whether someone could help me out. I am using .Swing and this is all executed within an ActionListener.
Essentially I want this function to get the next record in the database. As opposed to returning the last record.
nextEmployee.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Connection connection = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:employeeDatabase.sqlite");
connection.setAutoCommit(false);
System.out.println("Read operation - database successfully opened");
statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
ResultSet resultset = statement.executeQuery( "SELECT * from employees" );
while (resultset.next()) {
ArrayList<Employee> selectAllEmployees = new ArrayList<Employee>();
String id = resultset.getString("id");
String name = resultset.getString("name");
String email = resultset.getString("email");
String gender = resultset.getString("gender");
String dob = resultset.getString("dob");
String Address = resultset.getString("address");
String Postcode = resultset.getString("Postcode");
String NIN = resultset.getString("NIN");
String JobTitle = resultset.getString("JobTitle");
String StartDate = resultset.getString("StartDate");
String Salary = resultset.getString("Salary");
idTextField.setText(id);
nameTextField.setText(name);
genderTextField.setText(gender);
dobTextField.setText(dob);
addressTextField.setText(Address);
postcodeTextField.setText(Postcode);
ninTextField.setText(NIN);
jobtitleTextField.setText(JobTitle);
startdateTextField.setText(StartDate);
salaryTextField.setText(Salary);
emailTextField.setText(email);
}
resultset.close();
statement.close();
connection.close();
} catch ( Exception e1 ) {
System.err.println( e1.getClass().getName() + ": " + e1.getMessage() );
System.exit(0);
}
}});
Thank you for your time and effort.
One of two things is happening. Either:
You have a bug in the code which populates the database, so you think you have rows A, B, and C in the database, but in fact you only have row C
Or:
Your code as listed populates your controls with the contents of row A, then it repeats to populate the exact same controls with contents of row B, and then the exact same controls once more with the contents of row C. So, naturally, the values you are left with are the values of the last row.
It helps to think precisely what it is that you are trying to do, precisely what is happening, precisely what you expected to happen instead, and most importantly, what makes you believe that the code should do that which you expect it to do rather than what it actually does.

Select item from JCombobox and delete the row in database

I am working on a project in which I have a SQLite database with a table called Table1 and values title/location without an ID as column etc...
My form has a combobox which I've managed to get it display my DB each entry in one row . Now I want with a button "Delete" to delete the row that I have selected in the combobox and I am kind of lost.
Here is my code for the combobox (I think it's fine):
private void FillCombo(){
try {
String newLine = System.getProperty("line.separator");
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:C:\\users\\Kajou\\momentsdb.sqlite");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM Table1");
while (resultSet.next()) {
comboBox1.addItem(resultSet.getString("Title") + " " + "Date:" + resultSet.getString("Day")+"/"+ resultSet.getString("Month") +"/" + resultSet.getString("Year") + " " + resultSet.getString("Location")+ " " + resultSet.getString("Mood"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And now about the button delete. I've tried few things but looks like not going well:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:C:\\users\\Kajou\\momentsdb.sqlite");
statement = connection.createStatement();
String sql = "DELETE FROM Table1 WHERE col_string=Title";
int deleteCount = statement.executeUpdate(sql);
sql = "DELETE FROM Table1 WHERE col_string=?";
pst = connection.prepareStatement(sql);
pst.setString(1,"a string");
deleteCount=pst.executeUpdate();
} catch (ClassNotFoundException ex) {
Logger.getLogger(DeleteImportantMomentsForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DeleteImportantMomentsForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
You need something like:
Object item = comboBox.getSeletedItem();
pst.setString(1, item.toString());
First off, sorry for the extension but I have several advices for you :)
1) My form has a combobox which i managed to get it display my DB each
entry in one row
Here is the way you're adding an entry to the combo box:
comboBox1.addItem(resultSet.getString("Title") + " " + "Date:" +
resultSet.getString("Day")+"/"+
resultSet.getString("Month") +"/" +
resultSet.getString("Year") + " " +
resultSet.getString("Location")+ " " +
resultSet.getString("Mood"));
This way you'll get a very large string added to your combo box, which is not bad but can be highly improved if you map this info into a domain class. For instance:
class MyClass {
int day, month, year;
String title, location, mood;
public MyClass(int day, int month, int year,
String title, String location, String mood) {
this.day = day;
this.month = month;
this.year = year,
this.title = title;
this.location = location;
this.mood = mood;
}
// getters and setters are up to you :)
}
Next step is adding new MyClass objects to your combo box:
while (resultSet.next()) {
MyClass myClass = new MyClass(resultSet.getInt("Day"),
resultSet.getInt("Month"),
resultSet.getInt("Year"),
resultSet.getString("Title"),
resultSet.getString("Location"),
resultSet.getString("Mood"));
comboBox1.addItem(myClass); // see note below
}
Note: Swing components (such as JComboBox) must be created and updated in the Event Dispatching Thread (a.k.a. EDT) which is a single and special thread. If you have a heavy task running in the EDT (for instance database connections) then this task may block the EDT and your GUI will freeze and Swing components won't be able to work (or even display) untill this task is done. To avoid this issue there are some tools you can use to make the heavy tasks in a separate thread and update Swing components in the EDT, for instance SwingWorker. For further information take a look to Concurrency in Swing.
So I would suggest you make database calls using a SwingWorker:
SwingWorker<Void,MyClass> worker = new SwingWorker<Void,MyClass>() {
#Override
protected Void doInBackground() throws Exception { // this take place in a background thread
// connect to the database and execute the query here
while (resultSet.next()) {
MyClass myClass = new MyClass(resultSet.getInt("Day"), ...);
publish(myClass);
}
return null;
}
#Override
protected void process(List<MyClass> chunks){ // this take place in the EDT
for(MyClass myClass : chunks){
comboBox1.addItem(myClass);
}
}
}
Well now you have the items properly added to your combo box. Next step is make the combo box display the text as you wish. To do so you'll need to implement a ListCellRenderer. Take a look to Providing a Custom Renderer section in How to Use Combo Boxes tutorial. Take a look to this example. It's about setting a custom renderer to a JList but exactly the same applies to JComboBox.
2) Now i want with a button "delete" to delete the row that i have
selected in the combobox and i am kind of lost
Please note you're trying to execute two different delete queries:
String sql = "DELETE FROM Table1 WHERE col_string=Title"; // This doesn't make sense
int deleteCount = statement.executeUpdate(sql);
sql = "DELETE FROM Table1 WHERE col_string=?"; // This looks better I guess
pst = connection.prepareStatement(sql);
I suspect one of these queries (if not both of them) throws an Exception.
As your combo box will contain MyClass objects, you can make this change at the action performed method:
MyClass myClass = (MyClass)comboBox1.getSelectedItem();
String sql = "DELETE FROM Table1 WHERE Title = ?"; //If Title is the name of the column, of course
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1,myClass.getTitle());
Note: Once again, the action performed method is executed in the EDT. You should move the database call to a background thread to avoid blocking the EDT.

How to populate JList with data from another JList

I have a MySQL database which contains data i would like to populate into a JList in my java program. I have two JList, one which is fill with Events Title and the second is to be fill with Guest Name.
What i would like is when the user click on any of the Events Title, the second JList will show all the Guest Name that belong to that Event.
I have already successfully populate the first JList with all the Events Title. What I'm having trouble with is when the user click on the Events Title, the Guests Name will show twice on the second JList. How can i make it to show only once?
Here is what i got so far...
Java Class
private JList getJListEvents() {
if (jListEvents == null) {
jListEvents = new JList();
Border border = BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(1, Color.black, Color.black), "Events", TitledBorder.LEFT, TitledBorder.TOP);
jListEvents.setBorder(border);
jListEvents.setModel(new DefaultListModel());
jListEvents.setBounds(new Rectangle(15, 60, 361, 421));
Events lEvents = new Events();
lEvents.loadEvents(jListEvents);
jListEvents.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
EventC eventC = new EventC();
//eventC.MonitorRegDetailsInfo(jListEvents, jTextFieldEventName, jTextFieldEventVenue, jTextFieldEventDate, jTextFieldEventTime, jTextAreaEventDesc);
//eventC.MonitorRegPackageInfo(jListEvents, jTextFieldBallroom, jTextFieldBallroomPrice, jTextFieldMeal, jTextFieldMealPrice, jTextFieldEntertainment, jTextFieldEntertainmentPrice);
eventC.MonitorRegGuest(jListEvents, jListGuest);
}
});
}
return jListEvents;
}
Controller Class
public void MonitorRegGuest(JList l, JList l2){
String event = l.getSelectedValue().toString();
Events retrieveGuest = new Events(event);
retrieveGuest.loadGuests(l2);
}
Class with all the sql statement
public void loadGuests(JList l){
ResultSet rs = null;
ResultSet rs2 = null;
ResultSet rs3 = null;
MySQLController db = new MySQLController();
db.getConnection();
String sqlQuery = "SELECT MemberID FROM event WHERE EventName = '" + EventName + "'";
try {
rs = db.readRequest(sqlQuery);
while(rs.next()){
MemberID = rs.getString("MemberID");
}
} catch (SQLException e) {
e.printStackTrace();
}
String sqlQuery2 = "SELECT GuestListID FROM guestlist WHERE MemberID = '" + MemberID + "'";
try {
rs2 = db.readRequest(sqlQuery2);
while(rs2.next()){
GuestListID = rs2.getString("GuestListID");
}
} catch (SQLException e) {
e.printStackTrace();
}
String sqlQuery3 = "SELECT Name FROM guestcontact WHERE GuestListID = '" + GuestListID + "'";
try {
rs3 = db.readRequest(sqlQuery3);
while(rs3.next()){
((DefaultListModel)l.getModel()).addElement(rs3.getString("Name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
db.terminate();
}
Thanks in advance!
Please for the time being forget about the SQL. Then follow the steps below:
Start with the example --- the corresponding Java Web Start link.
Play with the sample, to see how to add elements to a list.
Then all you need to do is grab a reference to the one you want to copy and for each element copy it then add to the 2nd list.
Enjoy Java.
EDIT:
I am still looking at your code and I am still confused of what is going on (Please consider making a SSCCE). But let me guess, as something is telling me that when you are calling the ListSelectionListener you are not using getIsValueAdjusting() of the ListSelectionEvent, right? Therefore, this might be as well it, for more read here.
As far as I can see, you aren't clearing the list before populate it, you could try to clear the model first, like:
String sqlQuery3 = "SELECT Name FROM guestcontact WHERE GuestListID = '" + GuestListID + "'";
try {
rs3 = db.readRequest(sqlQuery3);
DefaultListModel lm = (DefaultListModel)l;
lm.clear();
while(rs3.next()){
(lm.getModel()).addElement(rs3.getString("Name"));
}
} catch (SQLException e) {
e.printStackTrace();
}

Categories

Resources