我创建了一个带有JTable
的文件上传对话框:
每次用户上传另一个文件时,JTable
都会添加另一行,其中包含文档大小和一个图标,以触发特定行的操作。
由于单元格中的图标通常有一些空间,因此用户无需单击图标上的完全,单击单元格即可触发图标 - 动作。
我担心,我的用户可能会“点击”,即想要使列更大,点击标题附近并在第一个文档上触发图标操作而不会注意到。
那么,我是否只能使图标可点击而不是单元格本身?
我的示例与mKorbel编写的示例非常相似,因此如果您要测试代码,可以将其用作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();
}
});
}
}