How to populate JList with data from another JList - java

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();
}

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.

JTree database node select and display in textfield in 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

cardinality violation and NullPointerException while populating a combobox with available courses

I am relativity new to java programming any way here what i am trying to do
I am trying to populate combobox1(Add list) with the courses available to the student and then removing the selected item and sending to combobox2(drop list)
but its simply not reacting right especially when the student doesn't have any courses that are available to add and it returns the exceptions
"net.ucanaccess.jdbc.ucanaccessSQLException:cardinality violation"
&
"java.lang.NullPointerException"
here's how initialize each of the comboboxes
try
{String mail=Login.user_mail;
String sql = "select CourseCode from Course where CourseCode!=(select CourseCode from CourseStudent where StudentEmail='"+mail+"') OR NOT EXISTS(select CourseCode from CourseStudent where StudentEmail='"+mail+"')";
java.sql.ResultSet rs = dbm.select(sql);
DefaultComboBoxModel m = new DefaultComboBoxModel();
while (rs.next()) {
m.addElement(rs.getObject(1).toString());
}
jComboBox1.setModel(m);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.toString());
}
then combo box2
String mail=Login.user_mail;
String sql = "select CourseCode from CourseStudent where StudentEmail='"+mail+"'";
java.sql.ResultSet rs = dbm.select(sql);
DefaultComboBoxModel m = new DefaultComboBoxModel();
while (rs.next()) {
m.addElement(rs.getObject(1).toString());
}
jComboBox2.setModel(m);
}
this is within the Add button
String ID = (String) jComboBox1.getSelectedItem();
String mail=Login.user_mail;
try {
dbm.insert(" insert into CourseStudent (StudentEmail, CourseCode ) values ('"+mail+"', '"+ID+"') ");
jComboBox2.addItem(jComboBox1.getSelectedItem());
jComboBox1.removeItem(jComboBox1.getSelectedItem());
} catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Insertion Faild\n"+ex);
}
and this is with the drop button
try {
String ID = (String) jComboBox2.getSelectedItem();
String mail=Login.user_mail;
dbm.delete("delete from CourseStudent where CourseCode='"+ID+"' And StudentEmail='"+mail+"'");
jComboBox1.addItem(jComboBox2.getSelectedItem());
jComboBox2.removeItem(jComboBox2.getSelectedItem());
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Delete Faild\n"+e);
}
i think the problem lays in the combobox1 SQl statement but i really can't see any other way to do it as i need to retrieve the courses from a table while making sure that the user doesn't take it already from another table...
any help would be greatly appreciated as i said i have been using java for a couple of weeks now and i haven't used sql before so i am a little lost

MySQL Query based on user input in Java

i'm new to SQL and Java and couldn't find anything to fix my problem.
(closest thing: MySQL query based on user input)
So I have a DB full of shows/events and I want users to "search" for a certain event or show.
The user will input the name of the show/event into GUI and I want the query to return data associated with the user-input.
For example:
User is searching for the artist Zedd;
searchSet = statement.executeQuery("SELECT eventname,date FROM shows WHERE artist LIKE 'zedd' ");
The query is fixed, can the query be modified to search whatever the user input?
Something like:
String artist = "zeppelin"
searchSet = statement.executeQuery("SELECT eventname,date FROM shows WHERE artist LIKE "artist" ");
Thanks in advance for the help!
You should double check your shows second column. I'm not sure you can use a column named date. Anyway, you should certainly use a PreparedStatement with something like,
String sql = "SELECT eventname, eventdate FROM shows WHERE artist LIKE ?";
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, artist);
rs = ps.executeQuery();
while (rs.next()) {
String eventName = rs.getString("eventname");
Date eventDate = rs.getDate("eventdate");
// Use your columns in your row here.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
As per normal SQL, you statement would work if it was
String artist = "'%zeppelin%'";
searchSet = statement.executeQuery("SELECT eventname,date FROM shows WHERE artist LIKE " + artist);
The String needs to be aurrounded with % and also quoted.
Have a look at preparedStement though, it has method to set each parameter separately and avoid SQL injection.
It would be something like this:
String artist = "zeppelin"
searchSet = statement.executeQuery("SELECT eventname, date FROM shows WHERE artist LIKE '%" + artist + "%'");
Note the sql wildcard string '%'

Can't populate jtable with mysql "like" statement

I am building an application in which you can save deals to database. I'd like to search deals in my database and populate my jtable with relevant results. I want to query my database on keyrelease event. I know it is not an efficient method but I am curious why I can't get it to work.
Below is a sample code that tries to query a database table with ID and country names. There are only 3 country names that start with "D". Somehow I can get country names printed out but can't get them to populate jtable.
The error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" I can't get ResultSet rs1 into a Object[][] . It works fine if I do System.out.println(rs1.getString("Name")
Below is the code -
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String columnName[] = new String[] { "Name" };
Object oss[][] = new Object[3][];
ResultSet rs1 = null;
int li = 0;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection con = DriverManager.getConnection(Url, User, Password);
Statement st = con.createStatement();
String query = "SELECT * from unit.cntry WHERE Name LIKE '" + abc.getText() + "%';";
rs1 = st.executeQuery(query);
} catch (Exception e) {}
try {
while (rs1.next()) {
oss[li][0] = rs1.getString("Name");
li++;
}
myTable.setModel(new DefaultTableModel(oss, columnName));
} catch (SQLException ex) {
System.out.println(ex.toString());
} finally {
try {
if (rs1 != null) rs1.close();
} catch (SQLException e) {}
}
}
oss[li] = new Object[1];
oss[li][0] = rs1.getString("Name");
Other data structures might be more appealing.

Categories

Resources