add an image from Database into JTable - java

i am trying to add an image that is in my database in a column in JTable
with a number and a code special to this image the problem is i got the number and the code but the image doesn't show i don't know why here is my code
String sql="SELECT id,chiffre,image FROM symbolique WHERE id BETWEEN 200 and 205";
try{
st=connexion.prepareStatement(sql);
res=st.executeQuery();
while(res.next()){
int j=0;
String [] code= new String[1000];
String [] chiffre1=new String[100];
code [j] = res.getString("id");
chiffre1[j] = Integer.toString(res.getInt("chiffre"));
Blob blob = res.getBlob("image");
is2 = new BufferedInputStream(blob.getBinaryStream());
Image raw = ImageIO.read(is2);
ImageIcon icon =new ImageIcon(raw);
Object [][] data = new Object[200][100];
data[j][1]= code [j];
data[j][2]= chiffre1[j];
data[j][3]=icon;
j++;
String title[] = {"image", "chiffre","code"};
DefaultTableModel model = new DefaultTableModel(data, title);
table.setModel(model);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);}
}

put Icon/ImageIcon to JTable better to the TableModel directly
you have to override getColumnClass for Icon/ImageIcon in XxxTableModel for showing this Object as image in the JTables view
for detailed informations (incl. working code examples) to read official Oracle tutorial - How to use Tables

This won't help solve the image problem but right now your code recreates the TableModel for every row in the ResultSet, which means you will only ever see one row of data.
Since you have looping code you need to create an empty DefaultTableModel before the loop starts.
Inside the loop you then use the addRow(...) method to add another row of data to the TableModel for every row in the ResultSet
When you finish the loop then you use the model to create the JTable.
Did you add any debug code? Did you attempt to display the width/height of the image to confirm that you are reading the image properly? Why don't you do a simple test that tries to read and display an image in a JLabel first since using a JTable is more complicated than using a JLabel. Then once you get that working you can apply the knowledge to using a JTable.

Related

Add jcheckbox in jtable [duplicate]

This question already has answers here:
How to add JCheckBox in JTable?
(2 answers)
Closed 3 years ago.
I am currently working on an attendance system where I'll use jTable and add jCheckbox in it. However, I have no idea how to do this.
What should I do to add jCheckBox in my jTable. The data in my jTable is acquired from a database.
I have tried using this code but the table doesn't show the data from my database and still doesn't have a checkbox on it.
public void Update_table(int Column, int ColumnBoolean, DefaultTableModel model) {
try {
String sql = "select * from student_info";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
Attendance.setModel(DbUtils.resultSetToTableModel(rs));
Object[] files = new Object[Column];
while (rs.next()) {
for (int i = 1; i <= Column; i++) {
if (i == ColumnBoolean) {
files[ColumnBoolean - 1] = Boolean.FALSE;
} else {
files[i - 1] = rs.getObject(i - 1);
}
model.addRow(files);
}
Attendance.updateUI();
rs.close();
}
JCheckBox check = new JCheckBox();
Attendance.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(check));
Attendance.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer());
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
First of all you have all kinds of issues with the posted code:
Variable names should NOT start with an upper case character. Some are correct, other are not. Be consistent and follow Java conventions
Method names should NOT start with an upper case character. Again follow Java conventions.
Why are you passing a "DefaultTableModel" as a parameter to the method. You never use that variable. Get rid of the parameter if it is not needed!
There is no need to invoke updateUI(). The method is invoked internally on a Look and Feel change. The JTable will repaint itself when the model is added to the table.
Did you debug your while loop? I don't believe it will work. When using the DBUtils it will loop through the ResultSet to add the data to the TableModel. So when you execute that code you are already at the end of the ResultSet.
In any case I don't understand what you are attempting to do with the loop. All the data has already been added to the TableModel. I don't know why you would attempt to add more rows.
but the table doesn't show the data from my database
Well that is your first step. Display the data from the database and forget about the custom renderer/editor. Solve one problem at a time.
Once you get the data displayed, there is still no reason to use a custom renderer/editor because Swing already provides defaults. The problem is that you need to override the getColumnClass(...) method of your JTable to return the Class of each column so the table can choose the apppriate renderer/editor for the column.
For an example of how to do this see: Java, changing boolean column to checkbox in jTable when using rs2xml for populating jTable

