String path displayed when adding Image in JTable - java

I tried using setValueAt in adding an image but the problem is it prints the string and does not load the image. any help on this. the code is below
int selectedColumn = table1.getSelectedColumn();
int selectedRow = table1.getSelectedRow();
ImageIcon addIcon = new ImageIcon("c:\\onion.png");
table1.getModel().setValueAt(addIcon, selectedRow, electedColumn);

You need to create a table model which returns Icon.class for its getColumnClass method.

Ensure that your table knows what data is stored in a given column so it can choose the appropriate renderer. So, your JTable creation code should be something like this:
DefaultTableModel tableModel = new DefaultTableModel(dataObject, columnNames);
JTable table = new JTable(tableModel){
public Class getColumnClass(int column){
return getValueAt(0, column).getClass();
}
};

Related

Dynamically adding JTable header color/text

My project involves a JTable and GUI. The user populates the JTable by adding "transactions" (represented as a row) and can then copy or delete these "transactions" at will.
I have decided that I want to add some more color to the table. In particular I would like to have every other header and column have a black background with white text so that it is easy to view.
I have been able to write the code to accomplish with the columns. I have also been able to change the color of ALL column headers. The problem that I seem to be having is changing individual column headers dynamically (like I do the columns). I have referred to the question here: JTable header background color but am very confused by it.. The solution posted is quite complicated and I am having trouble translating it to my individual code. Here is what I have so far:
tbl = new JTable();
String header[] = new String[]{
"Notification Reference Number", "Amount","Credit/Debit Indicator","Initiating Party Id",
"Initiating Party Scheme Name", "Debtor Name","Debtor Zip Code","Debtor Town",
"Debtor Country Sub-Division","Debtor Address","Debtor Agent Clearing System Id","Debtor Agent Name",
"Creditor Agent Clearing System Id",
"Creditor Agent Name",
"Return/Reject Code","Return/Reject Additional Info",
"Payment Instrument","Type of Payment","Pass-Thru Data","Clearing Account","Transaction Type",
"Return Occurence","Retired Indicator","Representment Method",
"Check-Split Indicator","Check Split Amount","Corporate Check Indicator","Source Batch Identifier"
};
dtm.setColumnIdentifiers(header);
tbl.setModel(dtm);
tbl.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scroll = new JScrollPane(tbl);
scroll.getViewport().setBackground(Color.gray);
boolean flag = false;
for(int i = 0; i < header.length; i++){
tbl.getColumnModel().getColumn(i).setPreferredWidth(200);
if(flag==false){
TableColumn tm = tbl.getColumnModel().getColumn(i);
tm.setCellRenderer(new ColorColumnRenderer(Color.black,Color.white));
flag=true;
}else if(flag==true){
TableColumn tm = tbl.getColumnModel().getColumn(i);
tm.setCellRenderer(new ColorColumnRenderer(Color.white, Color.black));
flag=false;
}
}
As you can see I use the "flag" Boolean to ensure that every other column is changed. Here is the code for changing the columns:
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
// TODO Auto-generated method stub
return null;
}
}
class ColorColumnRenderer extends DefaultTableCellRenderer{
Color bkgndColor, fgndColor;
public ColorColumnRenderer(Color bkgnd, Color foregnd){
super();
bkgndColor = bkgnd;
fgndColor = foregnd;
}
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
Component cell = super.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, column);
cell.setBackground(bkgndColor);
cell.setForeground(fgndColor);
return cell;
}
}
During experimenting I was able to set all headers with this:
tbl.getTableHeader().setOpaque(false);
tbl.getTableHeader().setBackground(Color.black);
tbl.getTableHeader().setForeground(Color.white);
I have tried numerous methods of coding a specific header but all are unsuccessful. I'm sure the solution is simple I just can't figure it out.
I should note that I apologize for not posting a full code example. This code is actually quite complex so I was hoping someone might be able to easily identify what I need to do before I have to create new JTable and try to isolate this example - Although I will do this if necessary.

How to add rows on a JTable using AbstractTableModel?

