1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public static void main(String[] args) {
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] columnNames = {"Label","Path"};
Object[][] rowData = new Object[10][columnNames.length];
for(int i=0; i<rowData.length; i++) {
rowData[i][0] = ThreadLocalRandom.current().nextInt(10, 50);
rowData[i][1] = createFakePath(ThreadLocalRandom.current().nextInt(5, 80));
}
TableModel model = new DefaultTableModel(rowData, columnNames) {
public boolean isCellEditable(int row, int column) {
return column==0;
}
};
JTable table = new JTable(model);
table.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
label.setHorizontalAlignment(JLabel.RIGHT);
String string = (String)value;
final FontMetrics fontMetrics = label.getFontMetrics(label.getFont());
int width = fontMetrics.stringWidth(string);
int columnWidth = table.getColumnModel().getColumn(column).getWidth();
final Insets insets = label.getBorder().getBorderInsets(label);
columnWidth -= (insets.left+insets.right);
if ( width>=columnWidth && string.length()>0) {
String ellipsedString;
do {
string = string.substring(1);
ellipsedString = "\u2026" + string;
width = fontMetrics.stringWidth(ellipsedString);
} while( width>=columnWidth && string.length()>0 );
string = ellipsedString;
}
label.setText(string);
return label;
}
});
frame.add(new JScrollPane(table));
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static String createFakePath(int length) {
Path path = Paths.get("c:");
for(int i=0; i<length; i++) {
path = path.resolve("test");
}
return path.toString();
} |
Partager