I want to post a question about something I wish to do particularly but have no idea how to approach this as I am new with JTables.
This is what I have atm:
But I would like to arrange the table like this:
So that under a particular date, all events that correspond to that date are shown rather than individually like have above.
Here are the related classed in question, I am not sure where and how to make the alternations to allow me to achieve the above.
public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
for (int column=0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
Vector rows = new Vector();
while(rs.next()) {
Vector newRow = new Vector();
for (int i =1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows,columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public class EventModel {
public TableModel getTableData() {
TableModel model=null;
try {
String sql = "SELECT eventID as 'Event ID', date as 'Date',eventName as 'Name', time as 'Start Time' FROM Event";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
model = (DbUtils.resultSetToTableModel(rs));
}
catch(SQLException e){
e.printStackTrace();
}
finally {
try {rs.close(); pst.close();}
catch(SQLException e){} }
return model;
}
public Events getEvent(String tableClick) {
try {
pst = conn.prepareStatement("SELECT * FROM Event WHERE eventID='"+tableClick+"' ");
rs = pst.executeQuery();
while(rs.next()){
e.setEventName(rs.getString(2));
e.setEventDate(rs.getString(3));
e.setEventTime(rs.getString(4));
e.setEventVenue(rs.getString(5));
e.setEventDetail(rs.getString(6));
e.setEventOpportunity(rs.getString(7));
e.setEventMoreDetails(rs.getString(8));
e.setEndTime(rs.getString(9));
}
}
catch(SQLException ex){
ex.printStackTrace();
} finally {
try {
rs.close();
pst.close();
} catch (Exception e) {
}
}
return e;
} //end getEvent
}
public class EventController {
private KeyAdapter keyAdapter = new KeyAdapter() {
#Override
public void keyReleased(java.awt.event.KeyEvent e) {
if((e.getKeyCode()==KeyEvent.VK_UP) || (e.getKeyCode()==KeyEvent.VK_DOWN)) {
changeEvent();
}
}
};
public void changeEvent() {
int rowSelected = view.tableEvent.getSelectedRow();
tableClick = view.tableEvent.getModel().getValueAt(view.tableEvent.convertRowIndexToModel(rowSelected), 0).toString();
events = model.getEvent(tableClick); //tell model to change its state based on user input on views
view.changeDisplay(events);
}
}
public class EventView {
public void changeDisplay(Events e) {
evTitle.setText(""+e.getEventName());
evWhen.setText("When: "+ e.getEventDate());
evWhere.setText("Where: "+ e.getEventVenue());
evDescription.setText(""+ e.getEventDetail());
evOpportunity.setText(""+ e.getEventOpportunity());
evMoreDet.setText(""+ e.getEventMoreDetails());
endTime.setText("End Time: "+e.getEndTime());
}
}
e is the object of the class Events which is just a bean.
You may be able to simply setAutoCreateRowSorter(true). Addendum: Because Date implements Comaprable, ensure that your TableModel returns type Date.class for the date column, as shown here. See also How to Use Tables: Sorting and Filtering.
A more elaborate approach would be to use a tree-table such as Outline, shown here. The top level(s) would be dates, and the leaves would be events.
Related
I'm reading data from a DB and like to appended each row of data from the DB using a Callback. I've managed to get the Callback working but I don't know how I will get it append the data to file. Here is my code.
Main
public class Main {
public static void main(String[] args) {
FileIO fileIO = new FileIO();
fileIO.writeRStoFile();
}
}
FileIO
public class FileIO implements DBAccess.CallBack {
public void writeRStoFile() {
DBAccess dbAccess = new DBAccess(this);
String fileName = "/result.csv";
try (FileWriter fw = new FileWriter(fileName)) {
System.out.println("Starting data download from DB...");
dbAccess.readDB();
// HERE I LIKE TO APPEND EACH ROW TO THE FILE
fw.append('\n');
System.out.println("Finished data download from DB...");
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void iAmDone(String row) {
System.out.println("Row: " + row);
}
}
DBAccess
public class DBAccess {
public interface CallBack {
public void iAmDone(String row);
}
private final CallBack callBack;
public DBAccess(CallBack callBack) {
this.callBack = callBack;
}
public void readDB() {
String url = "jdbc:Cobol:////Dev/Project Files/DatAndCpyFiles";
try (Connection con = DriverManager.getConnection(url, "", "");
Statement stmt = con.createStatement())
{
stmt.setFetchSize(10);
Class.forName("com.hxtt.sql.cobol.CobolDriver").newInstance();
String sql = "select * from PROFS";
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData resultSetMetaData = rs.getMetaData();
int iNumCols = resultSetMetaData.getColumnCount();
for (int i = 1; i <= iNumCols; i++) {
callBack.iAmDone(resultSetMetaData.getColumnLabel(i) + ";");
}
String field;
while (rs.next()) {
String row = "";
for (int i = 1; i <= iNumCols; i++) {
field = rs.getString(i);
field = field.trim() + ";";
row = row + field;
}
callBack.iAmDone(row);
}
rs.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
I'm not sure how I get the data from iAmDone() into the writeRStoFile() method. I'm able to print the data to the console.
One way that I can think of is to declare fw as a member variable in FileIO. That way you can call fw.append(...) in iAmDone. (You might have to change the try-with-resources then.)
I am trying to pass data from a db in another class into JFrame in jcombobox but only the last row is displayed. Below is a sample code:
Class A...
public String jcbNames() {
try {
con = connCC.getDBconnection();
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select customerName From appointment");
while (rs.next()) {
customer = (rs.getString(1));
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Appointment.class.getName()).log(Level.SEVERE, null, ex);
}
return customer;
}
Class JFrame...
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
this.jCBCustomers.removeAllItems();
this.jCBCustomers.addItem(app.jcbNames());
}
the problem is there you return just one String in your jcbNames method , use an arraylist and add all of strings to it and then return it as a collection of database data.
so change your methods or use this modified methods.
public ArrayList<String> jcbNames() {
try {
con = connCC.getDBconnection();
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select customerName From appointment");
ArrayList<String> list = new ArrayList<>();
while (rs.next()) {
list.add(rs.getString(1));
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Appointment.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
and
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
this.jCBCustomers.removeAllItems();
ArrayList<String> list =app.jcbNames();
for (String str:list){
this.jCBCustomers.addItem(str);
}
}
and if you don't want to use this.jCBCustomers.removeAllItems(); to prevent duplicates , use below code
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
// collect all of your current data in jcombobox
ArrayList<String> current_list = new ArrayList<>();
int count = this.jCBCustomers.getItemCount(); // get count of them
for (int i = 0; i < count; i++) {
current_list.add((String) this.jCBCustomers.getItemAt(i)); // add them to current list
}
// data that returned from database
ArrayList<String> returned_from_db_list = jcbNames(); // calling jcbNames method
/*
for each string that has returned from database ,
if it doesn't in the current_list
you can add it to jcombobox , so ...
*/
for (String str : returned_from_db_list) {
if ( !current_list.contains(str) ) { // check for existing in the current_list
current_list.add(str); // adding fresh data to current_list!
/*
or you can add them directly to jcombobox and remove above statement.
this.jCBCustomers.addItem(str); // add updated data to jcombobox
*/
}
}
/*
if ::: you use current_list.add(str); in above for-each-loop ,
now you must update jcombobox data !
else ::: remove below loop.
*/
for (String singleStr : current_list) {
this.jCBCustomers.addItem(singleStr); // add updated data to jcombobox
}
}
I'm working on a Swing app which is connected to MySQL database. It fetches some data from the DB and shows in the table. Besides, there are 3 buttons that suppose to changes table data ( Add row to table ), update the database (Update database ) and to discard the changes ( Discard changes ) as following,
After clicking the Add row to table button, the new entries from the form should be added in the table. Afterwards if the update button is clicked, the data will be updated in the db. Discard changes will delete the data from the last row of the table and will have nothing to do with db. The app has two classes CoffeesFrame.java and CoffeesTableModel.java I provided the sample code from both of the classes below,
public class CoffeesFrame extends JFrame implements RowSetListener {
private static final long serialVersionUID = 1L;
private static Connection myConn = null;
private static String url = "jdbc:mysql://localhost:3306/myDemo";
private static String user = "student";
private static String password = "student";
// initiate a table object
JTable table;
// labels of the table
// text data fields of the table
// buttons of the table
// initiate a table model object
CoffeesTableModel myCoffeesTableModel;
// table constructor
public CoffeesFrame(Connection myConn) throws SQLException {
table = new JTable();
createNewTableModel(myConn);
/*
label, text field and buttons
*/
Container contentPane = getContentPane();
contentPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
contentPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
/*
Code for making the GUI
*/
button_ADD_ROW.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// showMessageDialog works
JOptionPane.showMessageDialog(CoffeesFrame.this, new String[] {
"Adding the following row:",
"Coffee name: [" + textField_COF_NAME.getText() + "]",
"Supplier ID: [" + textField_SUP_ID.getText() + "]",
"Price: [" + textField_PRICE.getText() + "]",
"Sales: [" + textField_SALES.getText() + "]",
"Total: [" + textField_TOTAL.getText() + "]" });
try {
// Insert row is not adding data to the table
myCoffeesTableModel.insertRow(
textField_COF_NAME.getText(),
Integer.parseInt(textField_SUP_ID.getText().trim()),
Float.parseFloat(textField_PRICE.getText().trim()),
Integer.parseInt(textField_SALES.getText().trim()),
Integer.parseInt(textField_TOTAL.getText().trim()));
// table.getModel();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
button_UPDATE_DATABASE.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
myCoffeesTableModel.coffeesRowSet.acceptChanges(myConn);
}
catch (Exception ex) {
ex.printStackTrace();
}
try {
createNewTableModel(myConn);
}
catch (Exception el) {
el.printStackTrace();
}
}
});
button_DISCARD_CHANGES.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The changes are DISCARDED");
}
});
}
private void createNewTableModel(Connection myConn) throws SQLException {
myCoffeesTableModel = new CoffeesTableModel(getContentsOfCoffeesTable(myConn));
myCoffeesTableModel.addEventHandlersToRowSet(this);
table.setModel(myCoffeesTableModel);
}
#Override
public void rowSetChanged(RowSetEvent event) {
// TODO Auto-generated method stub
}
#Override
public void rowChanged(RowSetEvent event) {
// TODO Auto-generated method stub
}
#Override
public void cursorMoved(RowSetEvent event) {
// TODO Auto-generated method stub
}
public CachedRowSet getContentsOfCoffeesTable(Connection mycConn)
throws SQLException {
CachedRowSet crs = null;
ResultSet resultSet = null;
Statement stmt = null;
String sql = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";
try {
stmt = myConn.createStatement();
resultSet = stmt.executeQuery(sql);
crs = new CachedRowSetImpl();
crs.populate(resultSet);
}
catch (Exception e) {
e.printStackTrace();
}
return crs;
}
public static void main(String[] args) throws SQLException {
try {
myConn = DriverManager.getConnection(url, user, password);
if (myConn != null) {
System.out.println("Connected to the database myDemo");
}
}
catch (SQLException ex) {
System.out
.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
myConn.setAutoCommit(false);
CoffeesFrame coffeesFrame = new CoffeesFrame(myConn);
coffeesFrame.pack();
coffeesFrame.setVisible(true);
}
}
The CoffeesTableModel.java as follows, //
public class CoffeesTableModel implements TableModel {
CachedRowSet coffeesRowSet; // The ResultSet to interpret
ResultSetMetaData metadata; // Additional information about the results
int numcols, numrows; // How many rows and columns in the table
public CoffeesTableModel(CachedRowSet rowSetArg) throws SQLException {
this.coffeesRowSet = rowSetArg;
this.metadata = this.coffeesRowSet.getMetaData();
numcols = metadata.getColumnCount();
// Retrieve the number of rows.
this.coffeesRowSet.beforeFirst();
this.numrows = 0;
while (this.coffeesRowSet.next()) {
this.numrows++;
}
this.coffeesRowSet.beforeFirst();
}
public CachedRowSet getCoffeesRowSet() {
return coffeesRowSet;
}
public void addEventHandlersToRowSet(RowSetListener listener) {
this.coffeesRowSet.addRowSetListener(listener);
}
public void insertRow(String coffeeName, int supplierID, float price,
int sales, int total) throws SQLException {
try {
this.coffeesRowSet.moveToInsertRow();
this.coffeesRowSet.updateString("COF_NAME", coffeeName);
this.coffeesRowSet.updateInt("SUP_ID", supplierID);
this.coffeesRowSet.updateFloat("PRICE", price);
this.coffeesRowSet.updateInt("SALES", sales);
this.coffeesRowSet.updateInt("TOTAL", total);
this.coffeesRowSet.insertRow();
this.coffeesRowSet.moveToCurrentRow();
}
catch (SQLException e) {
e.printStackTrace();
// JDBCTutorialUtilities.printSQLException(e);
}
}
public void close() {
try {
coffeesRowSet.getStatement().close();
}
catch (SQLException e) {
e.printStackTrace();
// JDBCTutorialUtilities.printSQLException(e);
}
}
/** Automatically close when we're garbage collected */
protected void finalize() {
close();
}
/** Method from interface TableModel; returns the number of columns */
public int getColumnCount() {
return numcols;
}
/** Method from interface TableModel; returns the number of rows */
public int getRowCount() {
return numrows;
}
/**
* Method from interface TableModel; returns the column name at columnIndex
* based on information from ResultSetMetaData
*/
public String getColumnName(int column) {
try {
return this.metadata.getColumnLabel(column + 1);
}
catch (SQLException e) {
return e.toString();
}
}
/**
* Method from interface TableModel; returns the most specific superclass
* for all cell values in the specified column. To keep things simple, all
* data in the table are converted to String objects; hence, this method
* returns the String class.
*/
public Class getColumnClass(int column) {
return String.class;
}
/**
* Method from interface TableModel; returns the value for the cell
* specified by columnIndex and rowIndex. TableModel uses this method to
* populate itself with data from the row set. SQL starts numbering its rows
* and columns at 1, but TableModel starts at 0.
*/
public Object getValueAt(int rowIndex, int columnIndex) {
try {
this.coffeesRowSet.absolute(rowIndex + 1);
Object o = this.coffeesRowSet.getObject(columnIndex + 1);
if (o == null)
return null;
else
return o.toString();
}
catch (SQLException e) {
return e.toString();
}
}
/**
* Method from interface TableModel; returns true if the specified cell is
* editable. This sample does not allow users to edit any cells from the
* TableModel (rows are added by another window control). Thus, this method
* returns false.
*/
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
// Because the sample does not allow users to edit any cells from the
// TableModel, the following methods, setValueAt, addTableModelListener,
// and removeTableModelListener, do not need to be implemented.
public void setValueAt(Object value, int row, int column) {
System.out.println("Calling setValueAt row " + row + ", column "
+ column);
}
public void addTableModelListener(TableModelListener l) {
}
public void removeTableModelListener(TableModelListener l) {
}
}
The data shows in the table is grabbed from the db and presented as table. The "Add row to table" shows the pop-up from the form insertion but don't put the data as new row in the end of the table. However, I'm not getting any error. The "Update database" button is not working and provides java.sql.SQLException: Table not specified.. How can I improve the code ?
Instead of implementing the TableModel interface, you should be extending from the AbstractTableModel, this has default functionality of some of the "normal" functionality you don't want to replicated.
Remove the addTableModelListener and removeTableModelListener, your current implementation has essentially broken the model's contract by not providing the ability to make notifications to other observers (like the JTable)
Your insertRow method MUST call fireTableRowsInserted (from AbstractTableModel) in order to notify the JTable that the model has changed and that it needs to update itself with the new data
Java makes no guarantees that finalize will be called, don't rely on it
getRowCount will be effected by the size of the RowSet, therefore, you need to be able to either keep a running value (ie you need to increment it when you add new rows) or calculate the number of rows from the RowSet itself. I believe you can do this by moving the cursor to the end (or beyond the last position) and using getRow, don't forget though, ResultSet is 1 based, not 0 based which JTable expects
I am trying to create a checkout simulation for my coursework. So every time I search for an item I can retrieve it from the database and display it on the JTable. However, once I add an item to the list and try to add another item the old item get replaced by the new item.
I am trying to list all the item in the JTable, this is my code:
DBConnection db = new DBConnection();
try {
ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '"+ id + "'");
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
System.out.println(e);
}`
The main problem is DbUtils.resultSetToTableModel(rs), which is creating a brand new TableModel, filled with the contents of the ResultSet, this, when applied to the JTable is replacing the view with the contents of the TableModel.
In order to be able to update the table, you need to update the existing TableModel...
There are a few ways this might be achieved, by the simplest might be to use a DefaultTableModel...
Start by creating a class instance field of a DefaultTableModel...
public class ... {
//...
private DefaultTableModel stockTableModel;
//...
Then, when you want to load the stock items, you will need to initialise the model, if it's not already initialised, and then add the new results to it...
DBConnection db = new DBConnection();
try (ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '" + id + "'")) {
if (stockTableModel == null) {
stockTableModel = new DefaultTableModel();
for (int col = 0; col < metaData.getColumnCount(); col++) {
stockTableModel.addColumn(metaData.getColumnName(col + 1));
}
jTable.setModel(model);
}
while (rs.next()) {
Vector rowData = new Vector(metaData.getColumnCount());
for (int col = 0; col < metaData.getColumnCount(); col++) {
rowData.add(rs.getObject(col + 1));
}
stockTableModel.addRow(rowData);
}
} catch (SQLException exp) {
exp.printStackTrace();
}
Take a look at How to Use Tables and JDBC Database Access for more details
You can create a custom data model that allows you to insert new rows to table.
lets say that you have class, that can hold your query result fields.
public class Item implements Comparable<Item> {
private Long id;
private String message;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
public String getMessage() {
return message;
}
public void setMessage(String value) {
this.message= value;
}
#Override
public int compareTo(Item o) {
return id.compareTo(o.id);
}
}
and it needs to go to table, which has been defined somewhere like:
JTable table =new JTable();
this is a data model to your table
public class Model extends AbstractTableModel {
private List<Item> items;
public Model() {
items = new ArrayList<>();
}
#Override
public int getRowCount() {
return items.size();
}
#Override
public int getColumnCount() {
return 3;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex > items.size() - 1 || rowIndex < 0) {
return "";
}
final Item get = items.get(rowIndex);
switch (columnIndex) {
case 0:
return get.getId();
case 1:
return get.getMessage();
}
return "";
}
#Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "id";
case 1:
return "message";
}
return "";
}
public void addItem(Item i) {
items.add(i);
fireTableDataChanged();
}
public void addItem(ResultSet rs) {
try {
Item item = new Item();
item.setId(rs.getLong("ID"));
item.setMessage(rs.getString("MESSAGE"));
items.add(item);
fireTableDataChanged();
} catch (SQLException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
now create field
Model myModel=new Model();
and set it as a table model
table.setModel(myModel);
now every time you need to add something to table, just use our table model (i created two methods to insert data public void addItem(Item i) and public void addItem(ResultSet rs).
this should work. If you need to clear table sometimes, just add pubic method public void clear() to your model, in which you will clear items list and call fireTableDataChanged();. It is necessary, otherwise GUI will not refresh.
EDIT
Your code should be like
DBConnection db = new DBConnection();
try {
ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '" + id + "'");
myModel.add(rs);
} catch (Exception e) {
System.out.println(e);
}
Just add a row to your JTable Model every time you have your result...
refer to this SO question
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
or in your case
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{searchResultData});
Here is a Controller Class of MVC:
public class EventController extends MouseAdapter implements ActionListener {
private EventModel model;
private EventView view;
/** Constructor */
public EventController(EventModel myModel, EventView myView){
model = myModel;
view = myView;
}
public void setUpListeners() {
this.view.addEventButton.addActionListener(this);
this.view.addEventMenuItem.addActionListener(this);
this.view.editEventMenuItem.addActionListener(this);
this.view.tableEvent.addMouseListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
Object button = e.getSource();
if(button==this.view.addEventButton) {
setEventDetails();
}
else if (button==this.view.addEventMenuItem) {
this.view.addDialog.setVisible(true);
}
else if(button==this.view.editEventMenuItem) {
this.view.editDialog.setVisible(true);
}
}
/*to change the display of label text of the VIEW according to the selected row of the table tableEvent*/
#Override
public void mouseClicked(java.awt.event.MouseEvent event) {
int rowSelected = view.tableEvent.getSelectedRow();
String tableClick = view.tableEvent.getModel().getValueAt(view.tableEvent.convertRowIndexToModel(rowSelected), 0).toString();
Events e = model.getEvent(tableClick); //tell model to change its state based on user input on views
view.changeDisplay(e);
}
Here is View Class and its changeDisplay() method to change label text appropriately:
public class EventView extends javax.swing.JFrame {
private EventModel model;
public void changeDisplay(Events e) {
evTitle.setText(""+e.getEventName());
evWhen.setText("When: "+ e.getEventDate());
evWhere.setText("Where: "+ e.getEventVenue());
evDescription.setText("Description: "+ e.getEventDetail());
evOpportunity.setText("Opporunity: "+ e.getEventOpportunity());
evMoreDet.setText("More Details: "+ e.getEventMoreDetails());
}
}
Here is Model Class:
public class EventModel {
Connection conn = JavaConnect.ConnectDB();
PreparedStatement pst = null;
ResultSet rs = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Events e = new Events();
public void addEvent(String name, Date date,String start, String venue, String details,
String opportunity, String more, String end) throws SQLException {
try {
String qry = "INSERT INTO EVENT(eventName,date,time,venue,details,opportunity,moreDetails,endTime) VALUES (?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(qry);
pst.setString(1, name);
pst.setString(2, sdf.format(date));
pst.setString(3, start);
pst.setString(4, venue);
pst.setString(5, details);
pst.setString(6, opportunity);
pst.setString(7, more);
pst.setString(8, end);
pst.executeUpdate();
}
finally{
try{ pst.close(); }
catch (SQLException se) {}
}
}
public Events getEvent(String tableClick) {
try {
pst = conn.prepareStatement("SELECT * FROM Event WHERE eventID='"+tableClick+"' ");
rs = pst.executeQuery();
while(rs.next()){
e.setEventName(rs.getString(2));
System.out.println(rs.getString(2));
e.setEventDate(rs.getString(3));
e.setEventTime(rs.getString(4));
e.setEventVenue(rs.getString(5));
e.setEventDetail(rs.getString(6));
e.setEventOpportunity(rs.getString(7));
e.setEventMoreDetails(rs.getString(8));
e.setEndTime(rs.getString(9));
rs.close();
pst.close();
}
}
catch(SQLException ex){
ex.printStackTrace();
}
return e;
} //end getEvent
}
My program is having a little error which I cant seem to fix for ages. Basically, whenever I click the row of the table (tableEvent) it should display the appropriate text in the labels next to the table as shown in the screenshot with the event "Software development careers event". This works fine on the first execution, but the mouseClicked event method in the controller does not change the display of the text after I've added an event through the addEvent method of the model. I am not sure what it is, whether I did something wrong with instantiation of an object of class Events, my addEvent method is wrong, or the actual mouseClicked overridden method in controller is wrong. What could it be?
I'm not sure that my answer helps you, but selection changes should be detected using ListSelectionListener. It's better because it provides reaction not only for the mouse clicks, but also for key events.
To add listener to your table simply use the selection model of the table:
myTable.getSelectionModel().addListSelectionListener(myListener)
Probably this change helps you to solve your problem