I have a JTable with my own Model (extends AbstractTableModel), and I'd like to add a row to it when I Click a JButton.
I don't really know how to hadd the row to the Model.
here is my model:
public class MembersModel extends AbstractTableModel {
String[] columnNames = {
"Name",
"Money Spent",
"Percent",
"Current Deck"
};
Object[][] data = {
{"Cajo", new Integer(150), new Integer(0), "Event Deck"},
{"Sekiam", new Integer(200), new Integer(0), "Jeskay"},
{"Nuvas", new Integer(100), new Integer(0), "Big Shit"},
{"Dos", new Integer(100), new Integer(0), "Crap Deck"},
{"Atoj", new Integer(100), new Integer(0), "IDK"}
};
public MembersModel(){
super();
calcAllPercent();
}
public void calcAllPercent(){
for(int i = 0; i < data.length; ++i){
data[i][2] = calcPercetage((Integer) data[i][1]);
}
}
private int calcPercetage(int money){
return (money*100)/teamMoneySpent();
}
private int teamMoneySpent(){
int money = 0;
for(int i = 0; i < data.length; ++i){
money += (Integer) data[i][1];
}
return money;
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
return false;
}
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
calcAllPercent();
fireTableRowsUpdated(0, 4);
}
}
Should i create my table aswell or add the method to the Model?
The key will be the data nucleus that you're using for your model, which here is your 2-D array, Object[][] data. The question then boils down to this: how do you add another row to the array and then notify the model's listener of the addition. While this can be done by creating a new data array with another row, copying all the data from this array, and adding the new data to the newly added row, why bother? For my money I'd
create a class to hold the data of a single table row, here I'll call it MyType, but you'll give it a better name, and it will have String, int, int, and String fields to correspond to the columns of your table.
Give this class some of the methods you have in your model above, such as doing row-specific calculations, calcPercentage(..), teamMoneySpent(...), and then the model can call the row object's method when this information is needed.
use an ArrayList<MyType> as my table model data nucleus, not a 2-dimensional hard-coded array.
give my model class an addRow(MyType myObj) method
in the method add to the ArrayList
and then call the appropriate model notification method, which here would be fireTableRowsInserted(...).
Note, I'm not sure what you mean by,
Should i create my table aswell or add the method to the Model?
Some problems with your current model:
The setValueAt() method is wrong. You should invoking tableCellUpdated(...). You don't want to repaint the data in the entire table when you update a single cell. Actually you don't even need to implement the setValueAt(...) method because your table is not editable.
You didn't override the getColumnClass(...) method. This method is required so the table can use the proper renderer to display the data.
Instead of creating a completely new TableModel, you could extend the DefaultTableModel. It already supports an addRow(...) method.
However, as hovercraft has already pointed out a better design is create a custom Object to store all the data of a single row. For a solution that uses this approach check out Row Table Model for a solution. The base TableModel is more complicated, but it makes it easier to create custom TableModels in the future since all the common code is in one class.
I would implement hovercraft's suggestion first so you better understand the concepts of creating a TableModel with a custom Object. I include this link as a suggestion for the future.

JXTable - how to update highlighters on sorting the table

I have a JXTable with custom table model. I added 2 ColorHighlighter's with custom HighlightPredicate's.
Problem is when i click on the column header, the table sorts the rows, BUT the highlighter's remain as for the old view.
How can I update the state of the highlight after sorting a table?
As #kleopatra mentioned, i looked at my predicate:
HighlightPredicate spakowany = new HighlightPredicate() {
#Override
public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
TableModel tableModel = table.getModel();
if (tableModel instanceof StanTableModel) {
StanTableModel stanTableModel = (StanTableModel) tableModel;
// int rowIndex = adapter.row; <- this was the issue
int rowIndex = adapter.convertRowIndexToModel(adapter.row);
StanTableRow myCustomRow = stanTableModel.getRow(rowIndex);
if ((myCustomRow.isSpakowany()) {
return true;
}
}
return false;
}
};
and used #mKorbel idea:
was:
int rowIndex = adapter.row;
is now:
int rowIndex = adapter.convertRowIndexToModel(adapter.row);
And it works now.
StanTableModel is my custom table model. It has getRow() function and returns a StanTableRow object which in turn has isSpakowany() function.

DefaultTableModel make cell not editable JTable [duplicate]

This question already has answers here:
How to make a JTable non-editable
(7 answers)
Closed 6 years ago.
I have an JAVA project and want to make my JTable with a DefaultTableModel non-editable. I know a work-around to do this, called:
JTable table = new JTable(...){
public boolean isCellEditable(int row, int column){
return false;
}
};
Like said: i dont like this. This is not according the rules of my school training.
Is there any way to do this? Maybe is there a good way. I hope so!
You should not subclass the JTable itself, but the table model:
DefaultTableModel myModel = new DefaultTableModel(...) {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
Or even better, don't use a DefaultTableModel, and use an AbstractTableModel that directly gets the information in your business objects rather than copying all the information from the business objects to Vectors.
select Jtable , and don't forget to create table model (DefaultTableModel TableModel)
JTable table_1 = new JTable (TableModel){public boolean isCellEditable(int row,int column)
{switch(column){
case 4: // select the cell you want make it not editable
return false;
default: return true;}
}};

How to add a tooltip to a cell in a jtable?

I have a table where each row represents a picture. In the column Path I store its absolute path. The string being kinda long, I would like that when I hover the mouse over the specific cell, a tooltip should pop-up next to the mouse containing the information from the cell.
Just use below code while creation of JTable object.
JTable auditTable = new JTable(){
//Implement table cell tool tips.
public String getToolTipText(MouseEvent e) {
String tip = null;
java.awt.Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
try {
tip = getValueAt(rowIndex, colIndex).toString();
} catch (RuntimeException e1) {
//catch null pointer exception if mouse is over an empty line
}
return tip;
}
};
I assume you didn't write a custom CellRenderer for the path but just use the DefaultTableCellRenderer. You should subclass the DefaultTableCellRenderer and set the tooltip in the getTableCellRendererComponent. Then set the renderer for the column.
class PathCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel c = (JLabel)super.getTableCellRendererComponent( /* params from above (table, value, isSelected, hasFocus, row, column) */ );
// This...
String pathValue = <getYourPathValue>; // Could be value.toString()
c.setToolTipText(pathValue);
// ...OR this probably works in your case:
c.setToolTipText(c.getText());
return c;
}
}
...
pathColumn.setCellRenderer(new PathCellRenderer()); // If your path is of specific class (e.g. java.io.File) you could set the renderer for that type
...
Oracle JTable tutorial on tooltips
You say you store an absolute path in a cell. You are probably using a JLabel for setting absolute path string. Suppose you have a label in your cell, use html tags for expressing tooltip content:
JLabel label = new JLabel("Bla bla");
label.setToolTipText("<html><p>information about cell</p></html>");
setToolTipText() can be used for some other Swing components if you are using something other than JLabel.

Categories