Dynamically add images to JTable cells - java

I am dynamically adding data to a cell with the following code:
for(int i = 0; i < matchedSlots.size(); i++)
{
String title = matchedSlots.get(i).getTitle();
String director = matchedSlots.get(i).getDirector();
int rating = matchedSlots.get(i).getRating();
int runTime = matchedSlots.get(i).getRunningTime();
DefaultTableModel tm = (DefaultTableModel) searchResults.getModel();
tm.addRow(new Object[] {title,director,rating,runTime});
}
what do I need to add to the above to be able to add an image in the first cell of each row

By default JTable can render Images. You just need to override getColumnClass() in the TableModel and return Icon.class for 1st column.
Look at Renderers and Editors for more details.

ImageIcon image = new ImageIcon("image.gif");
...
tm.addRow(new Object[] {image,title,director,rating,runTime});
You may need to change your table model to account for the new column if you haven't already.
This short article should help you with the image renderer: http://mdsaputra.wordpress.com/2011/06/13/swing-hack-show-image-in-jtable/

Related

JTable Reverts JComboBox and JCheckBox to Values after Selection

I have a JTable with a column of JComboBox<Integer>s and a column of JCheckBoxs. The JTable is set with the appropriate renderers and editors. The table looks fine at first, but after selecting a value from the combobox or checkbox, the cells seem to revert to the values of Integer and Boolean. The issue appears to be more than cosmetic, as methods that anticipate the cell having a combobox or a checkbox throw errors at finding an Integer or a Boolean.
Here is a picture of what it looks like:
And here is the code:
dataTable.removeAll();
numberOfVariables = 7;
Object[] header = new Object[numberOfVariables];
header[0] = new String("Ring Number");
header[1] = new String("Radius (cm)");
header[2] = new String("Plume Distribution");
header[3] = new String("Thickness (A)");
header[4] = new String("Deposition Time (s)");
header[5] = new String("Rate (A/s)");
header[6] = new String("Optimize (y/n)");
Object[][] data = new Object[numberOfRings][numberOfVariables];
for(int k=0;k<numberOfRings;++k){
Object[] row = new Object[numberOfVariables];
row[0] = Integer.toString(k+1);
row[1] = String.format("%.2f", plume.getRingRadius(k));
row[2] = createDistributionComboBoxForRing(k);
row[3] = String.format("%.2f", plume.getThicknessOfRing(k));
row[4] = String.format("%.2f", plume.getTimeForRing(k));
row[5] = String.format("%.2f", plume.getRateForRing(k));
row[6] = new JCheckBox();
((JCheckBox) row[6]).setSelected(true);
data[k] = row;
}
tableModel = new DefaultTableModel(data,header);
dataTable.setModel(tableModel);
dataTable.getColumnModel().getColumn(2).setCellRenderer(new ControlTableRenderer());
//dataTable.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor( createDistributionComboBoxForRing(0) ));
dataTable.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor( (JComboBox<Integer>) data[0][2] ));
dataTable.getColumnModel().getColumn(6).setCellRenderer(new ControlTableRenderer());
dataTable.getColumnModel().getColumn(6).setCellEditor(new DefaultCellEditor( (JCheckBox) data[0][6] ));
dataTable.updateUI();
row[2] = createDistributionComboBoxForRing(k);
row[3] = String.format("%.2f", plume.getThicknessOfRing(k));
row[4] = String.format("%.2f", plume.getTimeForRing(k));
row[5] = String.format("%.2f", plume.getRateForRing(k));
row[6] = new JCheckBox();
((JCheckBox) row[6]).setSelected(true);
The TableModel for a JTable stores data, not components.
So if column 3 contains an Integer object then you store an Integer in the TableModel and you set the editor for the column to be a combo box containing the list of valid Integers.
Same for the column containing the check box renderer/editor. In this case you store a Boolean object.
For example:
row[2] = new Integer(1);
row[6] = Boolean.TRUE
Now in the TableModel you need to tell the table what type of data is in each column so you need to override the getColumnClass(...) method. Something like:
tableModel = new DefaultTableModel(data,header)
{
#Override
public Class getColumnClass(int column)
{
switch (column)
{
case 2: return Integer.class;
case 6: return Boolean.class;
default: return Object.class;
}
}
};
Now the table can choose the appropriate renderer and editor for each column.
However, in the case of the combo box you do have to create a custom editor with the values for the combo box. See the section from the Swing tutorial on Using a Combo Box as an Editor for a working example on how to do this.
Also, you are incorrectly using some other methods:
dataTable.removeAll();
Not sure what that is for. That is a Container method to remove components from the panel. All you need is the setModel(...) statement to reset the table.
dataTable.updateUI();
There is no need to use the updateUI() method. That method is used internally when the LAF is changed. You are not changing the LAF so get rid of that statement.
The idea of cell renderers and editors is that you only have one component and that gets moved around and data changed for each row. The code uses a different JComponent instance for each cell. Just put the data in the table model and let the cell renderer and editors manage the components.

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.

