I have a JTable bound with my database using Netbeans Wizard. Everything works fine but when I try to change the query and results based on filtering the table stops displaying the new results.
private static void updateResults() {
if (complaintList != null) {
LOG.log(Level.FINE, getQuery());
complaintList.clear();
complaintQuery = entityManager.createQuery(getQuery())
.setMaxResults(1000);
complaintList = complaintQuery.getResultList();
LOG.log(Level.INFO, "Result size: {0}", complaintList.size());
complaints.firePropertyChange(null, true, false);
}
}
Where:
complaintList is the list containing the results which is bound to the table.
complaintQuery is the bound Query.
I verified that the result has a size > 0. The contents of the table only update when I click/move one of the scroll bars.
Might not be pretty, but made it work by selecting the last row on the table after the change.
if (!complaintList.isEmpty()) {
complaints.changeSelection(complaintList.size() - 1, 0,
false, false);
}
Related
I have an activity where I create Tablerow programatically, as I don't know how many files I need.
Each TableRow has an ID starting by 100 and continue 200, 300 and so on.
When I create the row 3 the TableRow's ID is 300.
Then when someone edit other row I need to know what row is just to work with the elements of the row.
My problem: previous value:
trActiva.getId()=300
Then this is my code I put:
lineaActiva = (tv.getId()) / 100 * 100;
trActiva = findViewById(lineaActiva);
just on the point before these two lines trActiva.getId()=300
after the first row of the code lineaActiva = 200
That means after the second line trActiva.getId() should be 200 but it is still 300.
More weird things:
after these two lines:
trActiva.getId()=300
findViewById(lineaActiva).getId()=200
What is happening here? Why trActiva is not changing?
Thank you!!
We are unsure how you are increasing your Id and how you are storing your data as well how do you view 300 rows on a computer screen
So a lot of code is missing to give a very pointed answer to your question
Here is a table we populate from a Derby Database
The table is named ptable and we might also mention we are using a Model View Controller pattern to manage the data to GET and SET variables
First we read from the Database and populate the ptable with this code
private void ReadFromParent() throws SQLException{
ObservableList<ParentModel> TableData = FXCollections.observableArrayList();
stmnt = conn.createStatement();
ResultSet rs = stmnt.executeQuery("SELECT * FROM Parent");
while (rs.next()){// Add data to observableArrayList TableData to select a table ROW
TableData.add(new ParentModel(rs.getString("PID"),rs.getString("pMonth"),rs.getString("pYear")));
}
PropertyValueFactory<ParentModel, String> IDCellValueFactory = new PropertyValueFactory<>("PID");
colID.setCellValueFactory(IDCellValueFactory);
PropertyValueFactory<ParentModel, String> DateCellValueFactory = new PropertyValueFactory<>("pMonth");
colMonth.setCellValueFactory(DateCellValueFactory);
PropertyValueFactory<ParentModel, String> TypeCellValueFactory = new PropertyValueFactory<>("pYear");
colYear.setCellValueFactory(TypeCellValueFactory);
// ================================================================
// colTxDate are the ID's for the tableview columns
// sortDate are the Column Names for the Database TABLE CDBalance
// ================================================================
colMonth.setStyle("-fx-alignment: CENTER;");
colYear.setStyle("-fx-alignment:CENTER;");
Collections.sort(TableData, (p2, p1)-> p1.getPID().compareToIgnoreCase(p2.getPID()));
// Line of Code above Sorts Database Columns based on VARIABLE in ParentModel
// Change p2,p1 to sort Ascending or Descending
if(TableData.size() < 15) {// Format TableView to display Vertical ScrollBar
ptable.setPrefWidth(336);// 19 is the off set
}else {
ptable.setPrefWidth(355);
} ptable.setItems(TableData);
stmnt.close();
}
Then we write listener code to permit us to view the details of the row selected
Notice we get the ID from the row selected
This is where you can use that value to find the new entry that is greater than 300
OR you can write a Search query on the table that finds all records that have an ID greater than 300
Here is the code that permits you to click on a row in the table
private void showTableDataDetails(ParentModel info) throws IOException{
if (info != null) {
info = (ParentModel) ptable.getSelectionModel().getSelectedItem();
strID = info.getPID();
strMONTH = info.getPMonth();
strYEAR = info.getPYear();
toChildView();
System.out.println("########### PID "+strID);
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
ptable.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends ParentModel>
observable,ParentModel oldValue, ParentModel newValue) -> {
try {
showTableDataDetails((ParentModel) newValue); // When a row of the table is Selected call
// Proper Construction // showTableDataDetails method
} catch (IOException ex) {
Logger.getLogger(ParentTableViewController.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
Hope this helps and Welcome to Stack Overflow
PLEASE post a little more code in the future so your question can have a more definitive answer
I want to create a chart using mysql database with Jfreechart, this is the code i used :
try {
String query =
"Select id,Prop_menages_Urbains_Proprietaires from fes";
JDBCCategoryDataset dataset =
new JDBCCategoryDataset(
DBConnection.DBConnection(),
query
);
JFreeChart chart =
ChartFactory.createBarChart(
"test",
"id",
"Prop_menages_Urbains_Proprietaires",
dataset,
PlotOrientation.VERTICAL,
false,
true,
true
);
BarRenderer render = null;
CategoryPlot plot = null;
render = new BarRenderer();
ChartFrame fram =
new ChartFrame("test", chart);
fram.setVisible(true);
fram.setSize(600,650);
}
catch(Exception ex) {
System.out.println("Erreur: " + ex);
}
after the execution the barchart doesn't show up although there are no errors in the code syntax
any help please ?
UPDATE: i tried the same code but this time i used other columns from the database and it worked , what's the issues with the other one knowing that they're all numbers
The JDBCCategoryDataset API specifies:
The SQL query must return at least two columns. The first column will be the category name and remaining columns values (each column represents a series).
This complete example, which you have successfully adapted, illustrates the effect. The question then becomes,
What's the issues with the other one knowing that they're all numbers?
The executeQuery() source shows how each of the java.sql.Types is mapped to a numeric value: a numeric type becomes a Number directly, a date type becomes a Number representing milliseconds from the Java epoch, and a character type is converted using Double.valueOf(); the default is null.
In this case, verify that Prop_menages_Urbains_Proprietaires has a SQL type that is suitable for conversion to a numeric value.
I have recently tried to code a small java file which will insert a row into an already existing table in a .odt document. The table itself has 4 rows and 3 column, but I would like to implement a check which will expand that table if the content to be inserted is larger than 4. However, every time I try to get the table's rows, it returns a null pointer. I am not that familiar with UNO api, but as far as i read through the documentation, the class XColumnsAndRowRange should be used in this situation. My code is as follows:
XTextTablesSupplier xTablesSupplier = (XTextTablesSupplier) UnoRuntime.queryInterface(XTextTablesSupplier.class, xTextDocument);
XNameAccess xNamedTables = xTablesSupplier.getTextTables();
try {
Object table = xNamedTables.getByName(tblName);
XTextTable xTable = (XTextTable) UnoRuntime.queryInterface(XTextTable.class, table);
XCellRange xCellRange = (XCellRange) UnoRuntime.queryInterface(XCellRange.class, table);
if(flag){
XColumnRowRange xCollumnAndRowRange =(XColumnRowRange)
UnoRuntime.queryInterface(XColumnRowRange.class, xCellRange);
XTableRows rows = xCollumnAndRowRange.getRows();
System.out.println("Testing if this works");
rows.insertByIndex(4, size-4);
}
I am not sure if I am missing something here or if I should be using a different function.
As Lyrl suggested, this works:
XTableRows rows = xTable.getRows();
Apparently XColumnRowRange is only used for spreadsheets.
Note: With Basic or Python you would not have this problem, because those languages do not need queryInterface. The code would simply be:
table = tables.getByName(tblName)
rows = table.getRows()
I am working with apose words java recently.
In my first page I have a table need to merge, which can grow any size, no fixed number of rows and at the end of my first page, I want to keep some content (for example contact details) to be fixed. (Note: I can't keep contact details in Footer or in foot note section because of some formatting I need to ensure which can't maintain in footer or foot note section)
On growing of table as many rows, My content is going down, But I want to fix it at the end of my first page. if table grows bigger in size, wanted to skip the content and render table in next page.
is there any solution/work around for this?
My expected results are like below....
Page 1 Start
dynamic Table row1
dynamic Table row2
dynamic Table row3
Contact Details ,wanted to fix at the end of my first page
Page 1 end
Page 2 Start
dynamic table row 4
dynamic table row 5
........
For your scenario, ideally the contact details should be set in a footer. It is possible, but very risky.
First create a new document, either in Aspose.Words or MS Word, it will be used as a template.
Add a blank table on top
Add contact details, after the blank table
Add a bookmark, after the contact details
Now, using Aspose.Words, you can check the location of the bookmark, every time you are adding a new row in the table. If bookmark is at page 1, add new row to the first table. If bookmark is at page 2, add new row to the second table. Below is the sample code that adds rows to the table, keeping the contact details fixed on page 1.
Template document: Google drive link
Java source code is given below.
public static void main(String[] args)
{
try
{
String template = Common.DATA_DIR + "Contact Template.docx";
String saveDocument = Common.DATA_DIR + "Contact with tables.docx";
String bookmarkNameContact = "ContactEnd";
// Load the template
com.aspose.words.Document wordDoc = new com.aspose.words.Document(template);
DocumentBuilder builder = new DocumentBuilder(wordDoc);
// Find the contacts bookmark
com.aspose.words.Bookmark bookmarkContact = wordDoc.getRange().getBookmarks().get(bookmarkNameContact);
// Set the table with null
com.aspose.words.Table table = null;
// Add some rows
for (int i = 0; i < 50; i++)
{
// If contacts bookmark is on 1st page, add new rows to first table
if (getBookmarkPage(wordDoc, bookmarkContact) == 1)
{
table = (com.aspose.words.Table) wordDoc.getChild(NodeType.TABLE, 0, true);
} else
{
// If the contacts bookmark is on second page, add rows to second table
table = (com.aspose.words.Table) wordDoc.getChild(NodeType.TABLE, 1, true);
// If there is no second table, create it
if (table == null)
{
table = createNewTable(wordDoc, bookmarkContact);
}
}
// Add rows dynamically to either first or second table
addRow(wordDoc, table, "some text " + i);
}
// Save the document
wordDoc.save(saveDocument);
} catch (Exception ex)
{
System.err.println(ex.getMessage());
}
}
private static com.aspose.words.Table createNewTable(com.aspose.words.Document wordDoc, com.aspose.words.Bookmark bookmarkContact) throws Exception
{
// Get the first table and clone it to create the second one
com.aspose.words.Table firstTable = (com.aspose.words.Table) wordDoc.getChild(NodeType.TABLE, 0, true);
com.aspose.words.Table table = (com.aspose.words.Table) firstTable.deepClone(true);
// Add the second table after the bookmark
bookmarkContact.getBookmarkEnd().getParentNode().getParentNode().appendChild(table);
// Delete all its rows
table.getRows().clear();
return table;
}
// Add a new row to the table
private static void addRow(com.aspose.words.Document wordDoc, com.aspose.words.Table table, String text)
{
// Create a new row
com.aspose.words.Row row = new com.aspose.words.Row(wordDoc);
row.getRowFormat().setAllowBreakAcrossPages(true);
// Add it to the table
table.appendChild(row);
// Add cells to the row
for (int iCell = 0; iCell < 4; iCell++)
{
// Create a new cell and set text inside it
com.aspose.words.Cell cell = new com.aspose.words.Cell(wordDoc);
cell.appendChild(new com.aspose.words.Paragraph(wordDoc));
cell.getFirstParagraph().appendChild(new Run(wordDoc, text));
cell.getFirstParagraph().getParagraphFormat().setSpaceAfter(0);
row.appendChild(cell);
}
}
private static int getBookmarkPage(com.aspose.words.Document wordDoc, com.aspose.words.Bookmark bookmarkContact) throws Exception
{
// Find the page number, where our contacts bookmark is
LayoutCollector collector = new LayoutCollector(wordDoc);
return collector.getStartPageIndex(bookmarkContact.getBookmarkEnd());
}
I work with Aspose as Developer Evangelist.
i use Jpanel with a Jlabel on it as render-component in my jtable. i add "fake-entries" (=JLabel without text) if there are not enough entries to fill the whole table.
it happens from time to time that text is displayed in the jtable after deleting it. each entrie contains the text of the last table entrie (before the delete) e.g. "Gegeben Bar..."
Even calling a repaint doesn't solve the problem. Only after inserting a new row the table gets displayed correctly. jre is 1.4_09 on running on linux
here's what i do after clearing table-elements
model.fireTableRowsDeleted( firstRow, firstRow + rowCount - 1);
model.fireTableDataChanged();
i've a function to log the table elements and component when the problem occures
for(int i=0; i < model.getRowCount();i++){
try
{
bw.newLine();
bw.write("el"+i+" "+model.getValueAt(i, 1)+"->" +model.getValueAt(i, 1).hashCode());
bw.newLine();
bw.write(" ->"+((JPanel)renderer.getTableCellRendererComponent(this, model.getValueAt(i,1),false, false, i, 0)).getComponent(0).hashCode()+"->" +((JPanel)renderer.getTableCellRendererComponent(this, model.getValueAt(i,1),false, false, i, 0)).getComponent(0));
bw.newLine();
if(observedElement.getElements().size()>i)
bw.write(" -> "+observedElement.getElements().get(i));
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
in the output you can see the neither the element nor the jlabel contain text
el0 ->5840819
->20546691->javax.swing.JLabel[,4,0,273x19,alignmentX=0.0,alignmentY=null,border=,flags=8,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEFT,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=<html><font face="Inconsolata,Inconsolata"></font></html>,verticalAlignment=CENTER,verticalTextPosition=CENTER]
->
el1 ->5840819
->20546691->javax.swing.JLabel[,4,0,273x19,alignmentX=0.0,alignmentY=null,border=,flags=8,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEFT,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=<html><font face="Inconsolata,Inconsolata"></font></html>,verticalAlignment=CENTER,verticalTextPosition=CENTER]
->
el2 ->5840819
->20546691->javax.swing.JLabel[,4,0,273x19,alignmentX=0.0,alignmentY=null,border=,flags=8,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEFT,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=<html><font face="Inconsolata,Inconsolata"></font></html>,verticalAlignment=CENTER,verticalTextPosition=CENTER]
->
...
any idea what might be the cause of the problem or how to solve it?