I have created an file-upload dialog with a JTable
:
Every time the user uploads another file, the JTable
adds another row with the size of the document and an icon to trigger an action for the specific row.
Since usually there is a bit of space left and right to the icon in the cell, the user does not have to click exactly on the icon, clicking the cell is sufficient to trigger the icon-action.
I fear, that my users might "click around" i.e. wanting to make the column bigger, clicking near the header and triggering the icon-action on the first document without noticing.
So, can I make only the icon clickable and not the cell itself?
My example is very similar to one that mKorbel has written, so if you want to test the code, you can use this as an MCVE:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JFrame {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame ();
private JTable table;
private JLabel myLabel = new JLabel("waiting");
private int pHeight = 40;
private ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
private ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
private ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
private ImageIcon questIcon = (ImageIcon) UIManager.getIcon("OptionPane.questionIcon");
public TableIcon() {
String[] columnNames = {"Picture", "Description"};
Object[][] data = {{errorIcon, "About"}, {errorIcon, "Add"}, {errorIcon, "Copy"}, {errorIcon, "Copy"}};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);
JLabel jc = (JLabel) comp;
if (column == 0) {
if (isRowSelected(row) && isColumnSelected(column)) {
jc.setIcon(infoIcon);
} else if (isRowSelected(row) && !isColumnSelected(column)) {
jc.setIcon(warnIcon);
} else {
jc.setIcon(jc.getIcon());
}
}
return comp;
}
};
table.setRowHeight(pHeight);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
myLabel.setPreferredSize(new Dimension(200, pHeight));
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
frame.add(myLabel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocation(150, 150);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableIcon frame = new TableIcon();
}
});
}
}