-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathComboBoxTableEditorDemo.java
More file actions
88 lines (72 loc) · 2.45 KB
/
ComboBoxTableEditorDemo.java
File metadata and controls
88 lines (72 loc) · 2.45 KB
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
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class ComboBoxTableEditorDemo
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
// Build a table with data
Object[][] data =
{
{"Color", "Red"},
{"Fruit", "Banana"},
{"Shape", "Square"},
};
String[] columnNames = {"Type","Value"};
JTable table = new JTable(data, columnNames);
table.setRowHeight(table.getRowHeight() + 6);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
// Editor for first column
String[] items = { "Color", "Fruit", "Shape" };
DefaultCellEditor dce = new DefaultCellEditor(new JComboBox<String>(items));
table.getColumnModel().getColumn(0).setCellEditor(dce);
// Editor with multiple models for second column
JComboBox<String> comboBox = new JComboBox<>();
comboBox.setRenderer( new PromptComboBoxRenderer("Select Value") );
ComboBoxTableEditor editor = new ComboBoxTableEditor(comboBox, 0);
table.getColumnModel().getColumn(1).setCellEditor( editor );
String[] items1 = { "Red", "Blue", "Green" };
editor.addModel("Color", items1);
String[] items2 = { "Circle", "Square", "Triangle" };
editor.addModel("Shape", items2);
String[] items3 = { "Apple", "Orange", "Banana" };
editor.addModel("Fruit", items3);
// Reset second column when first column changes
// (replaces TableModelListener)
Action action = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
TableCellListener tcl = (TableCellListener)e.getSource();
int column = tcl.getColumn();
if (column == 0)
{
int row = tcl.getRow();
TableModel model = tcl.getTable().getModel();
model.setValueAt(null, row, 1);
}
}
};
TableCellListener tcl = new TableCellListener(table, action);
JFrame frame = new JFrame("Combo Box Table Editor");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( scrollPane );
frame.setSize(300, 200);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}