I am using ucanaccess to link my database to my code but whenever I run it it doesnt work as I intend it to if it even runs at all. I just want to reorder the primary key (ID) into numerical order using ORDER BY ID;. When I edit the database it doesnt reorder when I run the method, it just pushes the edited ID to the bottom and orders them there. I am also confused if I should use an array sort in order to reorganize the entire table? Any help is appreciated. This runs whenever I attempt to edit the table in the GUI.
Source code google drive
public void reorder()
{
for(int i = 0 ; i < size - 1;i++)
{
for(int j = i+1 ; j< size;j++)
{
if(launch[i].getID() > launch[j].getID())
{
Launch temp = launch[i];
launch[i] = launch[j];
launch[j] = temp;
System.out.println(launch[i]);
}
}
}
}
public void orderByID()
{
String sql = "SELECT * FROM LaunchPriceList ORDER BY ID DESC";
try
{
dbman.updateQuery(sql);
//reorder();
}
catch(SQLException e)
{
System.out.println("Error Order by: " + e);
}
}
I am unable to access your code (for whatever the n/w restrictions). Having said that...
You can start off by creating a custom implementation of TableModel by extending AbstractTableModel
Coming to populating the TableModel, you start with iterating through the result set and creating a TreeSet with a custom Comparator that compares the ID attribute.
once done, you can create the table with the previously populated table model. E.g.
JTable t = new JTable(model);
Updating the TableModel with refreshed data will automatically refresh the table.
Related
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.
This question already has an answer here:
How to add checkboxes to JTABLE swing [closed]
(1 answer)
Closed 8 years ago.
i am using swings for creating the desktop application . i have created the functionality which provided the data from the database and insert that into the Jtable .now i want to use provide the additional facility that include the additional column with the check box and the a button to delete that perticuler column (which is checked ) when the button is clicked .i have used the netbeans and it provide the maximum drag and drop option. i am not able to figure it out that the how and where to insert the instance of the checkbox in the current code for inserting the checkbox for the each and every row .
For providing the checkbox with the each row do have to generate the multiple instance of the check box
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
java.sql.Connection con = new DBConnection().getConnection();
PreparedStatement pst;
String Q;
Q = "select * from userregister ";
try {
pst = con.prepareStatement(Q);
ResultSet rs = null;
rs = pst.executeQuery();
String a, b, c, d;
int x = 0;
// DefaultTableModel dt = new DefaultTableModel(data, columnNames);
JCheckBox c1 = new JCheckBox();
for (int i = 0; rs.next(); i++) {
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
d = rs.getString(4);
jTable2.setValueAt(a, i, 0);
jTable2.setValueAt(b, i, 1);
jTable2.setValueAt(c, i, 2);
jTable2.setValueAt(d, i, 3);
jTable2.setValueAt(, i,4);
}
//jTable1.setAutoscrolls(rootPaneCheckingEnabled);
// TODO add your handling code here:
} catch (SQLException ex) {
Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
}
}
this is the methods that insert the data into the table . also i want to know that how do i be able to find out that which check box is checked and how to use the variable to respond the request of the multiple deletes . plz help
You have to take a look to Concepts: Editors and Renderers section of How to Use Tables tutorial.
This JCheckBox you're looking for is the default renderer/editor for Boolean class. Having said this JTable makes use of TableModel.getColumnClass() to decide the proper renderer/editor. If you use DefaultTableModel the implementation of the aforementioned method always return Object.class so you would have to override it to return Boolean.class. For instance let's say the first column will contain booleans:
DefaultTableModel model = new DefaultTableModel() {
#Override
Class<?> getColumnClass(int columnIndex) {
return columnIndex == 0 ? Boolean.class : super.getColumnClass(columnIndex);
}
};
It is all well explained in the linked tutorial.
Addendum
Another approach is shown in this Q&A: Checkbox in only one JTable Cell. This is useful when a given column may contain different types of values (booleans, numbers, strings...) so overriding getColumnClass() is not feasible. Don't think it's your case but it might be helpful.
also i want to know that how do i be able to find out that which check
box is checked and how to use the variable to respond the request of
the multiple deletes
Just iterate over the rows asking for the column value (true/false). If it's "selected" (true) then delete it:
TableModel model = table.getModel();
for(int i = 0; i < model.getRowCount(); i++) {
if((Boolean)model.getValueAt(i, 0)) {
// delete the row
}
}
Off-topic
Database calls are time consuming tasks and may block the Event Dispatch Thread (a.k.a. EDT) causing the GUI become unresponsive. The EDT is a single and special thread where Swing components creation and update take place. To avoid block this thread consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing trail.
What I am trying to do is retrieve an ArrayList from another database manager class. Unfortunately all I can do because the manager class cannot work statically is create an instance in another class, then call the method. Then I got myself into passing that same instance into the method which asked for an SQLiteDatabase object. Now I've worked myself into a bind of confusion, when all I really want is to do is retrieve the arraylist to display a listview of elements from an SQL column.
EDIT: My post lacked clarity, so I'll try to specify exactly what is going wrong and what I am trying to accomplish here:
In a display (output) activity, I am trying to use a ListView to display elements contained in an SQL database. Currently, I am only focusing on one column (Assignment Names). My approach involved using a get method built into the database manager class, but because you cannot reference that method statically, I tried to use the method by creating an instance of that manager class. This would return an ArrayList of Inputted objects (each containing a name). It seemed to have worked, but when running the program, the LogCat protested that I was calling getDatabase recursively. After looking online, people recommended that I fix the issue by changing the method to ask for (SQLiteDatabase db) as parameters so the same database gets tossed around in the manager. Now I get confused here-- I'm not sure what to pass into this method from the display activity. It also doesn't help that from what I've heard from the comments, my get method doesn't traverse the SQL database properly. If you can solve this puzzle THANK YOU!
I'll post my code for diagnosis, hopefully an outside view will show exactly what's wrong with everything I'm trying here.
public Cursor getAssignmentNames(SQLiteDatabase db) {
return db.query(false, ASSIGNMENT_TABLE, COLUMN_TITLES,
" WHERE " + ASSIGNMENT_NAME + " ", null, null, null, " ORDER BY "+ASSIGNMENT_URGENCY_RATING, null);
}
/
public ArrayList<Inputted> getListOfAssignments (SQLiteDatabase db) {
Cursor names = getAssignmentNames(db);
ArrayList<Inputted> assList = new ArrayList<Inputted>();
names.moveToFirst();
while (!cursorsAreAfterLast(names) ) {
int go = 0;
assList.add(new Inputted(names.getString(go))
names.moveToNext();
go++;
}
return assList;
}
/
DBRecordsLayer assignmentRecords = new DBRecordsLayer(this,
"assignment.db", null, 1);
ArrayList<Inputted> assList = DBRecordsLayer.getListOfAssignments(assignmentRecords);
Your code is a bit confusing... In each iteration of the while loop, you are incrementing the cursor (names.moveToNext()); You are also incrementing go.
The result would be:
1st iteration: You are taking the data from the first column of the first query
2nd iteration: You are taking the data from the second column of the second query
etc...
I'm assume that you want to be reading data from the same column of the database for each iteration.
try this:
public ArrayList<Inputted> getListOfAssignments (SQLiteDatabase db) {
Cursor names = getAssignmentNames(db);
ArrayList<Inputted> assList = new ArrayList<Inputted>();
names.moveToFirst();
columnContainingStringToSendToInputtedConstructor = x; //replace the x with column you need from your table
while (!names.isAfterLast()) {
assList.add(new Inputted(names.getString(columnContainingStringToSendToInputtedConstructor));
names.moveToNext();
}
}
I am facing problem of duplicate rows in the JXTable. If I sort the JXTable data while the new rows are being inserted in JXTable, the final result in JXTable shows duplicate rows that make invalid result in table. Even it also shows correct count of rows that has been inserted but some rows are completely missing whereas some rows are found duplicate in JXTable.
If I sort the JXTable after all data has been inserted successfully then it is showing correct data i.e no duplicate rows and no rows missing.
code example :
I have a method to which I am passing defaultTableModel and here is am adding items in the table
public void addingItems(DefaultTableModel defaultTableModel)
{
for(int i=0;i< numberofItems;i++){
Vector vobject = new Vector();
vobject.add("...");
vobject.add("xxx");
vobject.add("yyy");
...
..
vobject.add("");
defaultTableModel.addRow(vobject);
}
one the other hand I have adding code of sorting at tableHeader actionlistener
tableheader.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
Vector data = defaultTableModel.getDataVector();
Collections.sort(data, new ColumnSorter(colIndex, ascending));
}
});
I have put code in the synchronized block but not getting success.
Please provide a better solution to handle this issue.
I have put code in the synchronized block but not getting success.
Because you have to handle synchronization not only in your sort handler block, but also on each modification operation.
For example:
...
vobject.add("");
synchronized(monitor) {
defaultTableModel.addRow(vobject);
}
}
and
...
Vector data = defaultTableModel.getDataVector();
synchronized(monitor) {
Collections.sort(data, new ColumnSorter(colIndex, ascending));
}
}
In this case your UI could look somewhat unresponsive if you have a lot of data in your table because sort is N^2*logN. If you have somewhat about 200 entries - it wouldn't make a problem for you.
We have a Virtual Table in my Eclipse RCP application. We make a call to the backend to retrieve the data to be populated in the virtual table.
We want default sorting on the table on a single column. We use ViewerComparator to achieve sorting functionality. My problem is, I am not able to get this sorting working when the table loads with the data for the 1st time. But when I click on the column, everything works fine as expected.
This is how, I set the Comparator to the column
TableViewerColumn tvc = viewer.addColumn(100, SWT.LEFT, "Name");
viewer.setColumnComparator(tvc,
new Comparator<Person>() {
#Override
public int compare(Person o1,Person o2) {
double firstValue = Double.parseDouble(o1
.getAge());
double secondValue = Double.parseDouble(o2
.getAge());
return firstValue > secondValue ? 1 : -1;
}
});
setColumnComparator method in custom viewer
public void setColumnComparator(TableViewerColumn tvc, Comparator<T> cmp){
final MyViewerComparator c = new MyViewerComparator(cmp);
final TableColumn tc = tvc.getColumn();
setComparator(c);
getTable().setSortDirection(c.getDirection());
getTable().setSortColumn(tc);
refresh();
tc.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
<same code as above>
}
});
MyViewerComparator
class MyViewerComparator extends ViewerComparator{
Comparator<T> cmp;
boolean desc = true;
MyViewerComparator(Comparator<T> cmp){
this.cmp = cmp;
}
int getDirection(){
return desc?SWT.UP:SWT.DOWN;
}
void flipDirection(){
desc = !desc;
}
#Override
public int compare(Viewer viewer, Object e1, Object e2) {
if(e1 == null || e2==null){
return 0;
}
int rc = cmp.compare((T)e1, (T)e2);
if(desc)
return -rc;
return rc;
}
}
When the table loads the data for the 1st time, it goes inside the Bolded condition in the above code as one of the object is ALWAYS NULL
Note: This functionality works totally fine if I use a Standard table rather than VIRTUAL TABLE. I am not sure whether I can change it to use Standard table as we want the lazy load functionality as well..
ContentProvider used is: ObservableListContentProvider
Please advise..
A late answer that hopefully still helps others. I encountered exactly the same problem when using SWT.VIRTUAL with an ObservableListContentProvider in combination with sorting.
The original intent of SWT.VIRTUAL is that not all elements in the contents need to be fetched to show only part of the contents. A custom content provider needs to be implemented which only has to return the elements that need to be currently shown on the screen. You also have to tell the table the total number of elements in existence. In such a use case, a table cannot be sorted in the normal way with a ViewerComparator because not all elements are known. However SWT.VIRTUAL can also be used as a performance optimization for rendering a table with many elements. This seems to work fine with the non-observable ArrayContentProvider.
But when using ObservableListContentProvider I am seeing exactly the same issue as you have. Somehow it tries to be smart and update only the elements that have actually changed. Somewhere in the depths of it's implementation something goes wrong for virtual tables, I have no clue exactly what. But I do have a solution: don't use ObservableListContentProvider at all and simply refresh the table viewer. You can e.g. use a plain ArrayContentProvider and add the following listener to the IObservableList contents of the viewer:
new IListChangeListener() {
#Override
public void handleListChange(ListChangeEvent event) {
viewer.refresh();
}
};
I actually implemented my own "SimpleObservableListContentProvider" that does exactly this, but also takes care of switching table input by implementing the inputChanged method to remove this listener from the old input list and add it to the new one.