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));
//CODE TO SET WIDTH OF JTABLE IN VIEWS
}
catch(SQLException e){
e.printStackTrace();
}
finally {
try {rs.close(); pst.close();}
catch(SQLException e){} }
return model;
}
Above is a method of the Model class, responsible for setting up the table model for the table I have in Views called tableEvent.
The Controller class uses the above method to set change the state of the tableEvent of Views Class. Please note tableEvent in Views is empty/nothing there. Model passes values of rs to Controller which will then change the display of the table and populate values.
Heres what I mean:
view.tableEvent.setModel(model.getTableData());
However, I am trying to set the width of the columns in Model rather than inViews through tableEvent.getColumnModel().getColumn(1).setPreferredWidth(60);. if I pass the table itself to the method getTableData() in order to set the width of the column, it doesnt really work. Is there a way I can specify my desired width of the first 4 column of the table in Model class in geTableData() method somehow so that it is consistent at all times. Right now I have this at part of the constructor of Views class which obviously means its only to my desired width only at initialisation.
If the JTable or TableModel are empty and have no column information, then you need to supply that information yourself.
You could either create a new TableColumnModel, add the required TableColumns to it, providing the width information you want/need and apply that model to the JTable.
You would then need to fill in the TableModel and supply that to the JTable as well.
I would, personally, extract the meta data from the ResultSet BEFORE I tried retrieving the data from it.
Related
I'm working on a simple GUI where I drag combobox and edit the values here I i have a class categories and then 3 methods of rice,sweets and meal. I would like to be to call these three methods on my frame and then from there I want to fill the values into the combo box. An important thing that these 3 methods of categories class are connected with access so they fetch data from there. My question is: What will be the return type of these particular methods?
public String rice()
{
String query ="select * from categories";
String end=null;
String a ;
try{
ps=conn.prepareStatement(query);
rs=ps.executeQuery();
while(rs.next())
{
end=end+rs.getString("Rice")+"\t";
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return end;
}`
now in another class
Combo_boxes obj = new Combo_boxes();
comboBox.addItem(obj.rice());
When I call this method it will to return a value of 1 row of database and then I want to place it into the combo box and then next row so from this,i will place every item from database. When I update my database it should automatically update the combo box.
This is my first question here and I hope I am not repeating someone else's question. I will try and explain the problem as much as I can in the next few lines. Pardon my English if its really bad .
So I have here a JTable in which I would like to retrieve values from a database. So far I can add 1 value and I know why this is. The question is . How do I add multiple values to this table ?
This is the method I use in my operations to find a gun in a specific shop with its quantity
public ResultSet gunSearch(String id, int qty, int storeId) {
try {
String s = "SELECT gunID, gunName AS \"Gun Name\", gunPrice AS \"Price\", SellCost AS \"Cost\", availableQty AS \"Amount Available\", "+qty+" AS \"Quantity\" FROM Guns WHERE gunId = '" + id + "'AND storeId='"+storeId+"'";
pstmt = conn.prepareStatement(s);
rset = pstmt.executeQuery(s);
} catch (Exception ex) {
System.out.println("Error here at searchByProdId Operation "+ex);
}
return rset;
}
For my GUI I use the following code to display the information entered by the user
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(enterBtn)){
String gunID = gunIdText.getText();
int qty = Integer.parseInt(quantityText.getText());
table.setModel(DbUtils.resultSetToTableModel(op.gunSearch(gunID, qty, storeId)));
Whenever I click the Enter button the column of data is retrieved from the database. However if I re-enter another gunId and quantity , the previous column disappears and the new column of data is retrieved from the database.
How could I possibly , enter couple of different gunId's and quantitie's into the JTable ?
Your gunSearch method only returns one result. You then completely recreate the TableModel from this one result, erasing whatever you had in the old model.
You'll need to concoct a new method that can take a Collection<String> (a collection of gun ids) and return a row for each id provided.
Alternatively, you can create a method that adds a gun to an existing TableModel rather than recreating the whole model from scratch every time. It depends on how you want the application to work, which option is better.
at the moment I have an app that allows me to display data in a Jtable and then when I double click the Jtable this open a little window to edit only 3 fields, comments, expiration date and description. I update the this values (whit a preparedStatement) the thing is that everytime that I make an update to the database my table just refresh itself, changing the dateFormat with the new value that I've just inserted in my other window but with a different format!. How is this possible?
I' don't understand this because the only I only set a model to the table when I press my "search" button which contains the following code:
ArrayList<FiltrosResumen> filtrosResumenList = MainFrame.dataBase.searchFiltroResumen(query);
FiltrosResumenTableModel resumenModel = new FiltrosResumenTableModel(filtrosResumenList);
this.resumenTable.setModel(resumenModel);
hideColumns(1);
I'm using a custom table model containing all the table Fields, so first as you can see I colect all the rows from the database into a ArrayList from a custom object "FiltrosResumen", then I pass this to the constructor from my customTable model "FiltrosResumenTableModel" which extends AbstractTableMode I'm not using any special renders the most important methods are
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return this.filtrosResumen.get(rowIndex).getIdFiltro();
//....
//case 9:
default:
return null;
}
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
FiltrosResumen filtroResumen = new FiltrosResumen();
switch (columnIndex) {
case 0:
filtroResumen = this.filtrosResumen.get(rowIndex);
filtroResumen.setIdFiltro(Long.parseLong(aValue.toString()));
this.fireTableCellUpdated(rowIndex, columnIndex);
break;}
//....
//case 9:
}
And the constructor
public FiltrosResumenTableModel(List<FiltrosResumen> filtrosResumen) {
this.filtrosResumen = filtrosResumen;
}
And as I stated before, the database does not interact directly whit the table since storing the query result in a ArrayList, and then sending this to the constructor of my customTableModel.
EDIT: In order to change the value from one of the rows items I send a FiltrosResumen Object in this way:
FiltrosResumenTableModel modelo = (FiltrosResumenTableModel) this.resumenTable.getModel();
resumen = modelo.getResumen(row);
EditResumenIF editConexionesIF = new EditResumenIF(resumen);
EDIT: Passing a the resumen object to a InternalFrame Constructor (EditResumenIF).So in this new InternalFrame (EditResumenIF) I assign the values to a JCalendar and a JTextField to change the values and then save them. Afther the same object received by the constructor to a method that does the query and then return a string, ( if the string it's empty it' means that the query was successful without any mistakes)
String error = MainFrame.dataBase.updateResumen(resumen, resumen.getIdFiltro());
How comes that my Table knows that the value changed?
The default renderer for a cell of type Object.class is "a label that displays the object's string value." Unless your implementation of TableModel override's getColumnClass() to return some other value, your result is not unexpected. You might compare this example using DefaultTableModel to your implementation.
Addendum: How does my table know that the value changed?
JTable is a TableModelListener; any change to the model is (or should be) propagated to the table. Absent a complete example, I'm guessing that you are using a second table, table2, to edit a copy of certain data obtained from the original, table1.
Verify that you are copying the data in getResumen() and not just copying a reference to the table1 model.
In your implementation of setValueAt() in the TableModel of table2, update the model of table1. The exact mechanism depends on your TableModel; two approaches are contrasted here.
Addendum: I'm not using another tableā¦I'm passing a reference to my internal frame.
The same principles would apply. As an alternative to directly coupling the models, let the table's model be a PropertyChangeListener to the internal frame, as shown here.
I am using jTable in netbeans. After selection of combobox if i select employee id 1 it show all data of emp 1 in jTable. But next time when i choose emmployee id 2 jTable shows single value of emp id 1's and all another values of empid 2.
My code is given below
Connect c = new Connect();//connection to database
con = (Connection) c.getConnection();
st = (Statement)con.createStatement();
String ddate = (String)text.getSelectedItem();
System.out.println("id " +ddate);
rs = st.executeQuery("select e.employee_id,e.`first_name`, i.outtime, i.outtime_date from tbl_employee e,tbl_outtime i where e.employee_id=i.outtime_emp_id and i.`outtime_date` LIKE '%/"+month2+"/"+year1+"'and outtime_emp_id="+ddate);
while(rs.next())
{
String dat1=rs.getString("outtime_date");
String e1=rs.getString("employee_id");
System.out.println(e1);
st33=(Statement) con.createStatement();
rs33=st33.executeQuery("select i.intime, i.intime_date from tbl_employee e,tbl_intime
i where e.employee_id=i.intime_emp_id and i.`intime_date`='"+dat1+"' and
i.intime_emp_id="+e1);
if(rs33.next())
{
int emp=rs.getInt("employee_id");
System.out.println(emp);
String name=rs.getString("first_name");
String dept=rs33.getString("intime");
String desig=rs.getString("outtime");
String join=rs33.getString("intime_date");
jTable1.setValueAt(emp, cnt, 0);
jTable1.setValueAt(name, cnt, 1);
jTable1.setValueAt(dept, cnt, 2);
jTable1.setValueAt(desig, cnt, 3);
jTable1.setValueAt(join, cnt, 4);
cnt=cnt+1;
}
}
Tell me solution if anyone knows.
read tutorial about JTable
all data for JTables view are stored into XxxTableModel
have to clear XxxTableModel, and add new row(s) from JDBC to the XxxTableModel
Use TableModel for adding row.
Read
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
for samples.
Like all other Swing components, a table consists of two parts: a view part (the JTable) and a model part (the TableModel). The view is updated when the model indicates it has been changed by throwing events. See the table tutorial for more information.
So for your use-case, you can either adjust the existing TableModel or create a new one. I would personally opt to create a new one since you are working with a database.
Note that Swing components should only be accessed and modified on the Event Dispatch Thread, and that long running tasks (as querying a database) should not happen on this thread (see the Swing concurrency tutorial). That is why I would recommend to create a new TableModel. You can create this model on the worker thread you use for querying the database, and the replace the model in one go on the Event Dispatch Thread. The SwingWorker class is most suited for this.
EDIT(NEW):
Still haven't figured out how to populate the cboxCustomers. I've been at it for the past day or two, but without luck.
In case anyone can help: http://pastebin.com/e5wibRYw
I went from cats to customers, btw.
I tried Mr. Xymon's approach, but didn't implement it correctly since it didn't work.
Whatever event I used to handle the population I always got NullPointerException for whatever control/event I was trying to use.
OLD:
There's a JForm. On it, there's a single combo box. Also have a single table with cats - cats. Each cat has id, and catName.
What I wanted to do was when I click on the combo box, thus expanding it, populate it with all id of cats that are found in cats table.
SLOVED. Asnwer below.
Unfortunately I receive numerous unreported exception java.sql.SQLException from the lines I've indicated with >:
private void cboxCatsMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
// create an array list to be filled with cat's ids
ArrayList<String> cats = new ArrayList<String>();
String query = "SELECT id FROM cats ORDER BY id";
>java.sql.PreparedStatement stm = connection.prepareStatement(query);
>ResultSet rs = stm.executeQuery(query);
>while(rs.next()){
>String cat = rs.getString("id");
// add cat's ids tp the array list
cats.add(cat);
}
>rs.close();
// populate the combo box
DefaultComboBoxModel model = new DefaultComboBoxModel(cats.toArray());
cboxCats.setModel(model);
}
OLD ANSWER:
I think I fixed it. I just had to wrap all of the highlighted lines of code together into one big try-catch statement that would catch SQLException. Problem is - the combo box doesn't get populated with id values when I expand it. Why is that? Am I using the wrong event?
Isn't better to populate your combo box with cat's name instead of the id? I came up with a different solution by directly adding field value into model instead of using ArrayList. You have to perform it within the constructor to populate the combo box upon loading the form.
DefaultComboBoxModel list = new DefaultComboBoxModel();
JComboBox cbo_cats = new JComboBox(list);
// at constructor or a user-defined method that's called from constructor
try{
// assume that all objects were all properly defined
s = con.createStatement();
s.executeQuery("SELECT * FROM cats ORDER BY catName");
rs = s.getResultSet();
while(rs.next()){
//int id = rs.getInt("id");
//list.addElement(id);
String c = rs.getString("catName");
list.addElement(c);
}
}catch(Exception err){
System.out.println(err);
}
As you can see I didn't use prepared statements but you can easily change that.