Skip to content

Commit 5902d77

Browse files
authored
Add files via upload
1 parent a945742 commit 5902d77

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import java.awt.*;
2+
import java.awt.event.*;
3+
import java.io.*;
4+
import java.util.ArrayList;
5+
import java.util.Vector;
6+
import javax.swing.*;
7+
import javax.swing.event.*;
8+
import javax.swing.table.*;
9+
10+
public class ComboBoxTableEditorDemo
11+
{
12+
public static void main(String[] args)
13+
{
14+
SwingUtilities.invokeLater(new Runnable() {
15+
public void run() {
16+
createAndShowGUI();
17+
}
18+
});
19+
}
20+
21+
public static void createAndShowGUI()
22+
{
23+
// Build a table with data
24+
25+
Object[][] data =
26+
{
27+
{"Color", "Red"},
28+
{"Fruit", "Banana"},
29+
{"Shape", "Square"},
30+
};
31+
String[] columnNames = {"Type","Value"};
32+
33+
JTable table = new JTable(data, columnNames);
34+
table.setRowHeight(table.getRowHeight() + 6);
35+
table.setPreferredScrollableViewportSize(table.getPreferredSize());
36+
JScrollPane scrollPane = new JScrollPane( table );
37+
38+
// Editor for first column
39+
40+
String[] items = { "Color", "Fruit", "Shape" };
41+
DefaultCellEditor dce = new DefaultCellEditor(new JComboBox<String>(items));
42+
table.getColumnModel().getColumn(0).setCellEditor(dce);
43+
44+
// Editor with multiple models for second column
45+
46+
JComboBox<String> comboBox = new JComboBox<>();
47+
comboBox.setRenderer( new PromptComboBoxRenderer("Select Value") );
48+
ComboBoxTableEditor editor = new ComboBoxTableEditor(comboBox, 0);
49+
table.getColumnModel().getColumn(1).setCellEditor( editor );
50+
51+
String[] items1 = { "Red", "Blue", "Green" };
52+
editor.addModel("Color", items1);
53+
54+
String[] items2 = { "Circle", "Square", "Triangle" };
55+
editor.addModel("Shape", items2);
56+
57+
String[] items3 = { "Apple", "Orange", "Banana" };
58+
editor.addModel("Fruit", items3);
59+
60+
// Reset second column when first column changes
61+
// (replaces TableModelListener)
62+
63+
Action action = new AbstractAction()
64+
{
65+
public void actionPerformed(ActionEvent e)
66+
{
67+
TableCellListener tcl = (TableCellListener)e.getSource();
68+
int column = tcl.getColumn();
69+
70+
if (column == 0)
71+
{
72+
int row = tcl.getRow();
73+
TableModel model = tcl.getTable().getModel();
74+
model.setValueAt(null, row, 1);
75+
}
76+
}
77+
};
78+
79+
TableCellListener tcl = new TableCellListener(table, action);
80+
81+
JFrame frame = new JFrame("Combo Box Table Editor");
82+
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
83+
frame.add( scrollPane );
84+
frame.setSize(300, 200);
85+
frame.setLocationRelativeTo( null );
86+
frame.setVisible(true);
87+
}
88+
}

0 commit comments

Comments
 (0)