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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
|
public class TableFeaturesDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(TableFeaturesDemo::createAndShowGUI);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("JTable Features Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
// Table data and columns
String[] columns = { "ID", "Name", "Age", "Department", "Role" };
Object[][] data = {
{ 1, "Alice", 30, "HR", "Manager" },
{ 2, "Bob", 24, "IT", "Developer" },
{ 3, "Charlie", 28, "Finance", "Analyst" },
{ 4, "Diana", 35, "IT", "Architect" },
};
DefaultTableModel tableModel = new DefaultTableModel(data, columns) {
@Override
public boolean isCellEditable(int row, int column) {
return column != 0; // Make ID column non-editable
}
};
JTable table = new JTable(tableModel);
// Add row sorter
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(tableModel);
table.setRowSorter(sorter);
// Set column widths
table.getColumnModel().getColumn(0).setPreferredWidth(50);
table.getColumnModel().getColumn(1).setPreferredWidth(150);
table.getColumnModel().getColumn(2).setPreferredWidth(50);
table.getColumnModel().getColumn(3).setPreferredWidth(150);
table.getColumnModel().getColumn(4).setPreferredWidth(150);
// Add table to scroll pane
JScrollPane scrollPane = new JScrollPane(table);
// Add TableModelListener
tableModel.addTableModelListener(e -> {
if (e.getType() == TableModelEvent.UPDATE) {
int row = e.getFirstRow();
int column = e.getColumn();
Object updatedValue = tableModel.getValueAt(row, column);
System.out.println("Updated value at row " + row + ", column " + column + ": " + updatedValue);
}
});
// Define a JComboBox for the "Department" column
String[] departments = { "HR", "IT", "Finance", "Marketing" };
JComboBox<String> departmentComboBox = new JComboBox<>(departments);
DefaultCellEditor departmentEditor = new DefaultCellEditor(departmentComboBox);
// Set the custom editor for the "Department" column
TableColumn departmentColumn = table.getColumnModel().getColumn(3);
departmentColumn.setCellEditor(departmentEditor);
// Add tooltips
table.setToolTipText("This is a JTable with various features");
table.getTableHeader().setToolTipText("This is a JTableHeader ");
// Add custom cell renderer
table.getColumnModel().getColumn(2).setCellRenderer(new DefaultTableCellRenderer() {
@Override
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);
if (value instanceof Integer && (Integer) value > 30) {
cell.setForeground(Color.RED);
} else {
cell.setForeground(Color.BLACK);
}
return cell;
}
});
// Add buttons for adding and deleting rows
JPanel buttonPanel = new JPanel(new BorderLayout());
JPanel controlPanel = new JPanel();
JPanel labelPanel = new JPanel();
JLabel selectionLabel = new JLabel("Selected Data: None");
labelPanel.add(selectionLabel);
JButton addRowButton = new JButton("Add Row");
JButton deleteRowButton = new JButton("Delete Row");
addRowButton.addActionListener(e -> {
Vector<Object> newRow = new Vector<>();
newRow.add(tableModel.getRowCount() + 1); // Auto ID
newRow.add("New Employee");
newRow.add(25);
newRow.add("Department");
newRow.add("Role");
tableModel.addRow(newRow);
});
deleteRowButton.addActionListener(e -> {
int selectedRow = table.getSelectedRow();
if (selectedRow != -1) {
tableModel.removeRow(table.convertRowIndexToModel(selectedRow));
} else {
JOptionPane.showMessageDialog(frame, "Please select a row to delete.", "Error",
JOptionPane.ERROR_MESSAGE);
}
});
// Add selection mode buttons
JButton singleSelectionButton = new JButton("Single Selection");
JButton contiguousSelectionButton = new JButton("Contiguous Selection");
JButton multipleSelectionButton = new JButton("Multiple Selection");
JLabel modeLabel = new JLabel("Selection Mode: Single");
controlPanel.add(modeLabel);
singleSelectionButton.addActionListener(e -> {
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modeLabel.setText("Selection Mode: Single");
});
contiguousSelectionButton.addActionListener(e -> {
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
modeLabel.setText("Selection Mode: Contiguous");
});
multipleSelectionButton.addActionListener(e -> {
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modeLabel.setText("Selection Mode: Multiple");
});
// Add selection listener to update label
table.getSelectionModel().addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) {
int[] selectedRows = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
StringBuilder selectedData = new StringBuilder();
for (int row : selectedRows) {
for (int column : selectedColumns) {
selectedData.append(table.getValueAt(row, column)).append(" ");
}
}
selectionLabel.setText("Selected Data: " + (selectedData.isEmpty() ? "None" : selectedData.toString()));
}
});
// Add a Print Table button
JButton printTableButton = new JButton("Print Table");
printTableButton.addActionListener(e -> {
try {
if (table.print(JTable.PrintMode.FIT_WIDTH)) {
JOptionPane.showMessageDialog(frame, "Table printed successfully.", "Print",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(frame, "Table print cancelled.", "Print",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Error occurred while printing: " + ex.getMessage(), "Print Error",
JOptionPane.ERROR_MESSAGE);
}
});
controlPanel.add(addRowButton);
controlPanel.add(deleteRowButton);
controlPanel.add(singleSelectionButton);
controlPanel.add(contiguousSelectionButton);
controlPanel.add(multipleSelectionButton);
controlPanel.add(printTableButton);
buttonPanel.add(controlPanel, BorderLayout.NORTH);
buttonPanel.add(labelPanel, BorderLayout.SOUTH);
// Add components to frame
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
|