Displaying Image in JTable - java

I'm trying to display an Image into column No 25 of a JTable :- For that i wrote the below code :-
jTable1.getColumnModel().getColumn(25).setCellRenderer(jTable1.getDefaultRenderer(ImageIcon.class));
String query = "SELECT name,type,supplier, department, manufacturer, model, serial_no, description, location, broker, dop, installation_date, expiring_date, retiring_date,warranty_info, icost, rcost, aarea, voltage, wattage, amperage, eline, capacity, plink, notes, adding_date, modification_date from assets where company_code='" + ims.MainWindow.cc + "' and adding_date between '" + new java.sql.Date(df.parse(df.format(jXDatePicker1.getDate())).getTime()) + "' and '" + new java.sql.Date(df.parse(df.format(jXDatePicker2.getDate())).getTime()) + "'";
System.out.println(query);
ResultSet rs = st.executeQuery(query);
int xx = 1;
byte[] imagedata=null;
ImageIcon format=null;
java.awt.Image originalImage=null;
java.awt.Image scaledImage=null;
javax.swing.ImageIcon newIconImage=null;
while (rs.next()) {
if(rs.getBytes(24)!=null){
imagedata=rs.getBytes(24);
format = new ImageIcon(imagedata);
originalImage = format.getImage();
scaledImage = originalImage.getScaledInstance(268, 200, java.awt.Image.SCALE_SMOOTH);
newIconImage = new javax.swing.ImageIcon(scaledImage);
}
mod.addRow(new Object[]{xx, rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getString(11), rs.getString(12), rs.getString(13), rs.getString(14), rs.getString(15), rs.getString(16), rs.getString(17), rs.getString(18), rs.getString(19), rs.getString(20), rs.getString(21), rs.getString(22), rs.getString(23), newIconImage, rs.getString(25), rs.getString(26), rs.getString(27)});
xx++;
}
When i run the frame containing the below code ,instead of showing an Icon in the Image column "javax.swing.ImageIcon#119537a" is being shown in the image column . Pls help

You can try changing the column number where you set the image icon renderer.
I.e try 24 in
jTable1.getColumnModel().getColumn(25).setCellRenderer(jTable1.getDefaultRenderer(ImageIcon.class));
I suspect the renderer is not changed for the column where you added the image icon.

When i run the frame containing the below code ,instead of showing an
Icon in the Image column "javax.swing.ImageIcon#119537a" is being
shown in the image column .
I think that have to set proper ColumnClass for Icon/ImageIcons (in this case and only)
JTable knows Icon/ImageIcons data type in the ColumnClass, same as String, Number, Boolean and e.i.

I think you need to change the column number to 24 instead of 25.
jTable1.getColumnModel().getColumn(24).setCellRenderer(jTable1.getDefaultRenderer(ImageIcon.class));

Related

JAVA - GridLayout and JScrollPane behave unexpected