Send 2D Array to JTable

I am using swing and java in Eclipse to send data to JTable from a 2D Array
String [][] row = {{"iphone"},{"34567"}};
I have a 2D array. I am wanting to display it in JTable using eclipse.
The JTable will have to header like "Phone" and "Price" and the Jtable gets filled by the click of a button.
String[] columns = {"Phone","Price"};
Can some please help me to get it displayed in JTable
DefaultTableModel model = new DefaultTableModel(new Object[]{"Column1", "Column2"})
JTable table = new JTable(model);
To add a row:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(new Object[]{"iPhone", "73567",});
Placing the above code inside the action performed of the button.
public void actionPerformed(ActionEvent e)
{
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(new Object[]{"iphone", "73576"});
}

How do I dynamically display contents in tables in Java

I need to display some content in a tabular form dynamically in Java. The content includes data that is fetched from an API in JSON format. At the end of each row I need to display a checkbox as well. The number of rows is dynamic and the columns are fixed. How do I do this?
The table will have the following columns:
Index
Username
Upload date
Percentage
Matched results
[Checkbox]
Finally found the answer to this problem. We can dynamically create a table using the class DefaultTableModel and the Java swing class JTable.
model = new DefaultTableModel();
Set the columns
model.setColumnIdentifiers(new Object[]{"Index","User","Reg no.","Match"});
jTable1.setModel(model);
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
jTable1.setFillsViewportHeight(true);
jScrollPane1.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jScrollPane1.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
Add the rows from the JSON response
for(int i=0;i< jsonArr.size();i++)
{
str = jsonArr.get(i).toString();
jsonObj = (JSONObject)parser.parse(str);
String sub = jsonObj.get("subid").toString();
String uname = jsonObj.get("username").toString();
String regno = jsonObj.get("regno").toString();
String percent = jsonObj.get("percent").toString();
model.addRow(new Object[]{sub,uname,regno,percent});
}

How to get the contains of file in jtable?

I create a jtable like this :
String name = temp.getName();
String enemy = namaFileUtama.toString();
DefaultTableModel models = (DefaultTableModel) Main_Menu.jTable4.getModel();
List<ReportMomentOfTruth> theListRMOT = new ArrayList<ReportMomentOfTruth>();
ReportMomentOfTruth rmot = new ReportMomentOfTruth();
rmot.setNameOfMainFile(name);
rmot.setNameOfComparingFile(enemy);
theListRMOT.add(rmot);
for (ReportMomentOfTruth reportMomentOfTruth : theListRMOT) {
models.addRow(new Object[]{
reportMomentOfTruth.getNamaFileUtama(),
reportMomentOfTruth.getNamaFilePembanding(),
});
}
You know, I dont get an idea. How can I get the contains the file if I click one row in jtable then the contains will be show in jTextArea ? Any suggestion ? any example perhaps ?
Thanks
edit
You know, I am using netbeans, I can get a method like this
private void jTable4MouseClicked(java.awt.event.MouseEvent evt) {
if (evt.getClickCount() == 1) {
}
}
Now how to ?
How can I get the contains the file if I click one row in jtable then the contains will be show in jTextArea?
You can better use JEditorPane that has a method setPage() that can be used to initialize the component from a URL.
Just get the values of selected row and use below code to set the content in JEditorPane.
sample code:
final JEditorPane document = new JEditorPane();
document.setPage(new File(".../a.java").toURI().toURL());
Add ListSelectionListener to detect the selection change event in the JTable
final JTable jTable = new JTable();
jTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int row = jTable.getSelectedRow();
if(row != -1){
String firstColumnValue = jTable.getModel().getValueAt(row, 0).toString();
String secondColumnValue = jTable.getModel().getValueAt(row, 1).toString();
// load the JEditorPane
}
}
});;
Read more...

Categories