How to load or refresh jTable's data everytime I add new data to ArrayList Object [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Load/refresh jTable everytime I inserted new set of data to arrayList
Already tried those lines I've put on comments but still nothing changed. Consider that adding of those data to arrayList are performed in separate class.So here, Action performed in a jButton so everytime I add set of data from jTextfields and stores it as Object to arrayList, only the first set of columns and rows I inserted to the arrayList are the only displayed data in jTable. Although the second set of data I inserted after clicking the jButton twice was saved to arrayList, the jTable didn't even refresh or load the new data I inserted. Any help will be appreciated
//BUTTON ACTION PERFORMED
DefaultTableModel tableModel = (DefaultTableModel) MyJTable.getModel();
tableModel.fireTableDataChanged();
//tableModel.setRowCount(0);
//tableModel.repaint();
//int rowCount = tableModel.getRowCount();
//for(int i = rowCount -1; i >= 0; i--){
//tableModel.removeRow(i);
//}
Object[][] displayOnTable = new Object[Data.data.size()][4];
for(int x=0; x < Data.data.size(); x++){
displayOnTable[x] = Data.data.get(x);
}
MyJTable.setModel(new javax.swing.table.DefaultTableModel(
disp,
new String [] {
"ID", "Name", "Gender", "Age"
} ));
// --- Declared in Separated class----
//public class Data {
// public static List<Object[]> data = new ArrayList<>();
// }
// ------------------------
Already tried those lines I've put on comments but still nothing changed.
Well start with something really simple.
Add two lines to your ActionListener:
DefaultTableModel tableModel = (DefaultTableModel) MyJTable.getModel();
tableModel.setRowCount(0);
If nothing happens to the data in the table, then it means you don't have a reference to the table that is visible on the frame. So you need to solve this problem.
Did the data in the table clear? If so this is a good sign as it means your code is referencing the TableModel of the JTable that has been added to the frame.
So now you can add data from the ArrayList.
The basic logic would be:
System.out.println( data.size() ); // to verify you actually have data in the List
for (Object[] row: data)
model.addRow( row );
That's it. No need to create a new TableModel. No need to create a 2D array. You will simply iterate through the ArrayList adding one row of data at a time to the model. Then the table will automatically repaint() itself.
Of course this will only work if you have data in the ArrayList.

How to add row of data to Jtable from values received from jtextfield and comboboxes

I have a JFrame Form which has JTextFields, JCombobox etc. and I am able to receive those values to variables and now I want to add the received data to JTable in new row when user clicks Add or something like that.
I have created JTable using net-beans the problem is what would be the code to add data from those variable to the rows of table. A basic example would be appreciated. I have tried numerous example and have added the code to ActionListener of the JButton but nothing Happens.
The Examples I tried are. How to add row in JTable? and How to add rows to JTable with AbstractTableModel method?
Any Help would be appreciated.
Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder
Set the table column headers
Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
Click on the ... button to the right of the property model. A dialog should appear.
Set rows to 0, set the number of columns you want, and their names.
Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row
Right-click on the button and select Events -> Action -> actionPerformed
You should see code like the following auto-generated
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
The jTable1 will have a DefaultTableModel. You can add rows to the model with your data
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
String data1 = something1.getSomething();
String data2 = something2.getSomething();
String data3 = something3.getSomething();
String data4 = something4.getSomething();
Object[] row = { data1, data2, data3, data4 };
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
// clear the entries.
}
So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.
you can use this code as template please customize it as per your requirement.
DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();
list.add(textField.getText());
list.add(comboBox.getSelectedItem());
model.addRow(list.toArray());
table.setModel(model);
here DefaultTableModel is used to add rows in JTable,
you can get more info here.
String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);
Here;this is the solution.

Java - Arraylist contents to display in Jtable

I am working on a project and I am stuck on this area. I am reading text from a file and I am saving it into an arraylist. the problem is the content from the file appears in one line of text in the jtable but i want each line to be displayed in rows. I am passing the data from another class and I know this is working because I can see the contents printed out in the console row after row . I have tried a few different ways but I've run out of ideas. Any help appreciated.
Below is the code I have wrote.
for (String item : helper.getItems() )
{
System.out.println(item);
storage.add(item);
}
JTable t1 = new JTable();
t1.setModel(new DefaultTableModel(
new Object[][]{
{storage.toString()}
},
new String[]{
"Tool Equipment"
}
));
storage.toString() will give you string representation of your ArrayList. What you want is probably List#toArray
The best way to add items to a JTable using the DefaultTableModel object is to utilize the .addRow method of the DefaulTableModel. You'll need to parse the storage string to deliminate the values you want placed into each row/col
For Example:
DefaultTableModel model=new DefaultTableModel();
// parsing of the storage obj, to get individual values for each col/row
// depending on the structure of storage a looping construct would be beneficial here
String col1= storage.substring(startindex, endindex);
String col2=storage.substring(startindex, endindex);
//add items to the model in a new row
model.addRow(new Object[] {col1, col2});
// if you used a loop to parse the data in storage, end it here
// add model to the table
t1.setModel(model);

Increase row count in a JTable

I'm developing an address book for my classmates but I'm having a problem with a JTable. Here you can see a preview of the program, I'm using NetBeans [click]. If you click Add to the Address Book, the program adds a new row in that table and fills its cells with the data located in text fields below. I'm using the following code but the row count doesn't increase.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
int h;
DefaultTableModel model = new DefaultTableModel();
h=jTable1.getRowCount()+1;
model.setRowCount(h);
jTable1.setValueAt(jTextField2.getText(), h, 1);
jTable1.setValueAt(jTextField3.getText(), h, 2);
//I'll use more setValueAt() because I must fill all the cells
}
Could you give me some advice as to how to fix this problem?
You created a new model. You should take the model that is assigned to the table.
DefaultTableModel model = new DefaultTableModel();
should be:
DefaultTableModel model = jTable1.getModel();

Categories

Resources