My GridLayout in Java behaving diffrently like I expected.
I want to have multiple Boxes within an JScrollPane (like in the screenshot below).
But when i have to less entries (for example 2) the height of the boxes are 100% height.
Does someone can tell me what i made wrong in my code?
ResultSet result = MysqlDataReader.ReadFromDataBase("DUMMY",connectionStrato);
innerPanel.removeAll();
innerPanel.setLayout(new GridLayout(Integer.parseInt(Math.round(result.getRow() / 3) + ""), 6, 2, 2));
while(result.next()){
URL url;
Image image;
try{
url = new URL("DUMMY" + result.getString(1) + ".jpg");
image = ImageIO.read(url.openStream());
} catch (MalformatedURLException ex) {
url = new URL("DUMMY");
image = ImageIO.read(url.openStream());
Logger.getLogger(ItemforList.class.getName()).log(Level.SEVERE, null, ex);
} catch(IOException ex){
url = new URL("DUMMY);
image = ImageIO.read(url.openStream());
Logger.getLogger(ItemforList.class.getName()).log(Level.SEVERE, null, ex);
}
ItemforList item = new ItemforList("DUMMY"+result.getString(1)+".jpg", result.getString(1)+"");
innerPanel.add(item)
}
scrollPaneL.setViewportView(innerPanel);
Component[] components = innerPanel.getComponents();
for (Component component : components){
if(component.getClass().equals(ItemforList.class)){
ItemforList item = (ItemforList) component;
System.out.printLn("TEST");
item.SetResizedIcon();
}
}
You didn't post any code so I can't comment on or directly fix that.
But to answer your question, the way to fix your problem is to fill in the extra grid boxes with dummy components - something just to take up that space

How to add CheckBox object in table in JAVA Swing

I am having a table which is getting data from database. But I want to add a row with checkbox having attributes as name But everytime I run the program it show the value as
javax.swing.JCheckBox[ , 0, 0, 0x0, invalid, alignmentX = 0.0, alignmentY = 0.5, border = java................
Here is the code.
while(rs.next()) {
Vector row = new Vector();
String name = rs.getString("name");
String catid = rs.getString("catalogid");
String brand = rs.getString("brand");
String counter = rs.getString("counter");
String qty = rs.getString("qty");
String price = rs.getString("column_price");
row.add(name);
row.add(catid);
row.add(brand);
row.add(counter);
row.add(qty);
row.add(price);
cb = new JCheckBox(name, true);
row.add(cb);
model.addRow(row);
}
You don't add components to the TableModel of a JTable. You add data and use renderers to render the data.
So in your case you need to:
add Boolean.TRUE as the data to the TableModel.
override the getColumnClass(...) method of the TableModel to return Boolean.class so the table can render the Boolean object as a check box.
Read the Swing tutorial on How to Use Tables for more information and examples to get you started.

JTable reverts to old cells when clicked on

This Code is in a While Loop, and each time I run a new Query it will go through this block after I have chosen what to filter it by, the problem is when I run it a second time and click on a cell in my table it will revert to cells in my previous table/query. I attached an image to show what I mean(I need 10 reputation for that so nevermind on the picture), I filtered the table by procsessState = -1 and when I clicked on some cells it reverted to what the previous table had. Help would be greatly appreciated. The program is around 1000 lines long and I did a terrible job of splitting it into different classes So I just posted where I am almost certain the issue arises.
I declared
final String columnNamesForTable[] = {"Error Message", "ID", "Locked By", "Message Id", "Process State",
"Row Date", "Sender", "Sent Date", "Subject" };
At The top, then I have this a bit later on.
else if (checkBoxCounter != 0)
{
DefaultTableModel tableModel = new DefaultTableModel(columnNamesForTable, 0);
tableModel.fireTableDataChanged();
try
{
Connection conn = DatabaseConnection.getConnection();
System.out.println("Connected");
PreparedStatement statement = conn.prepareStatement(sb.toString(),
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
// Change CONCUR_READ_ONLY to CONCUR_UPDATABLE
ResultSet resultSet = statement.executeQuery();
int errorMessageIndex = resultSet.findColumn("ErrorMessage");
int idIndex = resultSet.findColumn("Id");
int lockedByIndex = resultSet.findColumn("LockedBy");
int messageIdIndex = resultSet.findColumn("MessageId");
int processStateIndex = resultSet.findColumn("ProcessState");
int rowDateIndex = resultSet.findColumn("RowDate");
int senderIndex = resultSet.findColumn("Sender");
int sentDateIndex = resultSet.findColumn("SentDate");
int subjectIndex = resultSet.findColumn("Subject");
while (resultSet.next()) {
Object[] rowsForTable = { resultSet.getString(errorMessageIndex),
resultSet.getString(idIndex), resultSet.getString(lockedByIndex),
resultSet.getString(messageIdIndex), resultSet.getString(processStateIndex),
resultSet.getString(rowDateIndex), resultSet.getString(senderIndex),
resultSet.getString(sentDateIndex), resultSet.getString(subjectIndex)};
tableModel.addRow(rowsForTable);
}
resultSet.close();
statement.close();
conn.close();
filterFrame.setVisible(false);
JTable resultsTable = new JTable(tableModel);
JScrollPane pane = new JScrollPane(resultsTable);
displayPnl.add(pane);
pack();
resultsTable.repaint();
isDone= true;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Database error");
ex.printStackTrace();
isDone = true;
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Error loading database driver");
ex.printStackTrace();
isDone = true;
}
}
This Code is in a While Loop
Why would it be in a while loop. Swing is event driven. Code should only be executed when the uses generates some kind of event like clicking on a button, typing text, editing a cell.
I have chosen what to filter it by,
Don't create a whole new table and scroll pane. Just update the TableModel of the existing JTable.
pack();
Why would you pack the frame. The query could have 100's of rows of data. Pick a reasonable size for the table when the frame is created and there is no need to use pack() or repaint(). When you invoke the setModel(...) method of the JTable to replace the current model the table will be repainted automatically.
So all the code you need should be:
//filterFrame.setVisible(false);
//JTable resultsTable = new JTable(tableModel);
//JScrollPane pane = new JScrollPane(resultsTable);
//displayPnl.add(pane);
//pack();
//resultsTable.repaint();
existingTable.setModel( tableModel );
I cant comment I do not have enough reputation.
You fire tabledatachanged before changing data.
TableDataChanged does not always properly update rows , it seems better to fire update rows.
If your table is editable , if you clicked the table you need to release the editor.

How to display database values in JFreeChart linechart

I have a question about a JFreeChart issue. I want to display a chart with a line from the values out of my database. This is the code I have now:
public void drawachart(){
try{
String sql= "select status,date from luggage";
JDBCCategoryDataset dataset = new JDBCCategoryDataset(
"jdbc:mysql://localhost/corendon", "com.mysql.jdbc.Driver", "root", "root");
dataset.executeQuery(sql);
JFreeChart chart = ChartFactory.createLineChart("chart","date", "status",
dataset,PlotOrientation.VERTICAL,false,true,true);
BarRenderer bar= null;
bar = new BarRenderer();
CategoryPlot plot =null;
ChartFrame frame = new ChartFrame("shart", chart);
frame.setVisible(true);
frame.setSize(500, 500);
}
catch(Exception e){
e.printStackTrace();
}
}
After executing the code, it gives me a chart with no lines in it. Only a x and y axis. What should I do to get a line in the chart.
Try JDBCXYDataset, mentioned here. Because "the first column will be the x-axis," change your query to "select date, status from luggage". JDBCXYDataset can detect a time series based on metadata, so ChartFactory.createTimeSeriesChart() may be a suitable choice.

JasperReportBuilder HTML row height

I am building a report with JasperReportBuilder from a JDBC data source and afterward I export it to HTML by calling the toHtml method with a JasperHtmlExporterBuilder object parameter. I have been trying to get rid of extra space that exists above the text in each of my rows, column header row, and even my title. I have tried everything I can think of and have been searching online to no avail.
It seems most people have the opposite problem: they need to grow their rows to fit their text. I would like to force my rows to be the height of their contents. If that's not possible, I would be happy with restricting the height of my rows.
The HTML exporter appears to be controlling the height of my rows by inserting an image and setting its height.
Any help would be appreciated. Thanks!
Edit: Here is my code.
String imageServletUrl = "images?image=";
StringWriter writer = new StringWriter();
JasperHtmlExporterBuilder htmlExporter = Exporters.htmlExporter(writer);
htmlExporter.setImagesURI(imageServletUrl);
SqlRowSet rowSet = getData(databaseIpAddr, portNumber, databaseName, databaseUser, databasePassword);
JRDataSource ds = createDataSource(rowSet);
JasperReportBuilder builder = DynamicReports.report();
IntegerType intType = DynamicReports.type.integerType();
DateType dateType = DynamicReports.type.dateType();
int rowHeightPx = 20;
TextColumnBuilder<Integer> col1 = col
.column(COL_TITLE_RESULT_NUM, RESULTS_COL_TITLE_RESULT_NUM, intType)
.setWidth(35)
.setFixedHeight(rowHeightPx)
.setStretchWithOverflow(true);
... create other eight columns ...
StyleBuilder titleStyle = stl.style()
.bold()
.setFontSize(22)
.setHorizontalAlignment(HorizontalAlignment.CENTER);
StyleBuilder columnTitleStyle = stl.style()
.bold()
.setAlignment(HorizontalAlignment.CENTER, VerticalAlignment.MIDDLE)
.setBorder(stl.pen1Point());
StyleBuilder columnStyle = stl.style()
.setAlignment(HorizontalAlignment.CENTER, VerticalAlignment.MIDDLE)
.setLineSpacing(LineSpacing.SINGLE)
.setBorder(stl.pen1Point());
TextFieldBuilder<String> titleBuilder = DynamicReports.cmp
.text(selectedAgency)
.setStyle(titleStyle)
.setFixedHeight(20);
TextFieldBuilder<String> subtitleBuilder = DynamicReports.cmp
.text("Start Time: " + startDate + " " + getStartTime() + ", End Time: " + endDate + " " + getEndTime())
.setFixedHeight(20);
TextFieldBuilder<String> noDataMsgBuilder = DynamicReports.cmp
.text(NO_DATA_MSG)
.setStyle(columnStyle);
builder
.title(titleBuilder)
.addPageHeader(subtitleBuilder)
.setColumnTitleStyle(columnTitleStyle)
.columns(col1, col2, col3, col4, col5, col6, col7, col8, col9)
.setColumnStyle(columnStyle)
.highlightDetailOddRows()
.noData(titleBuilder, subtitleBuilder, noDataMsgBuilder)
.setWhenNoDataType(WhenNoDataType.NO_DATA_SECTION);
String reportHtml;
try {
// this seems to be required to get to the DynamicReports images
getContext().getRequest().getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, builder.toJasperPrint());
builder.toHtml(htmlExporter);
reportHtml = writer.toString();
}
catch (DRException e)
{
e.printStackTrace();
reportHtml = "There was an error generating the report";
}
Edit: Below solution works fine only with DynamicJasper library rather than DynamicReports. There must be similar operations in DR API as well i believe (not sure though - my exposure with DR is only very limitted :().
A combination of DynamicReportBuilder::setHeaderHeight(..), setDetailHeight(..) and JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN parameter setting must do it?
// build dynamicreport instance
DynamicReportBuilder dynamicReportBuilder = new DynamicReportBuilder();
dynamicReportBuilder.setHeaderHeight(50); //sets the column header height
dynamicReportBuilder.setDetailHeight(50); //sets the detail band rows height
DynamicReport dynamicReport = dynamicReportBuilder.build();
// build jasperprint..
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(
dynamicReport, new ClassicLayoutManager(), dataSource, new HashMap<String, Object>());
// export as html
JRExporter exporter = new JRHtmlExporter();
// tell jasper not to use images for aligning
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, targetFile);
exporter.exportReport();
adapt reports band heigts to heigth of your row for each band, make sure that you dont have any emty spaces between your rows. If you want to have "emty row" create an emty text field with width of the corresponding band. Think about the report as about grid.

Categories